From 8e9c0653dd6c6862123c9609ae34e1206d86456e Mon Sep 17 00:00:00 2001 From: talig Date: Wed, 20 Dec 2017 14:30:43 +0200 Subject: Add collaboration feature Issue-ID: SDC-767 Change-Id: I14fb4c1f54086ed03a56a7ff7fab9ecd40381795 Signed-off-by: talig --- .../sdc/ci/tests/utils/general/FileUtils.java | 10 +- .../sdc/generator/aai/AaiModelGenerator.java | 6 +- .../service/ArtifactGenerationService.java | 4 +- .../sdc/generator/aai/AaiArtifactGenerator.java | 2 +- .../sdc/generator/aai/AaiModelGeneratorImpl.java | 4 - .../sdc/generator/util/ArtifactGeneratorUtil.java | 2 +- .../generator/ArtifactGenerationServiceTest.java | 608 ++++++------ .../openecomp/sdc/generator/SampleJUnitTest.java | 217 ++--- onboarding/pom.xml | 14 +- .../action/rest/ActionsForSwaggerFileUpload.java | 2 +- .../sdcrests/action/rest/services/ActionsImpl.java | 90 +- .../activity-log-rest-services/pom.xml | 58 -- .../sdcrests/activitylog/rest/ActivityLog.java | 55 -- .../MapActivityLogEntityToActivityLogDto.java | 40 - .../activitylog/rest/services/ActivityLogImpl.java | 65 -- .../activity-log-rest-types/pom.xml | 15 - .../sdcrests/activitylog/types/ActivityLogDto.java | 81 -- .../sdcrests/activitylog/types/ActivityStatus.java | 54 - .../sdcrests/activitylog/types/ActivityType.java | 53 - .../activity-log-rest/pom.xml | 22 - .../rest/ApplicationConfiguration.java | 2 +- .../services/ApplicationConfigurationImpl.java | 4 +- .../conflict-rest/conflict-rest-services/pom.xml | 58 ++ .../sdcrests/conflict/rest/Conflicts.java | 61 ++ .../rest/mapping/MapConflictInfoToDto.java | 14 + .../conflict/rest/mapping/MapConflictToDto.java | 134 +++ .../rest/mapping/MapDtoToConflictResolution.java | 15 + .../rest/mapping/MapItemVersionConflictToDto.java | 22 + .../conflict/rest/services/ConflictsImpl.java | 62 ++ .../conflict-rest/conflict-rest-types/pom.xml | 22 + .../sdcrests/conflict/types/ConflictDto.java | 24 + .../sdcrests/conflict/types/ConflictInfoDto.java | 33 + .../conflict/types/ConflictResolutionDto.java | 27 + .../conflict/types/ItemVersionConflictDto.java | 29 + .../conflict-rest/pom.xml | 35 + .../sdcrests/health/rest/HealthCheck.java | 10 +- .../health/rest/services/HealthCheckImpl.java | 81 +- .../item-permissions-rest-services/pom.xml | 68 ++ .../itempermissions/rest/ItemPermissions.java | 53 + .../MapItemPermissionsToItemPermissionsDto.java | 20 + .../rest/services/ItemPermissionsImpl.java | 52 + .../item-permissions-rest-types/pom.xml | 24 + .../itempermissions/types/ItemPermissionsDto.java | 27 + .../types/ItemPermissionsRequestDto.java | 32 + .../item-permissions-rest/pom.xml | 24 + .../item-rest/item-rest-services/pom.xml | 55 ++ .../org/openecomp/sdcrests/item/rest/Versions.java | 88 ++ .../rest/mapping/MapActivityLogEntityToDto.java | 41 + .../sdcrests/item/rest/mapping/MapItemToDto.java | 15 + .../item/rest/mapping/MapRevisionToDto.java | 15 + .../item/rest/mapping/MapVersionToDto.java | 20 + .../sdcrests/item/rest/services/VersionsImpl.java | 270 +++++ .../item-rest/item-rest-types/pom.xml | 34 + .../sdcrests/item/types/ActivityLogDto.java | 85 ++ .../sdcrests/item/types/ActivityStatus.java | 54 + .../sdcrests/item/types/CommitRequestDto.java | 13 + .../sdcrests/item/types/ItemCreationDto.java | 22 + .../org/openecomp/sdcrests/item/types/ItemDto.java | 40 + .../openecomp/sdcrests/item/types/RevisionDto.java | 43 + .../sdcrests/item/types/RevisionRequestDto.java | 14 + .../sdcrests/item/types/SubmitRequestDto.java | 13 + .../sdcrests/item/types/VersionAction.java | 28 + .../item/types/VersionActionRequestDto.java | 52 + .../openecomp/sdcrests/item/types/VersionDto.java | 94 ++ .../sdcrests/item/types/VersionRequestDto.java | 24 + .../openecomp-sdc-rest-webapp/item-rest/pom.xml | 22 + .../notifications-fe/pom.xml | 161 +++ .../listeners/OnboardingAppStartupListener.java | 43 + .../src/main/resources/keyfile.txt | 27 + .../src/main/webapp/WEB-INF/beans-services.xml | 67 ++ .../src/main/webapp/WEB-INF/jetty-web.xml | 8 + .../main/webapp/WEB-INF/spring-mapper-servlet.xml | 12 + .../src/main/webapp/WEB-INF/web.xml | 81 ++ .../notifications-rest-services/pom.xml | 56 ++ .../rest/mapping/MapNotificationsStatusToDto.java | 64 ++ .../rest/mapping/MapNotificationsToDto.java | 57 ++ .../notifications/rest/services/Notifications.java | 94 ++ .../rest/services/impl/NotificationsImpl.java | 117 +++ .../notifications-rest-types/pom.xml | 23 + .../notifications/types/NotificationEntityDto.java | 91 ++ .../types/NotificationResponseStatus.java | 26 + .../types/NotificationsStatusDto.java | 61 ++ .../types/UpdateNotificationResponseStatus.java | 65 ++ .../notifications-rest/pom.xml | 24 + .../onboarding-rest-war/pom.xml | 32 +- .../server/filters/ActionAuthenticationFilter.java | 6 +- .../server/filters/ActionAuthorizationFilter.java | 2 +- .../server/filters/SessionContextFilter.java | 45 + .../src/main/webapp/WEB-INF/beans-services.xml | 23 +- .../main/webapp/WEB-INF/spring-mapper-servlet.xml | 13 + .../src/main/webapp/WEB-INF/web.xml | 34 +- .../openecomp/sdcrests/common/RestConstants.java | 4 +- .../sdcrests/common/types/VersionDto.java | 34 - .../openecomp/sdcrests/mapping/EchoMapMapping.java | 14 + .../openecomp/sdcrests/mapping/EchoMapping.java | 8 + .../openecomp/sdcrests/mapping/MappingBase.java | 6 - openecomp-be/api/openecomp-sdc-rest-webapp/pom.xml | 6 +- .../sdcrests/validation/rest/Validation.java | 2 +- .../validation/rest/ValidationForSwaggerUsage.java | 2 +- .../validation/rest/services/ValidationImpl.java | 4 +- .../vendor-license-rest-services/pom.xml | 17 +- .../vendorlicense/rest/EntitlementPoolLimits.java | 46 +- .../sdcrests/vendorlicense/rest/FeatureGroups.java | 6 +- .../vendorlicense/rest/LicenseKeyGroupLimits.java | 33 +- .../vendorlicense/rest/VendorLicenseModels.java | 124 +-- .../mapping/MapVendorLicenseModelEntityToDto.java | 36 + ...rLicenseModelToVendorLicenseModelEntityDto.java | 64 -- .../rest/services/EntitlementPoolLimitsImpl.java | 113 +-- .../rest/services/EntitlementPoolsImpl.java | 20 +- .../rest/services/FeatureGroupsImpl.java | 16 +- .../rest/services/LicenseAgreementsImpl.java | 35 +- .../rest/services/LicenseKeyGroupLimitsImpl.java | 116 +-- .../rest/services/LicenseKeyGroupsImpl.java | 16 +- .../rest/services/VendorLicenseModelsImpl.java | 348 +++++-- .../vendor-license-rest-types/pom.xml | 24 +- .../vendorlicense/types/FeatureGroupEntityDto.java | 2 +- .../types/LicenseAgreementEntityDto.java | 2 +- .../vendorlicense/types/MultiChoiceOrOtherDto.java | 2 +- .../types/VendorLicenseModelActionRequestDto.java | 21 +- .../types/VendorLicenseModelEntityDto.java | 49 - .../sdcrests/vsp/rest/ComponentDependencies.java | 87 ++ .../vsp/rest/ComponentDependencyModels.java | 50 - .../sdcrests/vsp/rest/ComponentProcesses.java | 10 +- .../org/openecomp/sdcrests/vsp/rest/Compute.java | 6 +- .../sdcrests/vsp/rest/DeploymentFlavors.java | 6 +- .../org/openecomp/sdcrests/vsp/rest/Images.java | 6 +- .../java/org/openecomp/sdcrests/vsp/rest/Nics.java | 6 +- .../vsp/rest/OrchestrationTemplateCandidate.java | 3 +- .../org/openecomp/sdcrests/vsp/rest/Processes.java | 6 +- .../sdcrests/vsp/rest/VendorSoftwareProducts.java | 36 +- ...VendorSoftwareProductsForSwaggerFileUpload.java | 7 +- .../openecomp/sdcrests/vsp/rest/VspEntities.java | 21 - .../MapComponentDependencyEntityToCreationDto.java | 16 + .../mapping/MapComponentDependencyEntityToDto.java | 18 + .../MapComputeDetailsDtoToComputeEntity.java | 2 +- .../rest/mapping/MapFilesDataStructureToDto.java | 17 + ...StructureToGetFileDataStructureResponseDto.java | 40 - .../vsp/rest/mapping/MapImageDataToImageDto.java | 1 - .../vsp/rest/mapping/MapItemToVspDetailsDto.java | 18 + .../mapping/MapPackageInfoToPackageInfoDto.java | 2 +- .../MapQuestionnaireToQuestionnaireDto.java | 21 + .../rest/mapping/MapValidationResponseToDto.java | 33 +- ...edVendorSoftwareProductInfoToVspDetailsDto.java | 83 -- .../rest/mapping/MapVspDescriptionDtoToItem.java | 16 + .../mapping/MapVspDescriptionDtoToVspDetails.java | 13 +- .../vsp/rest/mapping/MapVspDetailsToDto.java | 53 + .../mapping/MapVspDetailsToVspCreationDto.java | 32 - .../rest/services/ComponentDependenciesImpl.java | 119 +++ .../services/ComponentDependencyModelsImpl.java | 78 -- .../services/ComponentMonitoringUploadsImpl.java | 23 +- .../vsp/rest/services/ComponentProcessesImpl.java | 77 +- .../sdcrests/vsp/rest/services/ComponentsImpl.java | 45 +- .../sdcrests/vsp/rest/services/ComputeImpl.java | 88 +- .../vsp/rest/services/DeploymentFlavorsImpl.java | 43 +- .../sdcrests/vsp/rest/services/ImagesImpl.java | 85 +- .../sdcrests/vsp/rest/services/NetworksImpl.java | 24 +- .../sdcrests/vsp/rest/services/NicsImpl.java | 60 +- .../OrchestrationTemplateCandidateImpl.java | 71 +- .../sdcrests/vsp/rest/services/ProcessesImpl.java | 36 +- .../rest/services/VendorSoftwareProductsImpl.java | 582 +++++++---- .../vsp/rest/services/VspItemProperty.java | 7 + .../vendor-software-products-rest-types/pom.xml | 5 + .../types/ComponentDependencyCreationDto.java | 13 + .../types/ComponentDependencyResponseDto.java | 41 + .../types/DeploymentFlavorRequestDto.java | 2 +- .../types/FileDataStructureDto.java | 69 ++ .../types/OnboardingMethod.java | 6 - .../types/QuestionnaireDto.java | 30 + .../types/VendorSoftwareProductAction.java | 3 - .../VersionSoftwareProductActionRequestDto.java | 11 + .../types/VspCreationDto.java | 36 - .../types/VspDescriptionDto.java | 36 +- .../types/VspDetailsDto.java | 63 +- .../types/VspRequestDto.java | 16 + .../types/validation/IsValidJson.java | 16 +- .../types/validation/StringValidator.java | 4 +- .../types/validation/ValidateString.java | 12 +- .../sdc/action/impl/ActionManagerImpl.java | 92 +- .../java/org/openecomp/sdc/action/ActionTest.java | 51 - .../openecomp-sdc-activity-log-manager/pom.xml | 5 - .../sdc/activityLog/ActivityLogManager.java | 31 - .../sdc/activityLog/ActivityLogManagerFactory.java | 31 - .../impl/ActivityLogManagerFactoryImpl.java | 33 - .../activityLog/impl/ActivityLogManagerImpl.java | 53 - .../sdc/activitylog/ActivityLogManager.java | 33 + .../sdc/activitylog/ActivityLogManagerFactory.java | 30 + .../impl/ActivityLogManagerFactoryImpl.java | 34 + .../activitylog/impl/ActivityLogManagerImpl.java | 52 + .../src/main/resources/factoryConfiguration.json | 2 +- .../ApplicationConfigManagerTest.java | 7 - .../backend/openecomp-sdc-conflict-manager/pom.xml | 34 + .../openecomp/sdc/conflicts/ConflictsManager.java | 20 + .../sdc/conflicts/ConflictsManagerFactory.java | 30 + .../impl/ConflictsManagerFactoryImpl.java | 35 + .../sdc/conflicts/impl/ConflictsManagerImpl.java | 112 +++ .../src/main/resources/factoryConfiguration.json | 3 + .../openecomp-sdc-healthcheck-manager/pom.xml | 5 - .../health/impl/HealthCheckManagerFactoryImpl.java | 3 +- .../sdc/health/impl/HealthCheckManagerImpl.java | 4 +- .../openecomp-sdc-item-permissions-manager/pom.xml | 71 ++ .../itempermissions/ItemPermissionsManager.java | 23 + .../ItemPermissionsManagerFactory.java | 15 + .../impl/ItemPermissionsManagerFactoryImpl.java | 25 + .../dao/impl/ItemPermissionsManagerImpl.java | 159 +++ .../src/main/resources/factoryConfiguration.json | 3 + .../dao/impl/ItemPermissionsManagerImplTest.java | 86 ++ .../src/test/resources/logback.xml | 15 + .../impl/UploadValidationManagerImpl.java | 2 +- .../sdc/validation/util/ValidationManagerUtil.java | 2 +- .../sdc/vendorlicense/VendorLicenseManager.java | 79 +- .../impl/VendorLicenseManagerFactoryImpl.java | 6 +- .../impl/VendorLicenseManagerImpl.java | 773 +++++---------- .../sdc/vendorlicense/ArtifactTestUtils.java | 35 - .../org/openecomp/sdc/vendorlicense/LimitTest.java | 117 ++- .../vendorlicense/VendorLicenseFacadeImplTest.java | 34 - .../vendorlicense/impl/EntitlementPoolTest.java | 597 ++++++------ .../sdc/vendorlicense/impl/FeatureGroupTest.java | 499 +++++----- .../vendorlicense/impl/LicenseAgreementTest.java | 101 +- .../vendorlicense/impl/LicenseKeyGroupTest.java | 161 ++- .../vendorlicense/impl/VendorLicenseModelTest.java | 221 +---- .../impl/VendorLicenseArtifactsServiceTest.java | 14 - .../ComponentDependencyModelManager.java | 13 +- .../vendorsoftwareproduct/ComponentManager.java | 19 +- .../sdc/vendorsoftwareproduct/ComputeManager.java | 23 +- .../DeploymentFlavorManager.java | 20 +- .../sdc/vendorsoftwareproduct/ImageManager.java | 20 +- .../ManualVspToscaManager.java | 4 +- .../MonitoringUploadsManager.java | 7 +- .../sdc/vendorsoftwareproduct/NetworkManager.java | 11 +- .../sdc/vendorsoftwareproduct/NicManager.java | 14 +- .../OrchestrationTemplateCandidateManager.java | 13 +- .../sdc/vendorsoftwareproduct/ProcessManager.java | 23 +- .../VendorSoftwareProductManager.java | 44 +- .../ComponentDependencyModelErrorBuilder.java | 14 +- .../DuplicateComputeInComponentErrorBuilder.java | 31 +- .../errors/ImageErrorBuilder.java | 6 +- .../errors/MonitoringUploadErrorBuilder.java | 5 +- .../errors/NicInternalNetworkErrorBuilder.java | 6 +- .../NotSupportedHeatOnboardMethodErrorBuilder.java | 6 +- .../errors/OnboardingMethodErrorBuilder.java | 24 +- .../TranslationFileCreationErrorBuilder.java | 4 +- .../VendorSoftwareProductInvalidErrorBuilder.java | 8 +- ...ComponentDependencyModelManagerFactoryImpl.java | 9 +- .../impl/ComponentDependencyModelManagerImpl.java | 119 ++- .../impl/ComponentManagerImpl.java | 79 +- .../impl/ComputeManagerFactoryImpl.java | 6 +- .../impl/ComputeManagerImpl.java | 390 +++----- .../impl/DeploymentFlavorManagerImpl.java | 123 +-- .../impl/ImageManagerImpl.java | 211 ++-- .../impl/ManualVspToscaManagerImpl.java | 21 +- .../impl/MonitoringUploadsManagerFactoryImpl.java | 4 +- .../impl/MonitoringUploadsManagerImpl.java | 37 +- .../impl/NetworkManagerImpl.java | 20 +- .../vendorsoftwareproduct/impl/NicManagerImpl.java | 79 +- ...trationTemplateCandidateManagerFactoryImpl.java | 25 +- .../OrchestrationTemplateCandidateManagerImpl.java | 172 +--- .../impl/ProcessManagerFactoryImpl.java | 7 +- .../impl/ProcessManagerImpl.java | 201 ++-- .../impl/VendorSoftwareProductManagerImpl.java | 747 ++++---------- .../impl/VspManagerFactoryImpl.java | 16 +- .../BaseOrchestrationTemplateHandler.java | 149 +-- .../OrchestrationTemplateCSARHandler.java | 228 ++--- .../OrchestrationTemplateFileHandler.java | 8 +- .../OrchestrationTemplateZipHandler.java | 70 +- .../orchestration/OrchestrationUploadFactory.java | 4 +- .../impl/orchestration/OrchestrationUtil.java | 271 +++--- .../impl/orchestration/csar/CSARConstants.java | 1 + .../orchestration/csar/OnboardingManifest.java | 16 +- .../process/OrchestrationProcessFactory.java | 8 +- .../OrchestrationTemplateProcessCsarHandler.java | 73 +- .../OrchestrationTemplateProcessHandler.java | 4 +- .../OrchestrationTemplateProcessZipHandler.java | 82 +- .../types/FileDataStructureDto.java | 69 -- .../types/GetFileDataStructureResponseDTO.java | 69 -- .../sdc/vendorsoftwareproduct/ComputeTest.java | 28 - .../DeploymentFlavorTest.java | 28 - .../sdc/vendorsoftwareproduct/ImagesTest.java | 158 ++- .../QuestionnaireDataServiceTest.java | 34 +- .../impl/ComponentDependencyModelTest.java | 231 +++-- .../impl/ComponentManagerImplTest.java | 135 ++- .../impl/ComputeManagerImplTest.java | 532 +++++----- .../impl/DeplomentFlavorManagerImplTest.java | 463 --------- .../impl/DeploymentFlavorManagerImplTest.java | 171 ++-- .../impl/ImageManagerImplTest.java | 154 ++- .../impl/ManualVspToscaManagerImplTest.java | 98 +- .../impl/MonitoringUploadsManagerImplTest.java | 34 +- .../impl/NetworkManagerImplTest.java | 65 +- .../impl/NicManagerImplTest.java | 151 +-- ...hestrationTemplateCandidateManagerImplTest.java | 60 +- ...rchestrationTemplateProcessCsarHandlerTest.java | 46 +- .../impl/ProcessManagerImplTest.java | 119 +-- .../impl/VendorSoftwareProductManagerImplTest.java | 603 ++++++------ .../mock/VendorSoftwareProductDaoFactoryMock.java | 12 - .../services/impl/CandidateServiceImplTest.java | 17 +- .../CompositionDataExtractorImplTest.java | 7 +- .../CompositionEntityDataManagerImplTest.java | 11 +- .../schemagenerator/SchemaGeneratorTest.java | 21 - .../vendorsoftwareproduct/tree/UploadFileTest.java | 139 ++- .../HeatCleanup/HeatCleanupOnNewUploadTest.java | 2 +- .../upload/csar/ManifestParsingTest.java | 81 +- .../upload/csar/UploadCSARFileTest.java | 293 +++--- openecomp-be/backend/pom.xml | 2 + .../org/openecomp/sdc/common/errors/Messages.java | 8 +- .../sdc/common/errors/SdcRuntimeException.java | 42 + .../org/openecomp/sdc/common/utils/SdcCommon.java | 1 + .../openecomp-conflict-api/pom.xml | 38 + .../org/openecomp/conflicts/ItemMergeHandler.java | 27 + .../conflicts/ItemMergeHandlerFactory.java | 16 + .../org/openecomp/conflicts/dao/ConflictsDao.java | 18 + .../conflicts/dao/ConflictsDaoFactory.java | 32 + .../org/openecomp/conflicts/types/Conflict.java | 30 + .../openecomp/conflicts/types/ConflictInfo.java | 39 + .../conflicts/types/ConflictResolution.java | 32 + .../conflicts/types/ItemVersionConflict.java | 31 + .../org/openecomp/conflicts/types/Resolution.java | 5 + .../openecomp-conflict-core/pom.xml | 36 + .../conflicts/ItemMergeHandlerFactoryImpl.java | 40 + .../dao/impl/zusammen/ConflictsDaoFactoryImpl.java | 17 + .../dao/impl/zusammen/ConflictsDaoImpl.java | 175 ++++ .../ItemVersionConflictConvertorFromZusammen.java | 73 ++ .../openecomp/conflicts/impl/VspMergeHandler.java | 204 ++++ .../src/main/resources/factoryConfiguration.json | 4 + openecomp-be/lib/openecomp-conflict-lib/pom.xml | 20 + .../dao/ApplicationConfigImplDaoTest.java | 17 - .../core/factory/impl/AbstractFactoryBase.java | 6 +- .../org/openecomp/core/util/UniqueValueUtil.java | 33 +- .../impl/cassandra/CassandraNoSqlDbImpl.java | 6 +- .../org/openecomp/core/nosqldb/NoSqlDbTest.java | 7 - .../nosqldb/util/ConfigurationManagerTest.java | 2 +- .../openecomp-session-lib/pom.xml | 30 + .../sdc/common/session/SessionContext.java | 8 + .../sdc/common/session/SessionContextProvider.java | 10 + .../session/SessionContextProviderFactory.java | 32 + .../org/openecomp/sdc/common/session/User.java | 13 + .../session/impl/AsdcSessionContextProvider.java | 50 + .../impl/SessionContextProviderFactoryImpl.java | 33 + .../src/main/resources/factoryConfiguration.json | 3 + .../openecomp/core/utilities/file/FileUtils.java | 3 - .../utilities/file/FileContentHandlerTest.java | 4 +- .../openecomp-zusammen-api/pom.xml | 15 + .../org/openecomp/convertor/ElementConvertor.java | 37 + .../core/zusammen/api/ZusammenAdaptor.java | 73 +- .../openecomp/core/zusammen/api/ZusammenUtil.java | 38 +- .../main/java/org/openecomp/types/AsdcElement.java | 131 +++ .../org/openecomp/types/ElementPropertyName.java | 6 + .../core/zusammen/db/ZusammenConnector.java | 52 +- .../zusammen/db/impl/ZusammenConnectorImpl.java | 260 ++++- .../core/zusammen/impl/ZusammenAdaptorImpl.java | 219 +++-- .../openecomp-zusammen-plugin/pom.xml | 27 + .../core/zusammen/plugin/ZusammenPluginUtil.java | 222 ++++- .../plugin/collaboration/CommitStagingService.java | 100 ++ .../collaboration/ElementCollaborationStore.java | 119 --- .../plugin/collaboration/ElementPrivateStore.java | 48 + .../plugin/collaboration/ElementPublicStore.java | 23 + .../plugin/collaboration/ElementStageStore.java | 35 + .../plugin/collaboration/ElementStore.java | 20 + .../zusammen/plugin/collaboration/ErrorCode.java | 5 + .../zusammen/plugin/collaboration/Message.java | 6 + .../plugin/collaboration/PublishService.java | 201 ++++ .../plugin/collaboration/RevertService.java | 161 +++ .../zusammen/plugin/collaboration/SyncService.java | 384 ++++++++ .../collaboration/VersionCollaborationStore.java | 110 --- .../plugin/collaboration/VersionPrivateStore.java | 38 + .../plugin/collaboration/VersionPublicStore.java | 29 + .../plugin/collaboration/VersionStageStore.java | 18 + .../impl/ElementPrivateStoreImpl.java | 269 +++++ .../collaboration/impl/ElementPublicStoreImpl.java | 189 ++++ .../collaboration/impl/ElementStageStoreImpl.java | 133 +++ .../impl/VersionPrivateStoreImpl.java | 117 +++ .../collaboration/impl/VersionPublicStoreImpl.java | 135 +++ .../collaboration/impl/VersionStageStoreImpl.java | 39 + .../zusammen/plugin/dao/ElementRepository.java | 29 +- .../plugin/dao/ElementStageRepository.java | 34 + .../plugin/dao/ElementStageRepositoryFactory.java | 14 + .../dao/ElementSynchronizationStateRepository.java | 21 + ...ementSynchronizationStateRepositoryFactory.java | 14 + .../core/zusammen/plugin/dao/StageRepository.java | 15 + .../plugin/dao/SynchronizationStateRepository.java | 16 + .../core/zusammen/plugin/dao/VersionDao.java | 29 + .../zusammen/plugin/dao/VersionDaoFactory.java | 13 + .../plugin/dao/VersionStageRepository.java | 9 + .../plugin/dao/VersionStageRepositoryFactory.java | 13 + .../dao/VersionSynchronizationStateRepository.java | 18 + ...rsionSynchronizationStateRepositoryFactory.java | 14 + .../plugin/dao/impl/CassandraDaoUtils.java | 27 - .../dao/impl/CassandraElementRepository.java | 375 ------- .../impl/CassandraElementRepositoryFactory.java | 31 - .../dao/impl/cassandra/CassandraDaoUtils.java | 27 + .../cassandra/ElementRepositoryFactoryImpl.java | 31 + .../dao/impl/cassandra/ElementRepositoryImpl.java | 565 +++++++++++ .../ElementStageRepositoryFactoryImpl.java | 31 + .../impl/cassandra/ElementStageRepositoryImpl.java | 423 ++++++++ ...tSynchronizationStateRepositoryFactoryImpl.java | 33 + .../ElementSynchronizationStateRepositoryImpl.java | 209 ++++ .../dao/impl/cassandra/VersionDaoFactoryImpl.java | 15 + .../plugin/dao/impl/cassandra/VersionDaoImpl.java | 185 ++++ .../VersionStageRepositoryFactoryImpl.java | 15 + .../impl/cassandra/VersionStageRepositoryImpl.java | 82 ++ ...nSynchronizationStateRepositoryFactoryImpl.java | 33 + .../VersionSynchronizationStateRepositoryImpl.java | 137 +++ .../zusammen/plugin/dao/types/ElementEntity.java | 22 +- .../zusammen/plugin/dao/types/StageEntity.java | 60 ++ .../dao/types/SynchronizationStateEntity.java | 116 +++ .../zusammen/plugin/dao/types/VersionContext.java | 23 + .../plugin/dao/types/VersionDataElement.java | 21 + .../zusammen/plugin/dao/types/VersionEntity.java | 45 + .../CassandraCollaborationStorePluginImpl.java | 441 ++++++++- .../plugin/main/CassandraStateStorePluginImpl.java | 114 ++- .../src/main/resources/factoryConfiguration.json | 7 +- .../zusammen/plugin/collaboration/TestUtils.java | 64 ++ .../VersionCollaborationStoreTest.java | 237 +++++ .../impl/ElementStageStoreImplTest.java | 167 ++++ openecomp-be/lib/openecomp-core-lib/pom.xml | 1 + .../openecomp-sdc-healing-api/pom.xml | 22 + .../openecomp/sdc/healing/api/HealingManager.java | 14 +- .../org/openecomp/sdc/healing/dao/HealingDao.java | 13 + .../sdc/healing/factory/HealingManagerFactory.java | 2 +- .../openecomp/sdc/healing/interfaces/Healer.java | 4 +- .../sdc/healing/types/ConfigConstants.java | 5 + .../openecomp/sdc/healing/types/HealerType.java | 6 + .../sdc/healing/types/HealingContext.java | 41 - .../sdc/healing/dao/impl/HealingDaoImpl.java | 46 + .../healing/impl/HealingManagerFactoryImpl.java | 6 +- .../sdc/healing/impl/HealingManagerImpl.java | 189 +++- .../main/resources/entityHealingConfiguration.json | 12 + .../src/main/resources/healingConfiguration.json | 28 +- .../openecomp-sdc-healing-impl/pom.xml | 5 + .../healers/ComponentQuestionnaireHealer.java | 10 +- .../sdc/healing/healers/CompositionDataHealer.java | 30 +- .../healing/healers/FileDataStructureHealer.java | 83 +- .../healing/healers/ForwarderCapabilityHealer.java | 6 +- .../healers/HeatToToscaTranslationHealer.java | 29 +- .../sdc/healing/healers/NicDataHealer.java | 10 +- .../openecomp/sdc/healing/healers/OwnerHealer.java | 47 + .../healers/SubEntitiesQuestionnaireHealer.java | 15 +- .../healing/healers/ValidationStructureHealer.java | 250 ++--- .../sdc/healing/healers/VlmVersionHealer.java | 69 +- .../healing/healers/VspOnboardingMethodHealer.java | 94 +- .../healing/healers/VspQuestionnaireHealer.java | 7 +- .../healers/ComponentQuestionnaireHealerTest.java | 16 +- .../healers/ForwarderCapabilityHealerTest.java | 8 +- .../healers/VspOnboardingMethodHealerTest.java | 108 +- .../testHealers/data/TestDescriptionHealer.java | 16 + .../structure/TestNewEntityInVspHealer.java | 16 + .../openecomp-item-permissions-api/pom.xml | 32 + .../sdc/itempermissions/PermissionsRules.java | 17 + .../itempermissions/PermissionsRulesFactory.java | 16 + .../sdc/itempermissions/PermissionsServices.java | 26 + .../PermissionsServicesFactory.java | 16 + .../itempermissions/dao/ItemPermissionsDao.java | 21 + .../dao/ItemPermissionsDaoFactory.java | 15 + .../errors/PermissionsErrorMessages.java | 23 + .../errors/PermissionsErrorMessagesBuilder.java | 29 + .../notifications/NotificationConstants.java | 14 + .../type/ItemPermissionsEntity.java | 50 + .../openecomp-item-permissions-core/pom.xml | 63 ++ .../dao/impl/ItemPermissionsDaoFactoryImpl.java | 19 + .../dao/impl/ItemPermissionsDaoImpl.java | 66 ++ .../dao/impl/PermissionsServicesImpl.java | 70 ++ .../dao/impl/PrmissionsServicesFactoryImpl.java | 21 + .../itempermissions/servlet/PermissionsFilter.java | 72 ++ .../src/main/resources/factoryConfiguration.json | 4 + .../dao/impl/PermissionsServicesImplTest.java | 111 +++ .../openecomp-item-permissions-impl/pom.xml | 27 + .../impl/PermissionsRulesFactoryImpl.java | 16 + .../itempermissions/impl/PermissionsRulesImpl.java | 126 +++ .../impl/types/PermissionActionTypes.java | 14 + .../impl/types/PermissionTypes.java | 9 + .../src/main/resources/factoryConfiguration.json | 3 + .../impl/PermissionsRulesImplTest.java | 101 ++ .../src/test/resources/logback.xml | 15 + .../lib/openecomp-item-permissions-lib/pom.xml | 24 + .../sdc/action/errors/ActionExceptionMapper.java | 8 +- .../org/openecomp/sdc/action/util/ActionUtil.java | 24 +- .../sdc/action/dao/impl/ActionArtifactDaoImpl.java | 16 +- .../sdc/action/dao/impl/ActionDaoImpl.java | 52 +- .../sdc/activitylog/dao/ActivityLogDao.java | 4 - .../sdc/activitylog/dao/ActivityLogDaoFactory.java | 2 +- .../activitylog/dao/type/ActivityLogEntity.java | 217 +++-- .../sdc/activitylog/dao/type/ActivityType.java | 13 + .../dao/impl/ActivityLogDaoCassandraImpl.java | 82 +- .../dao/impl/ActivityLogDaoFactoryImpl.java | 10 +- .../openecomp/sdc/datatypes/model/ElementType.java | 31 + .../openecomp/sdc/datatypes/model/ItemType.java | 6 + .../sdc/enrichment/impl/EnrichmentManagerImpl.java | 4 +- .../enrichment/impl/EnrichmentManagerImplTest.java | 4 +- .../sdc/enrichment/impl/EnricherHandlerImpl.java | 4 +- .../external/artifact/ProcessArtifactEnricher.java | 34 +- .../artifact/VspInformationArtifactEnricher.java | 21 +- .../impl/tosca/ComponentQuestionnaireData.java | 38 +- .../impl/tosca/PortMirroringEnricher.java | 8 +- .../sdc/enrichment/impl/tosca/ToscaEnricher.java | 24 +- .../inter/ExternalArtifactEnricherInterface.java | 2 +- .../artifact/MonitoringMibEnricherTest.java | 5 +- .../artifact/ProcessArtifactEnricherTest.java | 41 +- .../impl/tosca/BaseToscaEnrichmentTest.java | 10 +- .../impl/tosca/ComponentQuestionnaireDataTest.java | 26 - .../impl/tosca/PortMirroringEnricherTest.java | 2 - .../sdc/logging/types/LoggerServiceName.java | 10 +- .../sdc/logging/types/LoggerTragetServiceName.java | 2 + .../sdc/logging/api/LoggerFactoryTest.java | 4 +- .../sdc/logging/api/context/TaskFactoryTest.java | 4 +- .../sdc/logging/servlet/LoggingFilter.java | 12 +- .../logging/context/MDCPropagationFactoryTest.java | 4 +- .../sdc/logging/servlet/LoggingFilterTest.java | 8 +- .../core/model/dao/EnrichedServiceModelDao.java | 3 - .../model/types/EnrichedServiceArtifactEntity.java | 4 +- .../model/types/EnrichedServiceTemplateEntity.java | 4 +- .../core/model/types/ServiceArtifactEntity.java | 3 +- .../core/model/types/ServiceTemplateEntity.java | 4 +- .../model/impl/EnrichedServiceModelDaoImpl.java | 3 - .../EnrichedServiceModelDaoZusammenImpl.java | 29 +- .../impl/zusammen/ServiceModelDaoZusammenImpl.java | 243 +++-- .../openecomp-sdc-notification-api/pom.xml | 20 + .../destinationprovider/DestinationProvider.java | 11 + .../sdc/notification/dao/LastNotificationDao.java | 34 + .../sdc/notification/dao/NotificationsDao.java | 49 + .../sdc/notification/dao/SubscribersDao.java | 37 + .../dao/types/LastSeenNotificationEntity.java | 103 ++ .../notification/dao/types/NotificationEntity.java | 188 ++++ .../notification/dao/types/SubscribersEntity.java | 68 ++ .../org/openecomp/sdc/notification/dtos/Event.java | 14 + .../sdc/notification/dtos/NotificationsStatus.java | 24 + .../exceptons/NotificationNotExistException.java | 18 + .../factories/LastNotificationDaoFactory.java | 34 + .../NotificationPropagationManagerFactory.java | 15 + .../factories/NotificationsDaoFactory.java | 34 + .../factories/NotificationsServiceFactory.java | 34 + .../factories/PropagationServiceFactory.java | 15 + .../factories/SubscribersDaoFactory.java | 34 + .../factories/SubscriptionServiceFactory.java | 34 + .../services/NotificationPropagationManager.java | 12 + .../services/NotificationsService.java | 31 + .../notification/services/PropagationService.java | 9 + .../notification/services/SubscriptionService.java | 15 + .../openecomp-sdc-notification-core/pom.xml | 42 + .../impl/MulticastDestination.java | 44 + .../impl/UnicastDestination.java | 23 + .../dao/impl/LastNotificationDaoCassandraImpl.java | 87 ++ .../dao/impl/NotificationsDaoCassandraImpl.java | 287 ++++++ .../dao/impl/SubscribersDaoCassandraImpl.java | 104 ++ .../impl/LastNotificationDaoFactoryImpl.java | 19 + .../NotificationPropagationManagerFactoryImpl.java | 19 + .../impl/NotificationsDaoFactoryImpl.java | 18 + .../impl/NotificationsServiceFactoryImpl.java | 22 + .../impl/PropagationServiceFactoryImpl.java | 16 + .../factories/impl/SubscribersDaoFactoryImpl.java | 15 + .../impl/SubscriptionServiceFactoryImpl.java | 17 + .../impl/NotificationPropagationManagerImpl.java | 35 + .../services/impl/NotificationsServiceImpl.java | 92 ++ .../services/impl/PropagationServiceImpl.java | 78 ++ .../services/impl/SubscriptionServiceImpl.java | 50 + .../src/main/resources/factoryConfiguration.json | 9 + .../impl/MulticastDestinationTest.java | 67 ++ .../NotificationPropagationManagerImplTest.java | 64 ++ .../impl/NotificationsServiceImplTest.java | 50 + .../services/impl/PropagationServiceImplTest.java | 96 ++ .../openecomp-sdc-notification-websocket/pom.xml | 34 + .../websocket/NotificationWebsocketHandler.java | 130 +++ .../openecomp-sdc-notification-worker/pom.xml | 73 ++ .../notification/config/ConfigurationManager.java | 113 +++ .../notification/types/NotificationEntityDto.java | 103 ++ .../notification/types/NotificationsStatusDto.java | 72 ++ .../workers/NewNotificationsReader.java | 29 + .../notification/workers/NotificationReceiver.java | 69 ++ .../notification/workers/NotificationWorker.java | 117 +++ .../impl/NewNotificationsReaderRestImpl.java | 84 ++ .../src/main/resources/factoryConfiguration.json | 3 + .../main/resources/onboarding_configuration.yaml | 5 + .../workers/NotificationWorkerTest.java | 134 +++ .../src/test/resources/logback.xml | 15 + .../src/test/resources/notification_1.csv | 11 + .../src/test/resources/notification_2.csv | 11 + .../test/resources/onboarding_configuration.yaml | 5 + .../lib/openecomp-sdc-notification-lib/pom.xml | 23 + .../services/ManualVspToscaGenerationService.java | 33 +- .../sdc/generator/core/utils/GeneratorUtils.java | 4 +- .../datatypes/heattotosca/TranslationContext.java | 1 - .../services/heattotosca/ConsolidationService.java | 1 - .../services/heattotosca/HeatToToscaUtil.java | 6 +- .../heattotosca/UnifiedCompositionService.java | 12 +- .../globaltypes/GlobalTypesServiceTemplates.java | 2 +- .../helper/VolumeTranslationHelper.java | 4 +- .../FunctionTranslationGetAttrImpl.java | 2 +- .../FunctionTranslationGetFileImpl.java | 2 +- .../FunctionTranslationGetParamImpl.java | 2 +- .../FunctionTranslationGetResourceImpl.java | 2 +- .../BaseResourceConnection.java | 2 +- .../ResourceConnectionUsingCapabilityHelper.java | 2 - .../ResourceTranslationBase.java | 1 - ...ourceTranslationCinderVolumeAttachmentImpl.java | 4 +- ...esourceTranslationContrailAttachPolicyImpl.java | 6 +- ...urceTranslationContrailV2NetworkPolicyImpl.java | 1 - .../ResourceTranslationNovaServerGroupsImpl.java | 2 +- .../ResourceTranslationNovaServerImpl.java | 21 +- .../SecurityRulesToPortResourceConnection.java | 1 - .../org/openecomp/sdc/translator/TestUtils.java | 22 +- .../heattotosca/resources/OSNovaServerTest.java | 6 +- .../heattotosca/ConsolidationDataUtilTest.java | 1 + .../heattotosca/ConsolidationServiceTest.java | 34 - .../heattotosca/UnifiedCompositionServiceTest.java | 28 +- .../ConsolidationDataTestUtil.java | 28 +- .../helper/ContrailTranslationHelperTest.java | 2 +- .../FunctionTranslationGetFileImplTest.java | 2 +- .../FunctionTranslationGetParamImplTest.java | 3 +- .../NameExtractorContrailComputeImplTest.java | 1 - .../NameExtractorNovaServerImplTest.java | 3 +- .../BaseResourceTranslationTest.java | 26 +- .../DependsOnResourceBaseTranslationlTest.java | 12 +- ...eTranslationCinderVolumeAttachmentImplTest.java | 6 +- ...ceTranslationContrailV2VmInterfaceImplTest.java | 4 +- .../ResourceTranslationNeutronPortImplTest.java | 4 +- ...esourceTranslationNovaServerGroupsImplTest.java | 4 +- .../SecurityRulesToPortResourceConnectionTest.java | 4 +- .../validation/types/GlobalValidationContext.java | 2 +- .../sdc/validation/impl/ValidationManagerImpl.java | 6 +- .../heat/services/tree/HeatTreeManagerTest.java | 4 - .../impl/util/HeatValidationService.java | 16 +- .../impl/validators/ContrailValidator.java | 6 +- .../ForbiddenResourceGuideLineValidator.java | 2 +- .../impl/validators/HeatResourceValidator.java | 35 +- .../validation/impl/validators/HeatValidator.java | 290 +++--- .../impl/validators/ManifestValidator.java | 2 +- .../NamingConventionGuideLineValidator.java | 2 +- .../SharedResourceGuideLineValidator.java | 10 +- .../validation/impl/validators/YamlValidator.java | 4 +- .../heatresource/NovaServerResourceValidator.java | 2 +- ...vaServerNamingConventionGuideLineValidator.java | 4 +- .../impl/validators/ContrailValidatorTest.java | 2 +- .../impl/validators/ErrorMessagesTest.java | 2 +- .../impl/validators/HeatValidatorTest.java | 2 +- .../SharedResourceGuideLineValidatorTest.java | 2 +- ...rviceTemplateNamingConventionValidatorTest.java | 3 +- .../NeutronPortNamingConventionValidatorTest.java | 3 +- .../sdc/validation/base/ResourceBaseValidator.java | 10 +- .../sdc/validation/util/ValidationTestUtil.java | 3 +- .../sdc/validation/util/ValidationUtil.java | 5 +- .../sdc/vendorlicense/VendorLicenseUtil.java | 28 + .../dao/types/EntitlementPoolEntity.java | 61 +- .../dao/types/LicenseKeyGroupEntity.java | 63 +- .../sdc/vendorlicense/dao/types/LimitEntity.java | 50 +- .../dao/types/VendorLicenseModelEntity.java | 10 + .../vendorlicense/facade/VendorLicenseFacade.java | 60 +- .../sdc/vendorlicense/healing/HealingService.java | 2 +- .../VendorLicenseArtifactsService.java | 2 +- .../dao/impl/FeatureGroupCassandraDaoImpl.java | 4 +- .../zusammen/EntitlementPoolZusammenDaoImpl.java | 191 ++-- .../impl/zusammen/FeatureGroupDaoZusammenImpl.java | 197 ++-- .../zusammen/LicenseAgreementDaoZusammenImpl.java | 159 ++- .../zusammen/LicenseKeyGroupZusammenDaoImpl.java | 200 ++-- .../dao/impl/zusammen/LimitZusammenDaoImpl.java | 134 +-- .../VendorLicenseModelDaoZusammenImpl.java | 111 ++- .../dao/impl/zusammen/VlmZusammenUtil.java | 39 +- .../ElementToEntitlementPoolConvertor.java | 95 ++ .../convertor/ElementToFeatureGroupConvertor.java | 83 ++ .../ElementToLicenseAgreementConvertor.java | 86 ++ .../ElementToLicenseKeyGroupConvertor.java | 104 ++ .../convertor/ElementToLimitConvertor.java | 44 + .../convertor/ElementToVLMGeneralConvertor.java | 52 + .../facade/impl/VendorLicenseFacadeImpl.java | 316 ++---- .../healing/impl/SimpleHealingServiceImpl.java | 20 +- .../impl/VendorLicenseArtifactsServiceImpl.java | 94 +- .../impl/types/VnfLicenseArtifact.java | 4 +- ...itlementPoolEntityForVendorLicenseArtifact.java | 10 +- .../MixinEntitlementPoolEntityForVnfArtifact.java | 14 +- ...enseKeyGroupEntityForVendorLicenseArtifact.java | 10 +- .../MixinLicenseKeyGroupEntityForVnfArtifact.java | 14 +- .../util/VendorLicenseArtifactsServiceUtils.java | 70 +- .../VendorSoftwareProductConstants.java | 6 +- .../dao/ComponentDependencyModelDao.java | 3 - .../dao/OrchestrationTemplateCandidateDao.java | 4 +- .../dao/OrchestrationTemplateDao.java | 9 +- .../vendorsoftwareproduct/dao/PackageInfoDao.java | 8 - .../sdc/vendorsoftwareproduct/dao/ProcessDao.java | 7 +- .../vendorsoftwareproduct/dao/UploadDataDao.java | 34 - .../dao/UploadDataDaoFactory.java | 31 - .../dao/VendorSoftwareProductDao.java | 127 --- .../dao/VendorSoftwareProductDaoFactory.java | 35 - .../dao/VendorSoftwareProductInfoDao.java | 6 - .../sdc/vendorsoftwareproduct/dao/VspMergeDao.java | 16 + .../dao/VspMergeDaoFactory.java | 11 + .../dao/type/DeploymentFlavorEntity.java | 6 +- .../dao/type/OnboardingMethod.java | 6 + .../type/OrchestrationTemplateCandidateData.java | 25 +- .../dao/type/OrchestrationTemplateEntity.java | 135 +++ .../dao/type/PackageInfo.java | 10 +- .../vendorsoftwareproduct/dao/type/UploadData.java | 90 -- .../dao/type/UploadDataEntity.java | 122 --- .../vendorsoftwareproduct/dao/type/VspDetails.java | 53 +- .../composition/CompositionEntityDataManager.java | 22 +- .../filedatastructuremodule/CandidateService.java | 24 +- .../services/impl/HeatFileAnalyzerRowDataImpl.java | 6 +- .../services/utils/CandidateEntityBuilder.java | 24 +- .../types/CandidateDataEntityTo.java | 42 +- .../questionnaire/component/compute/GuestOS.java | 6 +- .../questionnaire/component/compute/VmSizing.java | 12 +- .../questionnaire/component/general/Image.java | 12 +- .../questionnaire/component/general/Recovery.java | 12 +- .../questionnaire/component/storage/Backup.java | 6 +- .../questionnaire/component/storage/LogBackup.java | 12 +- .../types/questionnaire/nic/PeakAndAvg.java | 6 +- .../types/questionnaire/nic/Sizing.java | 6 +- .../vsp/general/StorageDataReplication.java | 12 +- .../src/main/resources/factoryConfiguration.json | 2 - .../ComponentDependencyModelDaoCassandraImpl.java | 6 - .../dao/impl/PackageInfoDaoImpl.java | 31 +- .../dao/impl/ProcessDaoFactoryImpl.java | 2 +- .../impl/VendorSoftwareProductDaoFactoryImpl.java | 34 - .../dao/impl/VendorSoftwareProductDaoImpl.java | 323 ------ .../dao/impl/VendorSoftwareProductInfoDaoImpl.java | 15 - .../dao/impl/VspMergeDaoFactoryImpl.java | 17 + .../dao/impl/VspMergeDaoImpl.java | 158 +++ .../zusammen/ComponentArtifactDaoZusammenImpl.java | 198 ++-- .../impl/zusammen/ComponentDaoZusammenImpl.java | 210 ++-- .../ComponentDependencyModelDaoZusammenImpl.java | 195 ++-- .../dao/impl/zusammen/ComputeDaoZusammenImpl.java | 175 ++-- .../zusammen/DeploymentFlavorDaoZusammenImpl.java | 146 ++- .../dao/impl/zusammen/ElementPropertyName.java | 6 - .../dao/impl/zusammen/ElementType.java | 13 - .../dao/impl/zusammen/ImageDaoZusammenImpl.java | 165 ++-- .../dao/impl/zusammen/NetworkDaoZusammenImpl.java | 148 +-- .../dao/impl/zusammen/NicDaoZusammenImpl.java | 193 ++-- ...hestrationTemplateCandidateDaoZusammenImpl.java | 160 ++- .../OrchestrationTemplateDaoZusammenImpl.java | 180 ++-- .../dao/impl/zusammen/ProcessDaoZusammenImpl.java | 265 ++--- .../dao/impl/zusammen/StructureElement.java | 24 - .../VendorSoftwareProductInfoDaoZusammenImpl.java | 262 ++--- .../dao/impl/zusammen/VspZusammenUtil.java | 38 - .../convertor/ElementToComponentConvertor.java | 38 + ...ElementToComponentDependencyModelConvertor.java | 41 + ...lementToComponentMonitoringUploadConvertor.java | 45 + .../ElementToComponentQuestionnnaireConvertor.java | 21 + .../ElementToCompositionEntityConvertor.java | 45 + .../convertor/ElementToComputeConvertor.java | 40 + .../ElementToComputeQuestionnaireConvertor.java | 19 + .../ElementToDeploymentFlavorConvertor.java | 40 + .../convertor/ElementToImageConvertor.java | 40 + .../ElementToImageQuestionnaireConvertor.java | 19 + .../ElementToMonitoringUploadMapConvertor.java | 23 + .../convertor/ElementToNetworkConvertor.java | 38 + .../zusammen/convertor/ElementToNicConvertor.java | 39 + .../ElementToNicQuestionnaireConvertor.java | 21 + ...OrchestrationTemplateCandidateMapConvertor.java | 20 + .../convertor/ElementToProcessConvertor.java | 53 + .../ElementToServiceModelMapConvertor.java | 20 + .../convertor/ElementToVSPGeneralConvertor.java | 78 ++ .../ElementToVSPQuestionnaireConvertor.java | 17 + .../errors/VendorSoftwareProductErrorCodes.java | 6 +- .../CompositionEntityDataManagerFactoryImpl.java | 6 +- .../QuestionnaireDataServiceImpl.java | 23 +- .../services/ManualVspDataCollectionService.java | 91 +- .../composition/CompositionDataExtractorImpl.java | 2 +- .../CompositionEntityDataManagerImpl.java | 173 ++-- .../CandidateServiceImpl.java | 1028 ++++++++++---------- .../ManifestCreatorNamingConventionImpl.java | 14 +- .../src/main/resources/factoryConfiguration.json | 3 + .../dao/ServiceModelDaoFactoryTest.java | 307 ++++-- .../TxtInformationArtifactGeneratorImplTest.java | 32 - .../openecomp-sdc-versioning-api/pom.xml | 15 + .../org/openecomp/sdc/versioning/ItemManager.java | 20 + .../sdc/versioning/ItemManagerFactory.java | 31 + .../sdc/versioning/VersioningManager.java | 23 + .../VersioningNotificationConstansts.java | 13 + .../org/openecomp/sdc/versioning/dao/ItemDao.java | 15 + .../sdc/versioning/dao/ItemDaoFactory.java | 30 + .../openecomp/sdc/versioning/dao/VersionDao.java | 29 + .../sdc/versioning/dao/VersionDaoFactory.java | 30 + .../sdc/versioning/dao/types/Revision.java | 42 + .../versioning/dao/types/SynchronizationState.java | 17 + .../sdc/versioning/dao/types/Version.java | 117 ++- .../sdc/versioning/dao/types/VersionState.java | 23 + .../sdc/versioning/dao/types/VersionStatus.java | 6 +- .../errors/EditOnUnlockedEntityErrorBuilder.java | 4 +- .../errors/RevisionIdNotFoundErrorBuilder.java | 44 + .../VersionableSubEntityNotFoundErrorBuilder.java | 2 +- .../versioning/errors/VersioningErrorCodes.java | 6 + .../org/openecomp/sdc/versioning/types/Item.java | 103 ++ .../versioning/types/NotificationEventTypes.java | 20 + .../versioning/types/VersionCreationMethod.java | 8 + .../src/main/resources/factoryConfiguration.json | 6 +- .../sdc/versioning/VersionCalculator.java | 12 + .../sdc/versioning/VersionCalculatorFactory.java | 31 + .../versioning/dao/impl/ItemDaoFactoryImpl.java | 36 + .../versioning/dao/impl/VersionDaoFactoryImpl.java | 36 + .../impl/VersionableEntityDaoCassandraImpl.java | 4 +- .../dao/impl/zusammen/ItemZusammenDaoImpl.java | 104 ++ .../dao/impl/zusammen/VersionZusammenDaoImpl.java | 165 ++++ .../convertor/ItemVersionToVersionConvertor.java | 49 + .../versioning/impl/ItemManagerFactoryImpl.java | 39 + .../sdc/versioning/impl/ItemManagerImpl.java | 68 ++ .../impl/MajorVersionCalculatorFactoryImpl.java | 14 + .../impl/MajorVersionCalculatorImpl.java | 53 + .../impl/VersionCalculatorFactoryImpl.java | 34 + .../sdc/versioning/impl/VersionCalculatorImpl.java | 155 +++ .../impl/VersioningManagerFactoryImpl.java | 9 +- .../sdc/versioning/impl/VersioningManagerImpl.java | 218 ++++- .../src/main/resources/factoryConfiguration.json | 3 + .../impl/zusammen/VersionZusammenDaoImplTest.java | 265 +++++ .../sdc/versioning/impl/ItemManagerImplTest.java | 124 +++ .../versioning/impl/VersioningManagerImplTest.java | 399 +++++++- .../errors/CreateToscaObjectErrorBuilder.java | 7 +- .../openecomp/core/impl/ToscaConverterImpl.java | 43 +- .../core/impl/ToscaConverterManagerImpl.java | 7 +- .../openecomp/core/impl/ToscaConverterUtil.java | 12 +- .../services/ServiceTemplateReaderServiceImpl.java | 9 +- .../converter/impl/ToscaConverterImplTest.java | 1 - .../impl/ToscaConvertorDefinitionsTest.java | 12 +- .../services/impl/ToscaAnalyzerServiceImpl.java | 2 +- .../impl/ToscaAnalyzerServiceImplTest.java | 12 +- openecomp-be/lib/pom.xml | 5 +- openecomp-be/pom.xml | 12 +- .../tools/build/scripts/cassandra-commands.json | 64 +- .../build/scripts/zusammen-cassandra-commands.json | 17 +- .../database/schemaTemplates/questionnaire/vsp.ftl | 1 + .../tools/migration/1702_to_1707_zusammen/pom.xml | 241 ----- .../src/main/assembly/migration-lib-assembly.xml | 41 - .../openecomp/core/migration/MigrationMain.java | 469 --------- .../migration/convertors/ComponentConvertor.java | 102 -- .../convertors/EntitlementPoolConvertor.java | 92 -- .../convertors/FeatureGroupConvertor.java | 102 -- .../core/migration/convertors/LKGConvertor.java | 79 -- .../convertors/LicenseAgreementConvertor.java | 84 -- .../core/migration/convertors/MibConvertor.java | 77 -- .../migration/convertors/NetworkConvertor.java | 91 -- .../core/migration/convertors/NicConvertor.java | 95 -- .../OrchestrationTemplateCandidateConvertor.java | 70 -- .../migration/convertors/ProcessConvertor.java | 98 -- .../core/migration/convertors/VlmConvertor.java | 92 -- .../convertors/VspInformationConvertor.java | 162 --- .../convertors/VspServiceArtifactConvertor.java | 83 -- .../convertors/VspServiceTemplateConvertor.java | 100 -- .../loaders/ComponentCassandraLoader.java | 55 -- .../loaders/EntitlementPoolCassandraLoader.java | 31 - .../loaders/FeatureGroupCassandraLoader.java | 30 - .../core/migration/loaders/LKGCassandraLoader.java | 31 - .../loaders/LicenseAgreementCassandraLoader.java | 31 - .../core/migration/loaders/MibCassandraLoader.java | 55 -- .../migration/loaders/NetworkCassandraLoader.java | 35 - .../core/migration/loaders/NicCassandraLoader.java | 63 -- ...hestrationTemplateCandidateCassandraLoader.java | 55 -- .../migration/loaders/ProcessCassandraLoader.java | 55 -- .../loaders/ServiceArtifactCassandraLoader.java | 61 -- .../loaders/ServiceTemplateCassandraLoader.java | 61 -- .../loaders/VendorLicenseModelCassandraLoader.java | 50 - .../loaders/VendorSoftwareProductInfoLoader.java | 61 -- .../loaders/VersionInfoCassandraLoader.java | 53 - .../core/migration/loaders/VspInformation.java | 276 ------ .../core/migration/store/ElementHandler.java | 136 --- .../core/migration/store/ItemHandler.java | 122 --- .../org/openecomp/core/migration/util/Utils.java | 15 - .../migration/util/marker/MigrationMarker.java | 49 - .../util/marker/MigrationMarkerEntity.java | 45 - .../src/main/resources/logback.xml | 15 - .../core/tools/Commands/ExportDataCommand.java | 67 -- .../org/openecomp/core/tools/Commands/HealAll.java | 29 +- .../core/tools/Commands/ImportCommand.java | 45 - .../core/tools/Commands/SetHealingFlag.java | 31 + .../tools/Commands/exportdata/ElementHandler.java | 108 -- .../Commands/exportdata/ImportProperties.java | 20 - .../tools/Commands/exportdata/ItemHandler.java | 87 -- .../tools/Commands/exportdata/VersionHandler.java | 73 -- .../tools/Commands/importdata/ElementImport.java | 135 --- .../core/tools/Commands/importdata/ItemImport.java | 44 - .../core/tools/Commands/importdata/TreeWalker.java | 54 - .../tools/Commands/importdata/VersionImport.java | 41 - .../Commands/importdata/VersionInfoImport.java | 41 - .../core/tools/concurrent/ItemHealingTask.java | 64 +- .../core/tools/exportinfo/ExportDataCommand.java | 125 +++ .../core/tools/exportinfo/ExportSerializer.java | 152 +++ .../core/tools/importinfo/ImportDataCommand.java | 37 + .../core/tools/importinfo/ImportProperties.java | 7 + .../core/tools/importinfo/ImportSingleTable.java | 166 ++++ .../tools/loaders/zusammen/VspGeneralLoader.java | 40 - .../core/tools/loaders/zusammen/VspItemLoader.java | 4 - .../core/tools/main/ZusammenMainTool.java | 10 +- .../core/tools/model/ColumnDefinition.java | 84 ++ .../org/openecomp/core/tools/model/TableData.java | 12 + .../tools/store/CassandraElementRepository.java | 23 +- .../openecomp/core/tools/store/ElementHandler.java | 13 +- .../openecomp/core/tools/store/HealingHandler.java | 54 + .../core/tools/store/VersionCassandraLoader.java | 6 + .../core/tools/store/VspGeneralLoader.java | 21 +- .../store/zusammen/datatypes/HealingEntity.java | 78 ++ .../store/zusammen/datatypes/VersionEntity.java | 4 +- .../java/org/openecomp/core/tools/util/Utils.java | 23 + .../org/openecomp/core/tools/util/ZipUtils.java | 30 +- .../zusammen-tools/src/main/resources/logback.xml | 1 + .../zusammen-tools/src/main/resources/queries.yaml | 16 + .../exportinfo/serialize/VLMExtractTest.java | 48 + .../src/test/resources/configuration.yaml | 251 +++++ .../zusammen-tools/src/test/resources/queries.yaml | 16 + openecomp-ui/.eslintrc | 1 + openecomp-ui/devConfig.defaults.json | 1 + openecomp-ui/gulpfile.js | 14 +- openecomp-ui/package.json | 21 +- openecomp-ui/pom.xml | 13 + openecomp-ui/resources/images/angle-left.svg | 9 - openecomp-ui/resources/images/angle-right.svg | 9 - openecomp-ui/resources/images/artifacts_icon.png | Bin 1052 -> 0 bytes openecomp-ui/resources/images/base_icon.png | Bin 1534 -> 0 bytes openecomp-ui/resources/images/download_icon.png | Bin 286 -> 0 bytes .../resources/images/icons/ZIP_blue_icon.png | Bin 371 -> 0 bytes openecomp-ui/resources/images/icons/ZIP_icon.png | Bin 340 -> 0 bytes .../resources/images/icons/artifacts_blue_icon.png | Bin 119 -> 0 bytes .../resources/images/icons/artifacts_grey_icon.png | Bin 112 -> 0 bytes openecomp-ui/resources/images/icons/back_icon.png | Bin 289 -> 0 bytes openecomp-ui/resources/images/icons/checked_in.png | Bin 1236 -> 0 bytes .../resources/images/icons/checked_out.png | Bin 1237 -> 0 bytes .../resources/images/icons/down_chevron.png | Bin 184 -> 0 bytes openecomp-ui/resources/images/icons/env_icon.png | Bin 145 -> 0 bytes .../resources/images/icons/env_icon_blue.png | Bin 145 -> 0 bytes .../resources/images/icons/error_icon_big.png | Bin 435 -> 0 bytes .../resources/images/icons/error_icon_small.png | Bin 363 -> 0 bytes openecomp-ui/resources/images/icons/favicon.ico | Bin 566 -> 0 bytes openecomp-ui/resources/images/icons/favicon.png | Bin 566 -> 0 bytes .../images/icons/go_to_overview_disable_icon.png | Bin 121 -> 0 bytes .../resources/images/icons/go_to_overview_icon.png | Bin 121 -> 0 bytes .../images/icons/nested_HEAT_icon_blue.png | Bin 174 -> 0 bytes .../resources/images/icons/nested_heat_icon.png | Bin 180 -> 0 bytes .../resources/images/icons/network_blue_icon.png | Bin 285 -> 0 bytes .../resources/images/icons/network_icon.png | Bin 306 -> 0 bytes .../resources/images/icons/orphans_blue_icon-n.png | Bin 683 -> 0 bytes .../resources/images/icons/orphans_grey_icon.png | Bin 321 -> 0 bytes .../resources/images/icons/others_blue_icon.png | Bin 121 -> 0 bytes .../resources/images/icons/others_icon.png | Bin 114 -> 0 bytes .../resources/images/icons/pencil_icon-01.svg | 17 - .../icons/plus_vlm_summary_disabled_icon.png | Bin 1012 -> 0 bytes .../images/icons/plus_vlm_summary_icon.png | Bin 690 -> 0 bytes .../images/icons/plus_vlm_summary_icon_blue.png | Bin 1013 -> 0 bytes .../images/icons/revert_icon_disabled.png | Bin 443 -> 0 bytes openecomp-ui/resources/images/icons/reverticon.png | Bin 1305 -> 0 bytes .../resources/images/icons/save_icon_disable.png | Bin 186 -> 0 bytes openecomp-ui/resources/images/icons/saveicon.png | Bin 15002 -> 0 bytes .../resources/images/icons/submit_icon_disable.png | Bin 479 -> 0 bytes .../resources/images/icons/submiticonactive.png | Bin 1334 -> 0 bytes .../images/icons/vlm_list_view_blue_icon.png | Bin 367 -> 0 bytes .../images/icons/vlm_list_view_grey_icon.png | Bin 347 -> 0 bytes .../resources/images/icons/volume_blue_icon.png | Bin 479 -> 0 bytes .../resources/images/icons/volume_icon.png | Bin 453 -> 0 bytes .../resources/images/icons/warning_icon_big.png | Bin 380 -> 0 bytes .../resources/images/icons/warning_icon_small.png | Bin 287 -> 0 bytes openecomp-ui/resources/images/module_icon.png | Bin 1204 -> 0 bytes openecomp-ui/resources/images/pencil_icon-01.svg | 17 - openecomp-ui/resources/images/plus-circle-icon.svg | 18 - .../resources/images/svg/angle-double-left.svg | 15 - .../resources/images/svg/angle-double-right.svg | 11 - openecomp-ui/resources/images/svg/angle-left.svg | 9 - openecomp-ui/resources/images/svg/angle-right.svg | 9 - openecomp-ui/resources/images/svg/back.svg | 6 - openecomp-ui/resources/images/svg/calendar.svg | 1 - openecomp-ui/resources/images/svg/caret-down.svg | 6 - openecomp-ui/resources/images/svg/check-circle.svg | 1 - openecomp-ui/resources/images/svg/check.svg | 9 - openecomp-ui/resources/images/svg/chevron-down.svg | 9 - openecomp-ui/resources/images/svg/chevron-up.svg | 9 - openecomp-ui/resources/images/svg/close.svg | 10 - openecomp-ui/resources/images/svg/error-circle.svg | 1 - .../images/svg/exclamation-triangle-full.svg | 9 - .../images/svg/exclamation-triangle-line.svg | 25 - .../resources/images/svg/exclamation-triangle.svg | 11 - openecomp-ui/resources/images/svg/filter.svg | 9 - openecomp-ui/resources/images/svg/locked.svg | 39 - openecomp-ui/resources/images/svg/pencil.svg | 17 - openecomp-ui/resources/images/svg/plus-circle.svg | 15 - openecomp-ui/resources/images/svg/plus.svg | 9 - openecomp-ui/resources/images/svg/search.svg | 8 - openecomp-ui/resources/images/svg/sliders.svg | 19 - openecomp-ui/resources/images/svg/trash-o.svg | 17 - openecomp-ui/resources/images/svg/unlocked.svg | 39 - openecomp-ui/resources/images/svg/vendor.svg | 1 - .../images/svg/version-controller-lock-closed.svg | 17 - .../images/svg/version-controller-lock-open.svg | 17 - .../images/svg/version-controller-revert.svg | 14 - .../images/svg/version-controller-save.svg | 10 - .../images/svg/version-controller-submit.svg | 10 - openecomp-ui/resources/images/svg/vlm.svg | 1 - openecomp-ui/resources/images/svg/vsp.svg | 1 - openecomp-ui/resources/images/trash_icon.png | Bin 173 -> 0 bytes openecomp-ui/resources/images/upload_icon.png | Bin 268 -> 0 bytes openecomp-ui/resources/images/v_icon.png | Bin 832 -> 0 bytes openecomp-ui/resources/scss/_components.scss | 9 +- openecomp-ui/resources/scss/_modules.scss | 4 + .../resources/scss/bootstrap-cust/_buttons.scss | 13 - .../resources/scss/bootstrap-cust/_forms.scss | 20 +- .../resources/scss/bootstrap-cust/_modals.scss | 4 + .../resources/scss/bootstrap-cust/_navbar.scss | 3 - .../resources/scss/bootstrap-cust/_navs.scss | 30 - openecomp-ui/resources/scss/bootstrap.scss | 6 - .../resources/scss/bootstrap/_button-groups.scss | 12 - openecomp-ui/resources/scss/common/_base.scss | 8 +- openecomp-ui/resources/scss/common/_layout.scss | 8 +- .../resources/scss/common/_typography.scss | 8 +- openecomp-ui/resources/scss/common/_utils.scss | 3 +- openecomp-ui/resources/scss/common/_variables.scss | 68 +- .../resources/scss/components/_activityLog.scss | 1 + .../resources/scss/components/_buttons.scss | 30 - .../resources/scss/components/_commitModal.scss | 10 + .../resources/scss/components/_dropzone.scss | 23 + .../resources/scss/components/_dualListBox.scss | 8 +- openecomp-ui/resources/scss/components/_forms.scss | 4 +- openecomp-ui/resources/scss/components/_grid.scss | 121 +-- openecomp-ui/resources/scss/components/_icon.scss | 164 ---- .../resources/scss/components/_listEditorView.scss | 30 +- .../scss/components/_navigationSideBar.scss | 5 +- .../resources/scss/components/_overlay.scss | 26 + openecomp-ui/resources/scss/components/_tree.scss | 56 ++ .../scss/components/_userNotifications.scss | 123 +++ .../scss/components/_versionController.scss | 370 +++++-- .../resources/scss/modules/_entitlementPools.scss | 33 +- .../resources/scss/modules/_featureGroup.scss | 43 - .../resources/scss/modules/_licenseAgreement.scss | 38 +- .../resources/scss/modules/_licenseKeyGroup.scss | 5 - .../resources/scss/modules/_licenseModel.scss | 16 +- .../scss/modules/_licenseModelOverview.scss | 23 +- .../resources/scss/modules/_mergeEditor.scss | 207 ++++ .../resources/scss/modules/_onboardingCatalog.scss | 33 + .../resources/scss/modules/_permissions.scss | 55 ++ .../resources/scss/modules/_revisions.scss | 86 ++ .../modules/_softwareProductAttachmentPage.scss | 28 +- .../modules/_softwareProductComponentGeneral.scss | 3 - .../modules/_softwareProductComponentImage.scss | 11 +- .../modules/_softwareProductComponentNetwork.scss | 11 +- .../_softwareProductComponentProcessesPage.scss | 3 - .../scss/modules/_softwareProductDependencies.scss | 25 +- .../scss/modules/_softwareProductDeployment.scss | 13 +- .../scss/modules/_softwareProductLandingPage.scss | 45 +- .../modules/_softwareProductProcessesPage.scss | 40 +- .../_softwareproductComponentLoadBalancing.scss | 6 - .../resources/scss/modules/_uploadScreen.scss | 14 - .../resources/scss/modules/_versionsPage.scss | 325 +++++++ .../scss/modules/_vspComponentCompute.scss | 13 - .../scss/modules/_vspComponentMonitoring.scss | 28 - .../scss/modules/_vspComponentQuestionnaire.scss | 9 +- .../modules/onboardingCatalog/_catalogHeader.scss | 2 +- .../modules/onboardingCatalog/_onboardHeader.scss | 5 +- .../modules/onboardingCatalog/_vspOverlay.scss | 2 +- openecomp-ui/resources/scss/onboarding.scss | 22 + .../src/nfvo-components/SubmitErrorResponse.jsx | 9 +- .../src/nfvo-components/datepicker/Datepicker.jsx | 29 +- .../src/nfvo-components/editor/TabulatedEditor.jsx | 10 +- .../fileupload/DraggableUploadFileBox.jsx | 7 +- openecomp-ui/src/nfvo-components/grid/GridItem.jsx | 4 +- .../src/nfvo-components/grid/GridSection.jsx | 9 +- openecomp-ui/src/nfvo-components/icon/Icon.jsx | 45 - .../src/nfvo-components/input/ExpandableInput.jsx | 7 +- .../src/nfvo-components/input/ToggleInput.jsx | 9 +- .../input/dualListbox/DualListboxView.jsx | 17 +- .../src/nfvo-components/input/validation/Form.jsx | 37 +- .../src/nfvo-components/input/validation/Input.jsx | 18 +- .../input/validation/InputOptions.jsx | 39 +- .../input/validation/InputWrapper.jsx | 10 +- .../src/nfvo-components/input/validation/Tabs.jsx | 3 +- .../input/validation/ValidationButtons.jsx | 15 +- .../listEditor/ListEditorItemView.jsx | 11 +- .../nfvo-components/listEditor/ListEditorView.jsx | 19 +- .../listEditor/listEditor.stories.js | 10 +- openecomp-ui/src/nfvo-components/loader/Loader.jsx | 3 +- .../src/nfvo-components/modal/GlobalModal.js | 27 +- .../src/nfvo-components/overlay/Overlay.jsx | 40 + .../nfvo-components/panel/NavigationSideBar.jsx | 22 +- .../panel/versionController/VersionController.jsx | 176 ++-- .../VersionControllerConstants.js | 23 +- .../versionController/VersionControllerUtils.js | 52 - .../versionController/components/ActionButtons.jsx | 109 +++ .../components/CommitCommentModal.jsx | 73 ++ .../versionController/components/Permissions.jsx | 65 ++ .../nfvo-components/progressBar/ProgressBar.jsx | 5 +- .../nfvo-components/table/SelectActionTableRow.jsx | 4 +- openecomp-ui/src/nfvo-components/tree/Tree.jsx | 181 ++++ .../src/nfvo-components/tree/Tree.stories.js | 119 +++ openecomp-ui/src/nfvo-utils/Validator.js | 16 +- openecomp-ui/src/nfvo-utils/WebSocketUtil.js | 56 ++ openecomp-ui/src/nfvo-utils/getValue.js | 8 +- openecomp-ui/src/nfvo-utils/i18n/en.json | 262 ++++- openecomp-ui/src/nfvo-utils/i18n/i18n.stories.js | 35 + openecomp-ui/src/sdc-app/AppStore.js | 4 +- openecomp-ui/src/sdc-app/Application.jsx | 15 + openecomp-ui/src/sdc-app/ModulesOptions.jsx | 15 +- .../src/sdc-app/common/activity-log/ActivityLog.js | 5 +- .../common/activity-log/ActivityLogActionHelper.js | 11 +- .../common/activity-log/ActivityLogView.jsx | 13 +- .../src/sdc-app/common/helpers/ItemsHelper.js | 78 ++ .../src/sdc-app/common/helpers/ScreensHelper.js | 290 ++++++ .../src/sdc-app/common/merge/MergeEditor.js | 37 + .../common/merge/MergeEditorActionHelper.js | 443 +++++++++ .../sdc-app/common/merge/MergeEditorConstants.js | 224 +++++ .../src/sdc-app/common/merge/MergeEditorReducer.js | 66 ++ .../src/sdc-app/common/merge/MergeEditorView.jsx | 256 +++++ .../src/sdc-app/common/modal/ModalContentMapper.js | 22 +- openecomp-ui/src/sdc-app/config/Configuration.js | 9 +- openecomp-ui/src/sdc-app/config/config.json | 5 +- .../src/sdc-app/flows/FlowsListEditorView.jsx | 4 +- openecomp-ui/src/sdc-app/flows/SequenceDiagram.jsx | 3 +- openecomp-ui/src/sdc-app/heatValidation.app.jsx | 2 +- .../heatvalidation/UploadScreenActionHelper.js | 36 +- .../src/sdc-app/onboarding/GridStyling.stories.js | 221 +++++ .../sdc-app/onboarding/OnboardingActionHelper.js | 138 +-- .../src/sdc-app/onboarding/OnboardingConstants.js | 119 ++- .../src/sdc-app/onboarding/OnboardingPunchOut.jsx | 376 ++++--- .../src/sdc-app/onboarding/OnboardingReducers.js | 118 ++- .../sdc-app/onboarding/OnboardingReducersMap.js | 14 +- .../onboarding/licenseModel/LicenseModel.js | 175 ++-- .../licenseModel/LicenseModelActionHelper.js | 142 +-- .../licenseModel/LicenseModelConstants.js | 9 - .../licenseModel/LicenseModelListReducer.js | 2 - .../licenseModel/creation/LicenseModelCreation.js | 24 +- .../creation/LicenseModelCreationActionHelper.js | 8 +- .../creation/LicenseModelCreationConstants.js | 3 +- .../creation/LicenseModelCreationView.jsx | 25 +- .../EntitlementPoolsActionHelper.js | 12 +- .../EntitlementPoolsEditorView.jsx | 81 +- .../entitlementPools/EntitlementPoolsLimits.js | 10 +- .../entitlementPools/EntitlementPoolsListEditor.js | 14 +- .../EntitlementPoolsListEditorView.jsx | 23 +- .../featureGroups/FeatureGroupEditorView.jsx | 35 +- .../featureGroups/FeatureGroupListEditor.js | 11 +- .../featureGroups/FeatureGroupListEditorView.jsx | 27 +- .../featureGroups/FeatureGroupsActionHelper.js | 43 +- .../LicenseAgreementActionHelper.js | 19 +- .../LicenseAgreementEditorView.jsx | 48 +- .../licenseAgreement/LicenseAgreementListEditor.js | 8 +- .../LicenseAgreementListEditorView.jsx | 21 +- .../LicenseKeyGroupsActionHelper.js | 13 +- .../LicenseKeyGroupsEditorView.jsx | 58 +- .../licenseKeyGroups/LicenseKeyGroupsLimits.js | 12 +- .../licenseKeyGroups/LicenseKeyGroupsListEditor.js | 10 +- .../LicenseKeyGroupsListEditorView.jsx | 38 +- .../onboarding/licenseModel/limits/LimitEditor.jsx | 51 +- .../licenseModel/overview/LicenseModelOverview.js | 15 +- .../overview/LicenseModelOverviewView.jsx | 35 +- .../licenseModel/overview/SummaryView.jsx | 23 +- .../licenseModel/overview/VLMListView.jsx | 5 +- .../listItemsComponents/AdditionalDataCol.jsx | 13 +- .../listItems/listItemsComponents/ArrowCol.jsx | 5 +- .../listItems/listItemsComponents/ItemInfo.jsx | 11 +- .../summary/LicenseModelDescriptionEdit.jsx | 11 +- .../licenseModel/overview/summary/ListButtons.jsx | 5 +- .../overview/summary/SummaryCountItem.jsx | 3 +- .../overview/summary/SummaryCountList.js | 34 +- .../overview/summary/VendorDataView.js | 12 +- .../onboarding/onboard/CatalogItemDetails.jsx | 149 +-- .../onboard/CatalogItemDetails.stories.js | 35 +- .../src/sdc-app/onboarding/onboard/CatalogList.jsx | 9 +- .../src/sdc-app/onboarding/onboard/CatalogTile.jsx | 31 - .../onboarding/onboard/DetailsCatalogView.jsx | 40 +- .../src/sdc-app/onboarding/onboard/Onboard.js | 62 +- .../src/sdc-app/onboarding/onboard/OnboardView.jsx | 43 +- .../OnboardingCatalogActionHelper.js | 20 +- .../OnboardingCatalogConstants.js | 4 + .../onboardingCatalog/OnboardingCatalogUtils.js | 6 +- .../onboardingCatalog/OnboardingCatalogView.jsx | 7 +- .../onboard/onboardingCatalog/Tooltip.jsx | 17 +- .../onboard/onboardingCatalog/VSPOverlay.jsx | 5 +- .../onboardingCatalog/VendorCatalogView.jsx | 24 +- .../onboard/onboardingCatalog/VendorItem.jsx | 109 ++- .../onboarding/onboard/workspace/WorkspaceView.jsx | 26 +- .../permissions/PermissionsActionHelper.js | 108 ++ .../onboarding/permissions/PermissionsConstants.js | 27 + .../onboarding/permissions/PermissionsManager.js | 43 + .../onboarding/permissions/PermissionsManager.jsx | 117 +++ .../onboarding/permissions/PermissionsReducer.js | 28 + .../src/sdc-app/onboarding/revisions/Revisions.js | 37 + .../onboarding/revisions/RevisionsActionHelper.js | 100 ++ .../onboarding/revisions/RevisionsConstants.js | 20 + .../onboarding/revisions/RevisionsReducer.js | 25 + .../sdc-app/onboarding/revisions/RevisionsView.jsx | 87 ++ .../onboarding/softwareProduct/SoftwareProduct.js | 273 +++--- .../softwareProduct/SoftwareProductActionHelper.js | 249 +++-- .../softwareProduct/SoftwareProductConstants.js | 38 +- .../softwareProduct/SoftwareProductListReducer.js | 2 - .../attachments/SoftwareProductAttachments.js | 34 +- .../attachments/SoftwareProductAttachmentsView.jsx | 29 +- .../attachments/validation/HeatValidationView.jsx | 6 +- .../components/SoftwareProductComponents.js | 59 +- .../SoftwareProductComponentsActionHelper.js | 1 + .../components/SoftwareProductComponentsList.js | 51 - .../SoftwareProductComponentsListView.jsx | 23 +- .../compute/SoftwareProductComponentCompute.js | 7 +- .../SoftwareProductComponentComputeView.jsx | 15 +- .../compute/computeComponents/ComputeFlavors.js | 19 +- .../compute/computeComponents/GuestOs.jsx | 4 +- .../compute/computeComponents/NumberOfVms.jsx | 3 +- .../computeFlavor/ComputeFlavorEditor.js | 12 +- .../computeFlavor/ComputeFlavorEditorView.jsx | 25 +- .../computeComponents/computeFlavor/VmSizing.jsx | 4 +- .../creation/SoftwareProductComponentCreation.js | 9 +- .../SoftwareProductComponentCreationView.jsx | 14 +- .../general/SoftwareProductComponentsGeneral.js | 6 - .../SoftwareProductComponentsImageActionHelper.js | 16 +- .../images/SoftwareProductComponentsImageEditor.js | 8 +- .../SoftwareProductComponentsImageEditorView.jsx | 7 +- .../images/SoftwareProductComponentsImageList.js | 20 +- .../SoftwareProductComponentsImageListView.jsx | 14 +- .../images/imagesEditorComponents/FileDetails.jsx | 4 +- .../images/imagesEditorComponents/Version.jsx | 2 +- .../SoftwareProductComponentLoadBalancing.js | 14 +- ...oftwareProductComponentLoadBalancingRefView.jsx | 11 +- .../SoftwareProductComponentsMonitoring.js | 15 +- .../SoftwareProductComponentsMonitoringView.jsx | 3 +- .../components/network/NICCreation/NICCreation.js | 6 +- .../network/NICCreation/NICCreationActionHelper.js | 4 +- .../network/NICCreation/NICCreationView.jsx | 29 +- .../network/SoftwareProductComponentsNICEditor.js | 10 +- .../SoftwareProductComponentsNICEditorView.jsx | 4 +- ...SoftwareProductComponentsNetworkActionHelper.js | 4 +- .../SoftwareProductComponentsNetworkList.js | 20 +- .../network/nicEditorComponents/Acceptable.jsx | 94 +- .../network/nicEditorComponents/NameAndPurpose.jsx | 15 +- .../network/nicEditorComponents/Network.jsx | 59 +- .../network/nicEditorComponents/PacketsBytes.jsx | 27 +- .../network/nicEditorComponents/Protocols.jsx | 13 +- .../network/nicEditorComponents/Sizing.jsx | 4 +- ...SoftwareProductComponentProcessesEditorView.jsx | 155 +-- .../SoftwareProductComponentProcessesList.js | 13 +- .../SoftwareProductComponentsProcessesListView.jsx | 88 +- .../storage/SoftwareProductComponentStorage.js | 18 +- .../SoftwareProductComponentStorageView.jsx | 17 +- .../creation/SoftwareProductCreation.js | 26 +- .../SoftwareProductCreationActionHelper.js | 12 +- .../creation/SoftwareProductCreationConstants.js | 3 +- .../creation/SoftwareProductCreationView.jsx | 42 +- .../dependencies/SoftwareProductDependencies.js | 13 +- .../SoftwareProductDependenciesActionHelper.js | 77 +- .../SoftwareProductDependenciesConstants.js | 5 +- .../SoftwareProductDependenciesReducer.js | 30 +- .../SoftwareProductDependenciesView.jsx | 99 +- .../deployment/SoftwareProductDeployment.js | 7 +- .../deployment/SoftwareProductDeploymentView.jsx | 9 +- .../editor/SoftwareProductDeploymentEditor.js | 9 +- .../editor/SoftwareProductDeploymentEditorView.jsx | 10 +- .../details/SoftwareProductDetails.js | 23 +- .../details/SoftwareProductDetailsReducer.js | 5 + .../details/SoftwareProductDetailsView.jsx | 49 +- .../landingPage/SoftwareProductLandingPage.js | 30 +- .../landingPage/SoftwareProductLandingPageView.jsx | 60 +- .../networks/SoftwareProductNetworksView.jsx | 19 +- .../processes/SoftwareProductProcessListView.jsx | 99 ++ .../processes/SoftwareProductProcesses.js | 11 +- .../processes/SoftwareProductProcessesEditor.js | 2 +- .../SoftwareProductProcessesEditorForm.jsx | 181 ++++ .../SoftwareProductProcessesEditorView.jsx | 154 +-- .../processes/SoftwareProductProcessesView.jsx | 82 +- .../userNotifications/NotificationsReducer.js | 72 ++ .../userNotifications/NotificationsView.jsx | 106 ++ .../userNotifications/UserNotifications.jsx | 131 +++ .../UserNotificationsActionHelper.js | 123 +++ .../UserNotificationsConstants.js | 19 + .../sdc-app/onboarding/users/UsersActionHelper.js | 61 ++ .../src/sdc-app/onboarding/users/UsersConstants.js | 22 + .../src/sdc-app/onboarding/users/UsersReducers.js | 42 + .../onboarding/versionsPage/VersionsPage.js | 87 ++ .../onboarding/versionsPage/VersionsPage.jsx | 77 ++ .../versionsPage/VersionsPageActionHelper.js | 90 ++ .../versionsPage/VersionsPageConstants.js | 27 + .../onboarding/versionsPage/VersionsPageReducer.js | 42 + .../versionsPage/components/PermissionsView.jsx | 82 ++ .../versionsPage/components/VersionList.jsx | 129 +++ .../versionsPage/creation/VersionsPageCreation.js | 44 + .../creation/VersionsPageCreationActionHelper.js | 79 ++ .../creation/VersionsPageCreationConstants.js | 28 + .../creation/VersionsPageCreationReducer.js | 44 + .../creation/VersionsPageCreationView.jsx | 249 +++++ openecomp-ui/test-utils/MockRest.js | 14 + openecomp-ui/test-utils/ShowMore.js | 10 + .../factories/common/CurrentScreenFactory.js | 100 ++ .../test-utils/factories/common/VersionFactory.js | 31 + .../licenseModel/LicenseModelFactories.js | 18 +- .../factories/revisions/RevisionsFactories.js | 30 + ...SoftwareProductComponentsMonitoringFactories.js | 9 +- .../SoftwareProductDependenciesFactories.js | 4 +- .../SoftwareProductEditorFactories.js | 5 +- .../VersionControllerUtilsFactory.js | 10 +- .../test-utils/factories/users/UsersFactories.js | 35 + .../versionsPage/VersionsPageCreationFactories.js | 38 + .../versionsPage/VersionsPageFactories.js | 27 + openecomp-ui/test-utils/failedTestReport.js | 2 +- openecomp-ui/test/activity-log/ActivityLog.test.js | 30 +- .../creation/LicenseModelCreation.test.js | 10 +- .../test/licenseModel/entitlementPools/test.js | 129 ++- .../test/licenseModel/featureGroups/test.js | 84 +- .../test/licenseModel/licenseAgreement/test.js | 65 +- .../test/licenseModel/licenseKeyGroups/test.js | 130 ++- .../overview/summary/SummaryCountList.test.js | 3 +- .../overview/summary/VendorDataView.test.js | 3 +- openecomp-ui/test/licenseModel/overview/test.js | 13 +- .../test/licenseModel/overview/views.test.js | 2 +- openecomp-ui/test/licenseModel/test.js | 96 +- .../nfvo-components/editor/TabulatedEditor.test.js | 9 +- .../test/nfvo-components/modal/globalModal.test.js | 8 +- .../VersionController/versionController.test.js | 108 +- .../versionControllerUtils.test.js | 128 --- .../test/nfvo-components/tree/tree.test.js | 31 + .../test/onboard/onboardingCatalog/views.test.js | 11 +- .../test/permissions/permissionsManaager.test.js | 110 +++ openecomp-ui/test/revisions/revisions.test.js | 240 +++++ .../validation/HeatValidationView.test.js | 3 - .../SoftwareProductComponentComputeEditor.test.js | 5 +- ...VSPComponentComputeActionHelperHeatMode.test.js | 4 +- ...PComponentComputeActionHelperManualMode.test.js | 29 +- .../SoftwareProductComponentsMonitoring.test.js | 14 +- .../softwareProduct/components/monitoring/test.js | 8 +- .../SoftwareProductComponentsNICEditor.test.js | 5 +- ...areProductComponentsNetworkActionHelper.test.js | 118 +-- .../SoftwareProductComponentsProcessesView.test.js | 4 +- .../softwareProduct/components/storage/test.js | 4 +- .../test/softwareProduct/components/test.js | 4 +- .../creation/SoftwareProductCreation.test.js | 16 +- .../SoftwareProductDependencies.test.js | 216 +++- .../SoftwareProductDeploymentEditor.test.js | 3 + .../softwareProduct/details/detailsView.test.js | 52 +- openecomp-ui/test/softwareProduct/details/test.js | 70 +- .../landingPage/landingPage.test.js | 61 +- .../networks/SoftwareProductNetworksView.test.js | 3 +- .../test/softwareProduct/processes/test.js | 21 +- openecomp-ui/test/softwareProduct/test.js | 116 +++ .../test/utils/errorResponseHandler.test.js | 28 +- .../test/versionsPage/VersionsPage.test.js | 154 +++ .../creation/VersionsPageCreation.test.js | 113 +++ openecomp-ui/webpack.common.js | 8 +- 1319 files changed, 42539 insertions(+), 24600 deletions(-) delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/pom.xml delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/src/main/java/org/openecomp/sdcrests/activitylog/rest/ActivityLog.java delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/src/main/java/org/openecomp/sdcrests/activitylog/rest/mapping/MapActivityLogEntityToActivityLogDto.java delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/src/main/java/org/openecomp/sdcrests/activitylog/rest/services/ActivityLogImpl.java delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/pom.xml delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityLogDto.java delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityStatus.java delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityType.java delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/Conflicts.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapConflictInfoToDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapConflictToDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapDtoToConflictResolution.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapItemVersionConflictToDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/services/ConflictsImpl.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictInfoDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictResolutionDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ItemVersionConflictDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/src/main/java/org/openecomp/sdcrests/itempermissions/rest/ItemPermissions.java create mode 100644 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 create mode 100644 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 create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-types/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-types/src/main/java/org/openecomp/sdcrests/itempermissions/types/ItemPermissionsDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-types/src/main/java/org/openecomp/sdcrests/itempermissions/types/ItemPermissionsRequestDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/Versions.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapActivityLogEntityToDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapItemToDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapRevisionToDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapVersionToDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/VersionsImpl.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ActivityLogDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ActivityStatus.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/CommitRequestDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemCreationDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/RevisionDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/RevisionRequestDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/SubmitRequestDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionAction.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionActionRequestDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionRequestDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/java/org/openecomp/server/listeners/OnboardingAppStartupListener.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/resources/keyfile.txt create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/beans-services.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/jetty-web.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/spring-mapper-servlet.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/web.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/mapping/MapNotificationsStatusToDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/mapping/MapNotificationsToDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/services/Notifications.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/services/impl/NotificationsImpl.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationEntityDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationResponseStatus.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationsStatusDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/UpdateNotificationResponseStatus.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/pom.xml create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/SessionContextFilter.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/webapp/WEB-INF/spring-mapper-servlet.xml delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/types/VersionDto.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/mapping/EchoMapMapping.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/mapping/EchoMapping.java create mode 100644 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 delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapVersionedVendorLicenseModelToVendorLicenseModelEntityDto.java create mode 100644 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 delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/ComponentDependencyModels.java create mode 100644 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 create mode 100644 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 create mode 100644 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 delete mode 100644 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/MapFilesDataStructureToGetFileDataStructureResponseDto.java create mode 100644 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 create mode 100644 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 delete mode 100644 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/MapVersionedVendorSoftwareProductInfoToVspDetailsDto.java create mode 100644 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 create mode 100644 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 delete mode 100644 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/MapVspDetailsToVspCreationDto.java create mode 100644 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 delete mode 100644 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/ComponentDependencyModelsImpl.java create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/OnboardingMethod.java create mode 100644 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 delete mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspCreationDto.java create mode 100644 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 delete mode 100644 openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activityLog/ActivityLogManager.java delete mode 100644 openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activityLog/ActivityLogManagerFactory.java delete mode 100644 openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activityLog/impl/ActivityLogManagerFactoryImpl.java delete mode 100644 openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activityLog/impl/ActivityLogManagerImpl.java create mode 100644 openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/ActivityLogManager.java create mode 100644 openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/ActivityLogManagerFactory.java create mode 100644 openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/impl/ActivityLogManagerFactoryImpl.java create mode 100644 openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/impl/ActivityLogManagerImpl.java create mode 100644 openecomp-be/backend/openecomp-sdc-conflict-manager/pom.xml create mode 100644 openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/ConflictsManager.java create mode 100644 openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/ConflictsManagerFactory.java create mode 100644 openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/impl/ConflictsManagerFactoryImpl.java create mode 100644 openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/impl/ConflictsManagerImpl.java create mode 100644 openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/resources/factoryConfiguration.json create mode 100644 openecomp-be/backend/openecomp-sdc-item-permissions-manager/pom.xml create mode 100644 openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/ItemPermissionsManager.java create mode 100644 openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/ItemPermissionsManagerFactory.java create mode 100644 openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsManagerFactoryImpl.java create mode 100644 openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsManagerImpl.java create mode 100644 openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/resources/factoryConfiguration.json create mode 100644 openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/test/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsManagerImplTest.java create mode 100644 openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/test/resources/logback.xml delete mode 100644 openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/FileDataStructureDto.java delete mode 100644 openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/GetFileDataStructureResponseDTO.java delete mode 100644 openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeplomentFlavorManagerImplTest.java delete mode 100644 openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/mock/VendorSoftwareProductDaoFactoryMock.java create mode 100644 openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/SdcRuntimeException.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/pom.xml create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandler.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactory.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDao.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDaoFactory.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Conflict.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictInfo.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictResolution.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ItemVersionConflict.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Resolution.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/pom.xml create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoImpl.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ItemVersionConflictConvertorFromZusammen.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/impl/VspMergeHandler.java create mode 100644 openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/resources/factoryConfiguration.json create mode 100644 openecomp-be/lib/openecomp-conflict-lib/pom.xml create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/pom.xml create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContext.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProvider.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProviderFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/User.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/AsdcSessionContextProvider.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/SessionContextProviderFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/resources/factoryConfiguration.json create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/convertor/ElementConvertor.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/AsdcElement.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/ElementPropertyName.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/CommitStagingService.java delete mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementCollaborationStore.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPrivateStore.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPublicStore.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStageStore.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStore.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ErrorCode.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/Message.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/PublishService.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/RevertService.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/SyncService.java delete mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStore.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPrivateStore.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPublicStore.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionStageStore.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPrivateStoreImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPublicStoreImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPrivateStoreImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPublicStoreImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionStageStoreImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepository.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepositoryFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepository.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepositoryFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/StageRepository.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/SynchronizationStateRepository.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDao.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDaoFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepository.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepositoryFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepository.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepositoryFactory.java delete mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraDaoUtils.java delete mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepository.java delete mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepositoryFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/CassandraDaoUtils.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementRepositoryFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementRepositoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/StageEntity.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/SynchronizationStateEntity.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionContext.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionDataElement.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionEntity.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/TestUtils.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStoreTest.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImplTest.java create mode 100644 openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/dao/HealingDao.java create mode 100644 openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/ConfigConstants.java create mode 100644 openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealerType.java delete mode 100644 openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealingContext.java create mode 100644 openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/dao/impl/HealingDaoImpl.java create mode 100644 openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/entityHealingConfiguration.json create mode 100644 openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/OwnerHealer.java create mode 100644 openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/data/TestDescriptionHealer.java create mode 100644 openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/structure/TestNewEntityInVspHealer.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/pom.xml create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRules.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRulesFactory.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServices.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServicesFactory.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDao.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDaoFactory.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessages.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessagesBuilder.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/notifications/NotificationConstants.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/type/ItemPermissionsEntity.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/pom.xml create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoImpl.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImpl.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PrmissionsServicesFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/servlet/PermissionsFilter.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/resources/factoryConfiguration.json create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/test/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImplTest.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/pom.xml create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImpl.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionActionTypes.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionTypes.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/resources/factoryConfiguration.json create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImplTest.java create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/resources/logback.xml create mode 100644 openecomp-be/lib/openecomp-item-permissions-lib/pom.xml create mode 100644 openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityType.java create mode 100644 openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ElementType.java create mode 100644 openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ItemType.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/pom.xml create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/destinationprovider/DestinationProvider.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/LastNotificationDao.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/NotificationsDao.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/SubscribersDao.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/LastSeenNotificationEntity.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/NotificationEntity.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/SubscribersEntity.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/Event.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/NotificationsStatus.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/exceptons/NotificationNotExistException.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/LastNotificationDaoFactory.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationPropagationManagerFactory.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsDaoFactory.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsServiceFactory.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/PropagationServiceFactory.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscribersDaoFactory.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscriptionServiceFactory.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationPropagationManager.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationsService.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/PropagationService.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/SubscriptionService.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/pom.xml create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestination.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/UnicastDestination.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/LastNotificationDaoCassandraImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/NotificationsDaoCassandraImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/SubscribersDaoCassandraImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/LastNotificationDaoFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationPropagationManagerFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsDaoFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsServiceFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/PropagationServiceFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscribersDaoFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscriptionServiceFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/SubscriptionServiceImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/resources/factoryConfiguration.json create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestinationTest.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImplTest.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImplTest.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImplTest.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/pom.xml create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/src/main/java/org/openecomp/sdc/notification/websocket/NotificationWebsocketHandler.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/pom.xml create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/config/ConfigurationManager.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationEntityDto.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationsStatusDto.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NewNotificationsReader.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationReceiver.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationWorker.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/impl/NewNotificationsReaderRestImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/factoryConfiguration.json create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/onboarding_configuration.yaml create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/java/org/openecomp/sdc/notification/workers/NotificationWorkerTest.java create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/logback.xml create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_1.csv create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_2.csv create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/onboarding_configuration.yaml create mode 100644 openecomp-be/lib/openecomp-sdc-notification-lib/pom.xml create mode 100644 openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseUtil.java create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 delete mode 100644 openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/UploadDataDao.java delete mode 100644 openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/UploadDataDaoFactory.java delete mode 100644 openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductDao.java delete mode 100644 openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductDaoFactory.java create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 delete mode 100644 openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/UploadData.java delete mode 100644 openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/UploadDataEntity.java delete mode 100644 openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductDaoFactoryImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductDaoImpl.java create mode 100644 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 create mode 100644 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 delete mode 100644 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/ElementPropertyName.java delete mode 100644 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/ElementType.java delete mode 100644 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/StructureElement.java create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 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 create mode 100644 openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/resources/factoryConfiguration.json create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManager.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManagerFactory.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningNotificationConstansts.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDao.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDaoFactory.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDao.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDaoFactory.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Revision.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/SynchronizationState.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionState.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/RevisionIdNotFoundErrorBuilder.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/Item.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/NotificationEventTypes.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionCreationMethod.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculator.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculatorFactory.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/ItemDaoFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionDaoFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/ItemZusammenDaoImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/convertor/ItemVersionToVersionConvertor.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/resources/factoryConfiguration.json create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImplTest.java create mode 100644 openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/ItemManagerImplTest.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/pom.xml delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/assembly/migration-lib-assembly.xml delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/MigrationMain.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/ComponentConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/EntitlementPoolConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/FeatureGroupConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/LKGConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/LicenseAgreementConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/MibConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/NetworkConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/NicConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/OrchestrationTemplateCandidateConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/ProcessConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VlmConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VspInformationConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VspServiceArtifactConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VspServiceTemplateConvertor.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ComponentCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/EntitlementPoolCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/FeatureGroupCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/LKGCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/LicenseAgreementCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/MibCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/NetworkCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/NicCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/OrchestrationTemplateCandidateCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ProcessCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ServiceArtifactCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ServiceTemplateCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VendorLicenseModelCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VendorSoftwareProductInfoLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VersionInfoCassandraLoader.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VspInformation.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/store/ElementHandler.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/store/ItemHandler.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/util/Utils.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/util/marker/MigrationMarker.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/util/marker/MigrationMarkerEntity.java delete mode 100644 openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/resources/logback.xml delete mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/ExportDataCommand.java delete mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/ImportCommand.java create mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/SetHealingFlag.java delete mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/ElementHandler.java delete mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/ImportProperties.java delete mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/ItemHandler.java delete mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/VersionHandler.java delete mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/ElementImport.java delete mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/ItemImport.java delete mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/TreeWalker.java delete mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/VersionImport.java delete mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/VersionInfoImport.java create mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exportinfo/ExportDataCommand.java create mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exportinfo/ExportSerializer.java create mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportDataCommand.java create mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportProperties.java create mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportSingleTable.java delete mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/loaders/zusammen/VspGeneralLoader.java delete mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/loaders/zusammen/VspItemLoader.java create mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/model/ColumnDefinition.java create mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/model/TableData.java create mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/HealingHandler.java create mode 100644 openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/HealingEntity.java create mode 100644 openecomp-be/tools/zusammen-tools/src/main/resources/queries.yaml create mode 100644 openecomp-be/tools/zusammen-tools/src/test/java/org/openecomp/core/tools/Commands/exportinfo/serialize/VLMExtractTest.java create mode 100644 openecomp-be/tools/zusammen-tools/src/test/resources/configuration.yaml create mode 100644 openecomp-be/tools/zusammen-tools/src/test/resources/queries.yaml delete mode 100644 openecomp-ui/resources/images/angle-left.svg delete mode 100644 openecomp-ui/resources/images/angle-right.svg delete mode 100644 openecomp-ui/resources/images/artifacts_icon.png delete mode 100644 openecomp-ui/resources/images/base_icon.png delete mode 100644 openecomp-ui/resources/images/download_icon.png delete mode 100644 openecomp-ui/resources/images/icons/ZIP_blue_icon.png delete mode 100644 openecomp-ui/resources/images/icons/ZIP_icon.png delete mode 100644 openecomp-ui/resources/images/icons/artifacts_blue_icon.png delete mode 100644 openecomp-ui/resources/images/icons/artifacts_grey_icon.png delete mode 100644 openecomp-ui/resources/images/icons/back_icon.png delete mode 100644 openecomp-ui/resources/images/icons/checked_in.png delete mode 100644 openecomp-ui/resources/images/icons/checked_out.png delete mode 100644 openecomp-ui/resources/images/icons/down_chevron.png delete mode 100644 openecomp-ui/resources/images/icons/env_icon.png delete mode 100644 openecomp-ui/resources/images/icons/env_icon_blue.png delete mode 100644 openecomp-ui/resources/images/icons/error_icon_big.png delete mode 100644 openecomp-ui/resources/images/icons/error_icon_small.png delete mode 100644 openecomp-ui/resources/images/icons/favicon.ico delete mode 100644 openecomp-ui/resources/images/icons/favicon.png delete mode 100644 openecomp-ui/resources/images/icons/go_to_overview_disable_icon.png delete mode 100644 openecomp-ui/resources/images/icons/go_to_overview_icon.png delete mode 100644 openecomp-ui/resources/images/icons/nested_HEAT_icon_blue.png delete mode 100644 openecomp-ui/resources/images/icons/nested_heat_icon.png delete mode 100644 openecomp-ui/resources/images/icons/network_blue_icon.png delete mode 100644 openecomp-ui/resources/images/icons/network_icon.png delete mode 100644 openecomp-ui/resources/images/icons/orphans_blue_icon-n.png delete mode 100644 openecomp-ui/resources/images/icons/orphans_grey_icon.png delete mode 100644 openecomp-ui/resources/images/icons/others_blue_icon.png delete mode 100644 openecomp-ui/resources/images/icons/others_icon.png delete mode 100644 openecomp-ui/resources/images/icons/pencil_icon-01.svg delete mode 100644 openecomp-ui/resources/images/icons/plus_vlm_summary_disabled_icon.png delete mode 100644 openecomp-ui/resources/images/icons/plus_vlm_summary_icon.png delete mode 100644 openecomp-ui/resources/images/icons/plus_vlm_summary_icon_blue.png delete mode 100644 openecomp-ui/resources/images/icons/revert_icon_disabled.png delete mode 100644 openecomp-ui/resources/images/icons/reverticon.png delete mode 100644 openecomp-ui/resources/images/icons/save_icon_disable.png delete mode 100644 openecomp-ui/resources/images/icons/saveicon.png delete mode 100644 openecomp-ui/resources/images/icons/submit_icon_disable.png delete mode 100644 openecomp-ui/resources/images/icons/submiticonactive.png delete mode 100644 openecomp-ui/resources/images/icons/vlm_list_view_blue_icon.png delete mode 100644 openecomp-ui/resources/images/icons/vlm_list_view_grey_icon.png delete mode 100644 openecomp-ui/resources/images/icons/volume_blue_icon.png delete mode 100644 openecomp-ui/resources/images/icons/volume_icon.png delete mode 100644 openecomp-ui/resources/images/icons/warning_icon_big.png delete mode 100644 openecomp-ui/resources/images/icons/warning_icon_small.png delete mode 100644 openecomp-ui/resources/images/module_icon.png delete mode 100644 openecomp-ui/resources/images/pencil_icon-01.svg delete mode 100644 openecomp-ui/resources/images/plus-circle-icon.svg delete mode 100644 openecomp-ui/resources/images/svg/angle-double-left.svg delete mode 100644 openecomp-ui/resources/images/svg/angle-double-right.svg delete mode 100644 openecomp-ui/resources/images/svg/angle-left.svg delete mode 100644 openecomp-ui/resources/images/svg/angle-right.svg delete mode 100644 openecomp-ui/resources/images/svg/back.svg delete mode 100644 openecomp-ui/resources/images/svg/calendar.svg delete mode 100644 openecomp-ui/resources/images/svg/caret-down.svg delete mode 100644 openecomp-ui/resources/images/svg/check-circle.svg delete mode 100644 openecomp-ui/resources/images/svg/check.svg delete mode 100644 openecomp-ui/resources/images/svg/chevron-down.svg delete mode 100644 openecomp-ui/resources/images/svg/chevron-up.svg delete mode 100644 openecomp-ui/resources/images/svg/close.svg delete mode 100644 openecomp-ui/resources/images/svg/error-circle.svg delete mode 100644 openecomp-ui/resources/images/svg/exclamation-triangle-full.svg delete mode 100644 openecomp-ui/resources/images/svg/exclamation-triangle-line.svg delete mode 100644 openecomp-ui/resources/images/svg/exclamation-triangle.svg delete mode 100644 openecomp-ui/resources/images/svg/filter.svg delete mode 100644 openecomp-ui/resources/images/svg/locked.svg delete mode 100644 openecomp-ui/resources/images/svg/pencil.svg delete mode 100644 openecomp-ui/resources/images/svg/plus-circle.svg delete mode 100644 openecomp-ui/resources/images/svg/plus.svg delete mode 100644 openecomp-ui/resources/images/svg/search.svg delete mode 100644 openecomp-ui/resources/images/svg/sliders.svg delete mode 100644 openecomp-ui/resources/images/svg/trash-o.svg delete mode 100644 openecomp-ui/resources/images/svg/unlocked.svg delete mode 100644 openecomp-ui/resources/images/svg/vendor.svg delete mode 100644 openecomp-ui/resources/images/svg/version-controller-lock-closed.svg delete mode 100644 openecomp-ui/resources/images/svg/version-controller-lock-open.svg delete mode 100644 openecomp-ui/resources/images/svg/version-controller-revert.svg delete mode 100644 openecomp-ui/resources/images/svg/version-controller-save.svg delete mode 100644 openecomp-ui/resources/images/svg/version-controller-submit.svg delete mode 100644 openecomp-ui/resources/images/svg/vlm.svg delete mode 100644 openecomp-ui/resources/images/svg/vsp.svg delete mode 100644 openecomp-ui/resources/images/trash_icon.png delete mode 100644 openecomp-ui/resources/images/upload_icon.png delete mode 100644 openecomp-ui/resources/images/v_icon.png delete mode 100644 openecomp-ui/resources/scss/bootstrap-cust/_buttons.scss delete mode 100644 openecomp-ui/resources/scss/bootstrap-cust/_navbar.scss delete mode 100644 openecomp-ui/resources/scss/bootstrap-cust/_navs.scss delete mode 100644 openecomp-ui/resources/scss/components/_buttons.scss create mode 100644 openecomp-ui/resources/scss/components/_commitModal.scss delete mode 100644 openecomp-ui/resources/scss/components/_icon.scss create mode 100644 openecomp-ui/resources/scss/components/_overlay.scss create mode 100644 openecomp-ui/resources/scss/components/_tree.scss create mode 100644 openecomp-ui/resources/scss/components/_userNotifications.scss create mode 100644 openecomp-ui/resources/scss/modules/_mergeEditor.scss create mode 100644 openecomp-ui/resources/scss/modules/_permissions.scss create mode 100644 openecomp-ui/resources/scss/modules/_revisions.scss create mode 100644 openecomp-ui/resources/scss/modules/_versionsPage.scss delete mode 100644 openecomp-ui/src/nfvo-components/icon/Icon.jsx create mode 100644 openecomp-ui/src/nfvo-components/overlay/Overlay.jsx delete mode 100644 openecomp-ui/src/nfvo-components/panel/versionController/VersionControllerUtils.js create mode 100644 openecomp-ui/src/nfvo-components/panel/versionController/components/ActionButtons.jsx create mode 100644 openecomp-ui/src/nfvo-components/panel/versionController/components/CommitCommentModal.jsx create mode 100644 openecomp-ui/src/nfvo-components/panel/versionController/components/Permissions.jsx create mode 100644 openecomp-ui/src/nfvo-components/tree/Tree.jsx create mode 100644 openecomp-ui/src/nfvo-components/tree/Tree.stories.js create mode 100644 openecomp-ui/src/nfvo-utils/WebSocketUtil.js create mode 100644 openecomp-ui/src/nfvo-utils/i18n/i18n.stories.js create mode 100644 openecomp-ui/src/sdc-app/common/helpers/ItemsHelper.js create mode 100644 openecomp-ui/src/sdc-app/common/helpers/ScreensHelper.js create mode 100644 openecomp-ui/src/sdc-app/common/merge/MergeEditor.js create mode 100644 openecomp-ui/src/sdc-app/common/merge/MergeEditorActionHelper.js create mode 100644 openecomp-ui/src/sdc-app/common/merge/MergeEditorConstants.js create mode 100644 openecomp-ui/src/sdc-app/common/merge/MergeEditorReducer.js create mode 100644 openecomp-ui/src/sdc-app/common/merge/MergeEditorView.jsx create mode 100644 openecomp-ui/src/sdc-app/onboarding/GridStyling.stories.js delete mode 100644 openecomp-ui/src/sdc-app/onboarding/onboard/CatalogTile.jsx create mode 100644 openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsActionHelper.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsConstants.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsManager.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsManager.jsx create mode 100644 openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsReducer.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/revisions/Revisions.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsActionHelper.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsConstants.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsReducer.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsView.jsx delete mode 100644 openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsList.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessListView.jsx create mode 100644 openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesEditorForm.jsx create mode 100644 openecomp-ui/src/sdc-app/onboarding/userNotifications/NotificationsReducer.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/userNotifications/NotificationsView.jsx create mode 100644 openecomp-ui/src/sdc-app/onboarding/userNotifications/UserNotifications.jsx create mode 100644 openecomp-ui/src/sdc-app/onboarding/userNotifications/UserNotificationsActionHelper.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/userNotifications/UserNotificationsConstants.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/users/UsersActionHelper.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/users/UsersConstants.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/users/UsersReducers.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPage.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPage.jsx create mode 100644 openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPageActionHelper.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPageConstants.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPageReducer.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/versionsPage/components/PermissionsView.jsx create mode 100644 openecomp-ui/src/sdc-app/onboarding/versionsPage/components/VersionList.jsx create mode 100644 openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreation.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationActionHelper.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationConstants.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationReducer.js create mode 100644 openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationView.jsx create mode 100644 openecomp-ui/test-utils/ShowMore.js create mode 100644 openecomp-ui/test-utils/factories/common/CurrentScreenFactory.js create mode 100644 openecomp-ui/test-utils/factories/common/VersionFactory.js create mode 100644 openecomp-ui/test-utils/factories/revisions/RevisionsFactories.js create mode 100644 openecomp-ui/test-utils/factories/users/UsersFactories.js create mode 100644 openecomp-ui/test-utils/factories/versionsPage/VersionsPageCreationFactories.js create mode 100644 openecomp-ui/test-utils/factories/versionsPage/VersionsPageFactories.js delete mode 100644 openecomp-ui/test/nfvo-components/panel/VersionController/versionControllerUtils.test.js create mode 100644 openecomp-ui/test/nfvo-components/tree/tree.test.js create mode 100644 openecomp-ui/test/permissions/permissionsManaager.test.js create mode 100644 openecomp-ui/test/revisions/revisions.test.js create mode 100644 openecomp-ui/test/softwareProduct/test.js create mode 100644 openecomp-ui/test/versionsPage/VersionsPage.test.js create mode 100644 openecomp-ui/test/versionsPage/creation/VersionsPageCreation.test.js diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java index b07a3c3d7b..5acb0e47c1 100644 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java @@ -39,13 +39,13 @@ import org.slf4j.LoggerFactory; import fj.data.Either; public class FileUtils { - static Logger logger = LoggerFactory.getLogger(Utils.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class.getName()); public static void writeToFile(String filePath, String content) { try { Files.write(Paths.get(filePath), content.getBytes()); } catch (IOException e) { - e.printStackTrace(); + LOGGER.debug(String.format("Failed to write to file '%s'", filePath), e); } } @@ -76,7 +76,7 @@ public class FileUtils { File file = new File(testResourcesPath); File[] listFiles = file.listFiles(); if (listFiles != null) { - List listFileName = new ArrayList(); + List listFileName = new ArrayList<>(); for (File newFile : listFiles) { if (newFile.isFile()) { listFileName.add(newFile.getPath()); @@ -100,7 +100,7 @@ public class FileUtils { public static String loadPayloadFileFromListUsingPosition(List listFileName, String pattern, Boolean isBase64, int positionInList) throws IOException { - List newList = new ArrayList(Arrays.asList(listFileName.get(positionInList))); + List newList = new ArrayList<>(Arrays.asList(listFileName.get(positionInList))); return loadPayloadFile(newList, pattern, isBase64); } @@ -109,7 +109,7 @@ public class FileUtils { String fileName; String payload = null; fileName = FileUtils.getFilePathFromListByPattern(listFileName, pattern); - logger.debug("fileName: {}",fileName); + LOGGER.debug("fileName: {}",fileName); if (fileName != null) { payload = Decoder.readFileToString(fileName); diff --git a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-api/src/main/java/org/openecomp/sdc/generator/aai/AaiModelGenerator.java b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-api/src/main/java/org/openecomp/sdc/generator/aai/AaiModelGenerator.java index f3c2cb97e7..4a1e781049 100644 --- a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-api/src/main/java/org/openecomp/sdc/generator/aai/AaiModelGenerator.java +++ b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-api/src/main/java/org/openecomp/sdc/generator/aai/AaiModelGenerator.java @@ -30,15 +30,12 @@ import static org.openecomp.sdc.generator.data.GeneratorConstants.PARTNER_NAME; import org.openecomp.sdc.generator.aai.model.Resource; import org.openecomp.sdc.generator.aai.model.Service; -import org.openecomp.sdc.generator.aai.model.Widget; import org.openecomp.sdc.generator.logging.CategoryLogLevel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; -import java.io.PrintWriter; import java.io.StringWriter; -import java.util.Arrays; public interface AaiModelGenerator { @@ -58,8 +55,7 @@ public interface AaiModelGenerator { MDC.put(ERROR_CODE, GENERATOR_ERROR_CODE); MDC.put(ERROR_DESCRIPTION, GENERATOR_ERROR_SERVICE_INSTANTIATION_FAILED); StringWriter sw = new StringWriter(); - exception.printStackTrace(new PrintWriter(sw)); - log.error(sw.toString()); + log.error(sw.toString(), exception); } return null; } diff --git a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-api/src/main/java/org/openecomp/sdc/generator/service/ArtifactGenerationService.java b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-api/src/main/java/org/openecomp/sdc/generator/service/ArtifactGenerationService.java index 2ac25273ce..1fbd25e14e 100644 --- a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-api/src/main/java/org/openecomp/sdc/generator/service/ArtifactGenerationService.java +++ b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-api/src/main/java/org/openecomp/sdc/generator/service/ArtifactGenerationService.java @@ -65,9 +65,7 @@ public interface ArtifactGenerationService { MDC.put(ERROR_CATEGORY, CategoryLogLevel.ERROR.name()); MDC.put(ERROR_CODE, GENERATOR_ERROR_CODE); MDC.put(ERROR_DESCRIPTION, GENERATOR_ERROR_SERVICE_INSTANTIATION_FAILED); - StringWriter sw = new StringWriter(); - exception.printStackTrace(new PrintWriter(sw)); - log.error(sw.toString()); + log.error(GENERATOR_ERROR_SERVICE_INSTANTIATION_FAILED, exception); } log.debug(GENERATOR_ERROR_SERVICE_INSTANTIATION_FAILED); return null; diff --git a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/aai/AaiArtifactGenerator.java b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/aai/AaiArtifactGenerator.java index 26b884e465..8462a71a97 100644 --- a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/aai/AaiArtifactGenerator.java +++ b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/aai/AaiArtifactGenerator.java @@ -560,7 +560,7 @@ public class AaiArtifactGenerator implements ArtifactGenerator { return tosca; } catch (Exception exception) { throw new IllegalArgumentException( - String.format(GeneratorConstants.GENERATOR_AAI_ERROR_INVALID_TOSCA, input.getName())); + String.format(GeneratorConstants.GENERATOR_AAI_ERROR_INVALID_TOSCA, input.getName()), exception); } } else { throw new SecurityException(GeneratorConstants.GENERATOR_AAI_ERROR_CHECKSUM_MISMATCH); diff --git a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/aai/AaiModelGeneratorImpl.java b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/aai/AaiModelGeneratorImpl.java index 7f4471c4c0..4e6153d7e4 100644 --- a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/aai/AaiModelGeneratorImpl.java +++ b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/aai/AaiModelGeneratorImpl.java @@ -33,7 +33,6 @@ import org.openecomp.sdc.generator.aai.xml.ModelVers; import org.openecomp.sdc.generator.aai.xml.Relationship; import org.openecomp.sdc.generator.aai.xml.RelationshipData; import org.openecomp.sdc.generator.aai.xml.RelationshipList; -import org.openecomp.sdc.generator.logging.annotations.Audit; import org.openecomp.sdc.generator.logging.annotations.Metrics; import org.w3c.dom.DOMException; @@ -271,12 +270,9 @@ public class AaiModelGeneratorImpl implements AaiModelGenerator { jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); jaxbMarshaller.marshal(model, modelStringWriter); } catch (JAXBException jaxbException) { - //jaxbException.printStackTrace(); - log.error(jaxbException.getMessage()); throw new DOMException(DOMException.SYNTAX_ERR, jaxbException.getMessage()); } - //System.out.println(modelStringWriter.toString()); return modelStringWriter.toString(); } } diff --git a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/util/ArtifactGeneratorUtil.java b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/util/ArtifactGeneratorUtil.java index aa3ce46013..26bbe7f619 100644 --- a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/util/ArtifactGeneratorUtil.java +++ b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/util/ArtifactGeneratorUtil.java @@ -163,7 +163,7 @@ public class ArtifactGeneratorUtil { String hostname = ip.getHostName(); MDC.put(BE_FQDN, hostname); } catch (UnknownHostException uhe) { - log.error("Failed to get server FQDN"); + log.error("Failed to get server FQDN", uhe); } if (log.isDebugEnabled()) { diff --git a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-test/src/main/java/org/openecomp/sdc/generator/ArtifactGenerationServiceTest.java b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-test/src/main/java/org/openecomp/sdc/generator/ArtifactGenerationServiceTest.java index ced8acbb80..38462d05bb 100644 --- a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-test/src/main/java/org/openecomp/sdc/generator/ArtifactGenerationServiceTest.java +++ b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-test/src/main/java/org/openecomp/sdc/generator/ArtifactGenerationServiceTest.java @@ -46,11 +46,16 @@ import static org.openecomp.sdc.generator.SampleJUnitTest.additionalParams; @SuppressWarnings("Duplicates") public class ArtifactGenerationServiceTest { + public static final String RESOURCE_MAPPING_NOT_FOUND = "Resource mapping not found for "; + public static final String INV_UID = "-INV_UID"; + public static final String VF_MODULE_NAMESPACE = "org.openecomp.groups.VfModule"; + public static final String VF_MODULE_DESCRIPTION = "vf_module_description"; + public static final String CATEGORY = "category"; static Map resourcesVersion = new HashMap<>(); public static Properties properties = new Properties(); @SuppressWarnings("Since15") - public static void validateName(List artifactList) { + public static void validateName(List artifactList) throws JAXBException { for(Artifact artifact : artifactList){ String xml = new String(Base64.getDecoder().decode(artifact.getPayload())); Model model = getUnmarshalledArtifactModel(xml); @@ -90,10 +95,10 @@ public class ArtifactGenerationServiceTest { String resourceVersion= resourcesVersion.get(toscaTemplate.getMetadata().get("UUID")); toscaTemplate.getMetadata().put("version", resourceVersion); if("VF".equals(toscaTemplate.getMetadata().get("type")) && !("Allotted Resource".equals - (toscaTemplate.getMetadata().get("category"))) ){ + (toscaTemplate.getMetadata().get(CATEGORY))) ){ testVfTosca(outputArtifactMap, toscaTemplate); } else if("VF".equals(toscaTemplate.getMetadata().get("type")) && ("Allotted Resource".equals - (toscaTemplate.getMetadata().get("category"))) ){ + (toscaTemplate.getMetadata().get(CATEGORY))) ){ testAllottedResourceTosca(outputArtifactMap, toscaTemplate); } else if("VL".equals(toscaTemplate.getMetadata().get("type"))){ testL3NetworkResourceTosca(outputArtifactMap, toscaTemplate); @@ -102,224 +107,212 @@ public class ArtifactGenerationServiceTest { } public static void testVfTosca(Map outputArtifactMap , ToscaTemplate resourceTosca) { - try { - //ToscaTemplate resourceTosca = getResourceTosca(toscas); - //resourceTosca.getTopology_template().getGroups(). - if (resourceTosca != null) { - Resource resource = new Resource(); - resource.populateModelIdentificationInformation(resourceTosca.getMetadata()); - String resourceNameVersionId = resource.getModelNameVersionId(); - Model resourceAAIModel = - getAAIModelByNameVersionId(resourceNameVersionId, outputArtifactMap); - if (resourceAAIModel != null) { - validateResourceModelMetadata(resource, resourceAAIModel); - //Validate Resource instance base widget - - ModelVer modelVersion = resourceAAIModel.getModelVers().getModelVer().get(0); - - List matchedVFBaseWidgetElements = - getModelElementbyRelationshipValue(modelVersion.getModelElements(), - Widget.getWidget(Widget.Type.VF).getId()); - validateMatchedModelElementsInService(matchedVFBaseWidgetElements, - Widget.getWidget(Widget.Type.VF).getName()); - - validateWidgetIds(matchedVFBaseWidgetElements, Widget.getWidget(Widget.Type.VF).getName(), - Widget.getWidget(Widget.Type.VF).getWidgetId()); - - ModelElements baseResourceWidgetModelElements = - matchedVFBaseWidgetElements.get(0).getModelElements(); - if (resourceTosca.getTopology_template() != null) { - Map groupIdTypeStore = getGroupsTypeStore(resourceTosca); - - if (baseResourceWidgetModelElements.getModelElement().size() != - groupIdTypeStore.size()) { - org.testng.Assert.fail("Missing VFModule in VF model.xml"); - } - for (String key : groupIdTypeStore.keySet()) { - - List matchedResourceElements = - getModelElementbyRelationshipValue(baseResourceWidgetModelElements, key); - validateMatchedModelElementsInService(matchedResourceElements, - Widget.getWidget(Widget.Type.VFMODULE).getName()); - Model resourceAAIVFModel = getAAIModelByNameVersionId(key, outputArtifactMap); - Map vfModuleModelMetadata = - getVFModuleMetadataTosca(resourceTosca, key); - Map vfModuleMembers = getVFModuleMembersTosca(resourceTosca, key); - - validateVFModelMetadata(vfModuleModelMetadata, resourceAAIVFModel); - - - ModelVer modelVfVersion = resourceAAIVFModel.getModelVers().getModelVer().get(0); - - List matchedVFModuleBaseWidgetElements = - getModelElementbyRelationshipValue(modelVfVersion.getModelElements(), - Widget.getWidget(Widget.Type.VFMODULE).getId()); - validateMatchedModelElementsInService(matchedVFModuleBaseWidgetElements, - Widget.getWidget(Widget.Type.VFMODULE).getName()); - validateWidgetIds(matchedVFModuleBaseWidgetElements, Widget.getWidget(Widget.Type.VFMODULE) - .getName(), Widget.getWidget(Widget.Type.VFMODULE).getWidgetId()); - - ModelElements baseResourceVFModuleWidgetModelElements = - matchedVFModuleBaseWidgetElements.get(0).getModelElements(); - if (vfModuleMembers.containsKey("l3-network")) { - //Validate l3 - List matchedL3NetworkElements = - getModelElementbyRelationshipValue(baseResourceVFModuleWidgetModelElements, - Widget.getWidget(Widget.Type.L3_NET).getId()); - validateMatchedModelElementsInService(matchedL3NetworkElements, - Widget.getWidget(Widget.Type.L3_NET).getName()); - validateWidgetIds(matchedL3NetworkElements, Widget.getWidget(Widget.Type.L3_NET) - .getName(), Widget.getWidget(Widget.Type.L3_NET).getWidgetId()); - } - if (vfModuleMembers.containsKey("vserver")) { - //Validate vserver - List matchedVserverElements = - getModelElementbyRelationshipValue(baseResourceVFModuleWidgetModelElements, - Widget.getWidget(Widget.Type.VSERVER).getId()); - validateMatchedModelElementsInService(matchedVserverElements, - Widget.getWidget(Widget.Type.VSERVER).getName()); - ModelElements vserverWidgetModelElements = - matchedVserverElements.get(0).getModelElements(); - - validateWidgetIds(matchedVserverElements, Widget.getWidget(Widget.Type.VSERVER) - .getName(), Widget.getWidget(Widget.Type.VSERVER).getWidgetId()); - - - //Validate vserver->vfc - List matchedVfcElements = - getModelElementbyRelationshipValue(vserverWidgetModelElements, - Widget.getWidget(Widget.Type.VFC).getId()); - validateMatchedModelElementsInService(matchedVfcElements, - Widget.getWidget(Widget.Type.VFC).getName()); - validateWidgetIds(matchedVfcElements, Widget.getWidget(Widget.Type.VFC).getName(), - Widget.getWidget(Widget.Type.VFC).getWidgetId()); - - //Validate vserver->Image - List matchedImageElements = - getModelElementbyRelationshipValue(vserverWidgetModelElements, - Widget.getWidget(Widget.Type.IMAGE).getId()); - validateMatchedModelElementsInService(matchedImageElements, - Widget.getWidget(Widget.Type.IMAGE).getName()); - validateWidgetIds(matchedImageElements, Widget.getWidget(Widget.Type.IMAGE) - .getName(), Widget.getWidget(Widget.Type.IMAGE).getWidgetId()); + if (resourceTosca != null) { + Resource resource = new Resource(); + resource.populateModelIdentificationInformation(resourceTosca.getMetadata()); + String resourceNameVersionId = resource.getModelNameVersionId(); + Model resourceAAIModel = + getAAIModelByNameVersionId(resourceNameVersionId, outputArtifactMap); + if (resourceAAIModel != null) { + validateResourceModelMetadata(resource, resourceAAIModel); + //Validate Resource instance base widget + + ModelVer modelVersion = resourceAAIModel.getModelVers().getModelVer().get(0); + + List matchedVFBaseWidgetElements = + getModelElementbyRelationshipValue(modelVersion.getModelElements(), + Widget.getWidget(Widget.Type.VF).getId()); + validateMatchedModelElementsInService(matchedVFBaseWidgetElements, + Widget.getWidget(Widget.Type.VF).getName()); + + validateWidgetIds(matchedVFBaseWidgetElements, Widget.getWidget(Widget.Type.VF).getName(), + Widget.getWidget(Widget.Type.VF).getWidgetId()); + + ModelElements baseResourceWidgetModelElements = + matchedVFBaseWidgetElements.get(0).getModelElements(); + if (resourceTosca.getTopology_template() != null) { + Map groupIdTypeStore = getGroupsTypeStore(resourceTosca); + + if (baseResourceWidgetModelElements.getModelElement().size() != + groupIdTypeStore.size()) { + org.testng.Assert.fail("Missing VFModule in VF model.xml"); + } + for (String key : groupIdTypeStore.keySet()) { - //Validate vserver->Flavor - List matchedFlavorElements = + List matchedResourceElements = + getModelElementbyRelationshipValue(baseResourceWidgetModelElements, key); + validateMatchedModelElementsInService(matchedResourceElements, + Widget.getWidget(Widget.Type.VFMODULE).getName()); + Model resourceAAIVFModel = getAAIModelByNameVersionId(key, outputArtifactMap); + Map vfModuleModelMetadata = + getVFModuleMetadataTosca(resourceTosca, key); + Map vfModuleMembers = getVFModuleMembersTosca(resourceTosca, key); + + validateVFModelMetadata(vfModuleModelMetadata, resourceAAIVFModel); + + + ModelVer modelVfVersion = resourceAAIVFModel.getModelVers().getModelVer().get(0); + + List matchedVFModuleBaseWidgetElements = + getModelElementbyRelationshipValue(modelVfVersion.getModelElements(), + Widget.getWidget(Widget.Type.VFMODULE).getId()); + validateMatchedModelElementsInService(matchedVFModuleBaseWidgetElements, + Widget.getWidget(Widget.Type.VFMODULE).getName()); + validateWidgetIds(matchedVFModuleBaseWidgetElements, Widget.getWidget(Widget.Type.VFMODULE) + .getName(), Widget.getWidget(Widget.Type.VFMODULE).getWidgetId()); + + ModelElements baseResourceVFModuleWidgetModelElements = + matchedVFModuleBaseWidgetElements.get(0).getModelElements(); + if (vfModuleMembers.containsKey("l3-network")) { + //Validate l3 + List matchedL3NetworkElements = + getModelElementbyRelationshipValue(baseResourceVFModuleWidgetModelElements, + Widget.getWidget(Widget.Type.L3_NET).getId()); + validateMatchedModelElementsInService(matchedL3NetworkElements, + Widget.getWidget(Widget.Type.L3_NET).getName()); + validateWidgetIds(matchedL3NetworkElements, Widget.getWidget(Widget.Type.L3_NET) + .getName(), Widget.getWidget(Widget.Type.L3_NET).getWidgetId()); + } + if (vfModuleMembers.containsKey("vserver")) { + //Validate vserver + List matchedVserverElements = + getModelElementbyRelationshipValue(baseResourceVFModuleWidgetModelElements, + Widget.getWidget(Widget.Type.VSERVER).getId()); + validateMatchedModelElementsInService(matchedVserverElements, + Widget.getWidget(Widget.Type.VSERVER).getName()); + ModelElements vserverWidgetModelElements = + matchedVserverElements.get(0).getModelElements(); + + validateWidgetIds(matchedVserverElements, Widget.getWidget(Widget.Type.VSERVER) + .getName(), Widget.getWidget(Widget.Type.VSERVER).getWidgetId()); + + + //Validate vserver->vfc + List matchedVfcElements = + getModelElementbyRelationshipValue(vserverWidgetModelElements, + Widget.getWidget(Widget.Type.VFC).getId()); + validateMatchedModelElementsInService(matchedVfcElements, + Widget.getWidget(Widget.Type.VFC).getName()); + validateWidgetIds(matchedVfcElements, Widget.getWidget(Widget.Type.VFC).getName(), + Widget.getWidget(Widget.Type.VFC).getWidgetId()); + + //Validate vserver->Image + List matchedImageElements = + getModelElementbyRelationshipValue(vserverWidgetModelElements, + Widget.getWidget(Widget.Type.IMAGE).getId()); + validateMatchedModelElementsInService(matchedImageElements, + Widget.getWidget(Widget.Type.IMAGE).getName()); + validateWidgetIds(matchedImageElements, Widget.getWidget(Widget.Type.IMAGE) + .getName(), Widget.getWidget(Widget.Type.IMAGE).getWidgetId()); + + + //Validate vserver->Flavor + List matchedFlavorElements = + getModelElementbyRelationshipValue(vserverWidgetModelElements, + Widget.getWidget(Widget.Type.FLAVOR).getId()); + validateMatchedModelElementsInService(matchedFlavorElements, + Widget.getWidget(Widget.Type.FLAVOR).getName()); + validateWidgetIds(matchedFlavorElements, Widget.getWidget(Widget.Type.FLAVOR).getName(), + Widget.getWidget(Widget.Type.FLAVOR).getWidgetId()); + + //Validate vserver->Tenant + List matchedTenantElements = + getModelElementbyRelationshipValue(vserverWidgetModelElements, + Widget.getWidget(Widget.Type.TENANT).getId()); + validateMatchedModelElementsInService(matchedTenantElements, + Widget.getWidget(Widget.Type.TENANT).getName()); + validateWidgetIds(matchedTenantElements, Widget.getWidget(Widget.Type.TENANT).getName(), + Widget.getWidget(Widget.Type.TENANT).getWidgetId()); + + //Validate vserver->l-interface + if (vfModuleMembers.containsKey("l-interface")) { + List matchedLinterfaceElements = getModelElementbyRelationshipValue(vserverWidgetModelElements, - Widget.getWidget(Widget.Type.FLAVOR).getId()); - validateMatchedModelElementsInService(matchedFlavorElements, - Widget.getWidget(Widget.Type.FLAVOR).getName()); - validateWidgetIds(matchedFlavorElements, Widget.getWidget(Widget.Type.FLAVOR).getName(), - Widget.getWidget(Widget.Type.FLAVOR).getWidgetId()); - - //Validate vserver->Tenant - List matchedTenantElements = + Widget.getWidget(Widget.Type.LINT).getId()); + validateMatchedModelElementsInService(matchedLinterfaceElements, + Widget.getWidget(Widget.Type.LINT).getName()); + validateWidgetIds(matchedLinterfaceElements, Widget.getWidget(Widget.Type.LINT).getName(), + Widget.getWidget(Widget.Type.LINT).getWidgetId()); + } + //Validate vserver->volume + if (vfModuleMembers.containsKey("volume")) { + List matchedVolumeElements = getModelElementbyRelationshipValue(vserverWidgetModelElements, - Widget.getWidget(Widget.Type.TENANT).getId()); - validateMatchedModelElementsInService(matchedTenantElements, - Widget.getWidget(Widget.Type.TENANT).getName()); - validateWidgetIds(matchedTenantElements, Widget.getWidget(Widget.Type.TENANT).getName(), - Widget.getWidget(Widget.Type.TENANT).getWidgetId()); - - //Validate vserver->l-interface - if (vfModuleMembers.containsKey("l-interface")) { - List matchedLinterfaceElements = - getModelElementbyRelationshipValue(vserverWidgetModelElements, - Widget.getWidget(Widget.Type.LINT).getId()); - validateMatchedModelElementsInService(matchedLinterfaceElements, - Widget.getWidget(Widget.Type.LINT).getName()); - validateWidgetIds(matchedLinterfaceElements, Widget.getWidget(Widget.Type.LINT).getName(), - Widget.getWidget(Widget.Type.LINT).getWidgetId()); - } - //Validate vserver->volume - if (vfModuleMembers.containsKey("volume")) { - List matchedVolumeElements = - getModelElementbyRelationshipValue(vserverWidgetModelElements, - Widget.getWidget(Widget.Type.VOLUME).getId()); - validateMatchedModelElementsInService(matchedVolumeElements, - Widget.getWidget(Widget.Type.VOLUME).getName()); - validateWidgetIds(matchedVolumeElements, Widget.getWidget(Widget.Type.VOLUME).getName(), - Widget.getWidget(Widget.Type.VOLUME).getWidgetId()); - } + Widget.getWidget(Widget.Type.VOLUME).getId()); + validateMatchedModelElementsInService(matchedVolumeElements, + Widget.getWidget(Widget.Type.VOLUME).getName()); + validateWidgetIds(matchedVolumeElements, Widget.getWidget(Widget.Type.VOLUME).getName(), + Widget.getWidget(Widget.Type.VOLUME).getWidgetId()); } } } - } else { - System.out.println("Resource mapping not found for " + resourceNameVersionId); } + } else { + System.out.println(RESOURCE_MAPPING_NOT_FOUND + resourceNameVersionId); } - - } catch (IllegalArgumentException e) { - org.testng.Assert.fail(e.getMessage()); //Can come while populating metadata } - } public static void testAllottedResourceTosca(Map outputArtifactMap , ToscaTemplate resourceTosca) { - try { - if (resourceTosca != null) { - Resource resource = new Resource(); - resource.populateModelIdentificationInformation(resourceTosca.getMetadata()); - String resourceNameVersionId = resource.getModelNameVersionId(); - Model resourceAAIModel = - getAAIModelByNameVersionId(resourceNameVersionId, outputArtifactMap); - if (resourceAAIModel != null) { - validateResourceModelMetadata(resource, resourceAAIModel); - //Validate Resource instance base widget - ModelVer modelVersion = resourceAAIModel.getModelVers().getModelVer().get(0); + if (resourceTosca != null) { + Resource resource = new Resource(); + resource.populateModelIdentificationInformation(resourceTosca.getMetadata()); + String resourceNameVersionId = resource.getModelNameVersionId(); + Model resourceAAIModel = + getAAIModelByNameVersionId(resourceNameVersionId, outputArtifactMap); + if (resourceAAIModel != null) { + validateResourceModelMetadata(resource, resourceAAIModel); + //Validate Resource instance base widget - List matchedVFBaseWidgetElements = - getModelElementbyRelationshipValue(modelVersion.getModelElements(), - Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getId()); - validateMatchedModelElementsInService(matchedVFBaseWidgetElements, - Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getName()); + ModelVer modelVersion = resourceAAIModel.getModelVers().getModelVer().get(0); - validateWidgetIds(matchedVFBaseWidgetElements, Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getName(), - Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getWidgetId()); + List matchedVFBaseWidgetElements = + getModelElementbyRelationshipValue(modelVersion.getModelElements(), + Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getId()); + validateMatchedModelElementsInService(matchedVFBaseWidgetElements, + Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getName()); - validateWidgetIds(matchedVFBaseWidgetElements, Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getName(), - Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getWidgetId()); + validateWidgetIds(matchedVFBaseWidgetElements, Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getName(), + Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getWidgetId()); - Map providingServiceDetails = getProvidingServiceDetails(resourceTosca); + validateWidgetIds(matchedVFBaseWidgetElements, Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getName(), + Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getWidgetId()); - ModelElements containedModelElements = modelVersion.getModelElements().getModelElement(). - get(0).getModelElements(); + Map providingServiceDetails = getProvidingServiceDetails(resourceTosca); - org.testng.Assert.assertEquals(containedModelElements.getModelElement().get(0).getRelationshipList() - .getRelationship().get(0).getRelationshipData().get(0).getRelationshipValue(), - providingServiceDetails.get("providing_service_uuid")); + ModelElements containedModelElements = modelVersion.getModelElements().getModelElement(). + get(0).getModelElements(); - org.testng.Assert.assertEquals(containedModelElements.getModelElement().get(0).getRelationshipList() - .getRelationship().get(0).getRelationshipData().get(1).getRelationshipValue(), - providingServiceDetails.get("providing_service_invariant_uuid")); + org.testng.Assert.assertEquals(containedModelElements.getModelElement().get(0).getRelationshipList() + .getRelationship().get(0).getRelationshipData().get(0).getRelationshipValue(), + providingServiceDetails.get("providing_service_uuid")); + org.testng.Assert.assertEquals(containedModelElements.getModelElement().get(0).getRelationshipList() + .getRelationship().get(0).getRelationshipData().get(1).getRelationshipValue(), + providingServiceDetails.get("providing_service_invariant_uuid")); - if("Allotted Resource".equals(resourceTosca.getMetadata().get("category")) && - "Tunnel XConnect".equals(resourceTosca.getMetadata().get("subcategory"))) { - List matchedTunnelXConnectWidgetElements = - getModelElementbyRelationshipValue(containedModelElements, - Widget.getWidget(Widget.Type.TUNNEL_XCONNECT).getId()); - validateMatchedModelElementsInService(matchedTunnelXConnectWidgetElements, - Widget.getWidget(Widget.Type.TUNNEL_XCONNECT).getName()); + if("Allotted Resource".equals(resourceTosca.getMetadata().get(CATEGORY)) && + "Tunnel XConnect".equals(resourceTosca.getMetadata().get("subcategory"))) { - validateWidgetIds(matchedTunnelXConnectWidgetElements, Widget.getWidget(Widget.Type.TUNNEL_XCONNECT).getName(), - Widget.getWidget(Widget.Type.TUNNEL_XCONNECT).getWidgetId()); - } + List matchedTunnelXConnectWidgetElements = + getModelElementbyRelationshipValue(containedModelElements, + Widget.getWidget(Widget.Type.TUNNEL_XCONNECT).getId()); + validateMatchedModelElementsInService(matchedTunnelXConnectWidgetElements, + Widget.getWidget(Widget.Type.TUNNEL_XCONNECT).getName()); - }else { - System.out.println("Resource mapping not found for " + resourceNameVersionId); + validateWidgetIds(matchedTunnelXConnectWidgetElements, Widget.getWidget(Widget.Type.TUNNEL_XCONNECT).getName(), + Widget.getWidget(Widget.Type.TUNNEL_XCONNECT).getWidgetId()); } - } - }catch (IllegalArgumentException e) { - org.testng.Assert.fail(e.getMessage()); //Can come while populating metadata + }else { + System.out.println(RESOURCE_MAPPING_NOT_FOUND + resourceNameVersionId); + } } - } public static Map getProvidingServiceDetails(ToscaTemplate resourceTemplate) { @@ -329,7 +322,7 @@ public class ArtifactGenerationServiceTest { for(String key : keys) { NodeTemplate node = resourceTemplate.getTopology_template().getNode_templates().get(key); if(node.getType().contains("org.openecomp.resource.vfc") && - node.getMetadata().get("category").equals("Allotted Resource")) { + node.getMetadata().get(CATEGORY).equals("Allotted Resource")) { nodeProperties = node.getProperties(); } } @@ -339,114 +332,102 @@ public class ArtifactGenerationServiceTest { public static void testL3NetworkResourceTosca(Map outputArtifactMap , ToscaTemplate resourceTosca) { - try { - if (resourceTosca != null) { - Resource resource = new Resource(); - resource.populateModelIdentificationInformation(resourceTosca.getMetadata()); - String resourceNameVersionId = resource.getModelNameVersionId(); - Model resourceAAIModel = - getAAIModelByNameVersionId(resourceNameVersionId, outputArtifactMap); - if (resourceAAIModel != null) { - validateResourceModelMetadata(resource, resourceAAIModel); - //Validate Resource instance base widget - - ModelVer modelVersion = resourceAAIModel.getModelVers().getModelVer().get(0); - - List matchedVFBaseWidgetElements = - getModelElementbyRelationshipValue(modelVersion.getModelElements(), - Widget.getWidget(Widget.Type.L3_NET).getId()); - validateMatchedModelElementsInService(matchedVFBaseWidgetElements, - Widget.getWidget(Widget.Type.L3_NET).getName()); - - validateWidgetIds(matchedVFBaseWidgetElements, Widget.getWidget(Widget.Type.L3_NET).getName(), - Widget.getWidget(Widget.Type.L3_NET).getWidgetId()); - }else { - System.out.println("Resource mapping not found for " + resourceNameVersionId); - } + if (resourceTosca != null) { + Resource resource = new Resource(); + resource.populateModelIdentificationInformation(resourceTosca.getMetadata()); + String resourceNameVersionId = resource.getModelNameVersionId(); + Model resourceAAIModel = + getAAIModelByNameVersionId(resourceNameVersionId, outputArtifactMap); + if (resourceAAIModel != null) { + validateResourceModelMetadata(resource, resourceAAIModel); + //Validate Resource instance base widget + + ModelVer modelVersion = resourceAAIModel.getModelVers().getModelVer().get(0); + + List matchedVFBaseWidgetElements = + getModelElementbyRelationshipValue(modelVersion.getModelElements(), + Widget.getWidget(Widget.Type.L3_NET).getId()); + validateMatchedModelElementsInService(matchedVFBaseWidgetElements, + Widget.getWidget(Widget.Type.L3_NET).getName()); + + validateWidgetIds(matchedVFBaseWidgetElements, Widget.getWidget(Widget.Type.L3_NET).getName(), + Widget.getWidget(Widget.Type.L3_NET).getWidgetId()); + + }else { + System.out.println(RESOURCE_MAPPING_NOT_FOUND + resourceNameVersionId); } - - }catch (IllegalArgumentException e) { - org.testng.Assert.fail(e.getMessage()); //Can come while populating metadata } - } public static void testServiceTosca(Map outputArtifactMap,List toscas) { - try { - ToscaTemplate serviceTosca = getServiceTosca(toscas); - if (serviceTosca == null) { - org.testng.Assert.fail("Service Tosca not found"); - } - serviceTosca.getMetadata().put("version", additionalParams.get(AdditionalParams - .ServiceVersion.getName())); - Service service = new Service(); - service.populateModelIdentificationInformation(serviceTosca.getMetadata()); - String serviceNameVersionId = service.getModelNameVersionId(); - Model serviceAAIModel = getAAIModelByNameVersionId(serviceNameVersionId, outputArtifactMap); - validateServiceModelMetadata(service, serviceAAIModel); - //Validate Service instance base widget - ModelVer modelVersion = serviceAAIModel.getModelVers().getModelVer().get(0); - - List matchedServiceBaseWidgetElements = - getModelElementbyRelationshipValue( modelVersion.getModelElements(), - Widget.getWidget(Widget.Type.SERVICE).getId()); - validateMatchedModelElementsInService(matchedServiceBaseWidgetElements, - Widget.getWidget(Widget.Type.SERVICE).getName()); - - validateWidgetIds(matchedServiceBaseWidgetElements, Widget.getWidget(Widget.Type.SERVICE).getName(), - Widget.getWidget(Widget.Type.SERVICE).getWidgetId()); - - ModelElements baseServiceWidgetModelElements = - matchedServiceBaseWidgetElements.get(0).getModelElements(); - - - Map nodeTemplateIdTypeStore = getNodeTemplateTypeStore(serviceTosca); - if (nodeTemplateIdTypeStore != null) { - for (String key : nodeTemplateIdTypeStore.keySet()) { - if (nodeTemplateIdTypeStore.get(key).contains("org.openecomp.resource.vf")) { - List matchedResourceElements = - getModelElementbyRelationshipValue(baseServiceWidgetModelElements, key); - if (nodeTemplateIdTypeStore.get(key).contains("org.openecomp.resource.vf.allottedResource")){ - validateMatchedModelElementsInService(matchedResourceElements, - Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getName()); - }else { - validateMatchedModelElementsInService(matchedResourceElements, - Widget.getWidget(Widget.Type.VF).getName()); - } - //Validate uuid and invariantuuid are populated in model-ver.model-version-id and model.model-invariant-id - org.testng.Assert.assertEquals(matchedResourceElements.get(0).getRelationshipList() - .getRelationship().get(0) - .getRelationshipData().get(0).getRelationshipValue(),key); - - org.testng.Assert.assertEquals(matchedResourceElements.get(0).getRelationshipList().getRelationship().get(0) - .getRelationshipData().get(1).getRelationshipValue(), nodeTemplateIdTypeStore - .get(key+"-INV_UID")); - } else if(nodeTemplateIdTypeStore.get(key).contains("org.openecomp.resource.vl")){ - //validate l3-network in service tosca - List matchedResourceElements = - getModelElementbyRelationshipValue(baseServiceWidgetModelElements, key); + ToscaTemplate serviceTosca = getServiceTosca(toscas); + if (serviceTosca == null) { + org.testng.Assert.fail("Service Tosca not found"); + } + serviceTosca.getMetadata().put("version", additionalParams.get(AdditionalParams + .ServiceVersion.getName())); + Service service = new Service(); + service.populateModelIdentificationInformation(serviceTosca.getMetadata()); + String serviceNameVersionId = service.getModelNameVersionId(); + Model serviceAAIModel = getAAIModelByNameVersionId(serviceNameVersionId, outputArtifactMap); + validateServiceModelMetadata(service, serviceAAIModel); + //Validate Service instance base widget + ModelVer modelVersion = serviceAAIModel.getModelVers().getModelVer().get(0); + + List matchedServiceBaseWidgetElements = + getModelElementbyRelationshipValue( modelVersion.getModelElements(), + Widget.getWidget(Widget.Type.SERVICE).getId()); + validateMatchedModelElementsInService(matchedServiceBaseWidgetElements, + Widget.getWidget(Widget.Type.SERVICE).getName()); + + validateWidgetIds(matchedServiceBaseWidgetElements, Widget.getWidget(Widget.Type.SERVICE).getName(), + Widget.getWidget(Widget.Type.SERVICE).getWidgetId()); + + ModelElements baseServiceWidgetModelElements = + matchedServiceBaseWidgetElements.get(0).getModelElements(); + + + Map nodeTemplateIdTypeStore = getNodeTemplateTypeStore(serviceTosca); + if (nodeTemplateIdTypeStore != null) { + for (Map.Entry entry : nodeTemplateIdTypeStore.entrySet()) { + if (entry.getValue().contains("org.openecomp.resource.vf")) { + List matchedResourceElements = + getModelElementbyRelationshipValue(baseServiceWidgetModelElements, entry.getKey()); + if (entry.getValue().contains("org.openecomp.resource.vf.allottedResource")){ validateMatchedModelElementsInService(matchedResourceElements, - Widget.getWidget(Widget.Type.L3_NET).getName()); - //Validate uuid and invariantuuid are populated in model-ver.model-version-id and model.model-invariant-id - org.testng.Assert.assertEquals(matchedResourceElements.get(0).getRelationshipList() - .getRelationship().get(0) - .getRelationshipData().get(0).getRelationshipValue(),key); - - org.testng.Assert.assertEquals(matchedResourceElements.get(0).getRelationshipList().getRelationship().get(0) - .getRelationshipData().get(1).getRelationshipValue(), nodeTemplateIdTypeStore - .get(key+"-INV_UID")); + Widget.getWidget(Widget.Type.ALLOTTED_RESOURCE).getName()); + }else { + validateMatchedModelElementsInService(matchedResourceElements, + Widget.getWidget(Widget.Type.VF).getName()); } - } - - - System.out.println(); + //Validate uuid and invariantuuid are populated in model-ver.model-version-id and model.model-invariant-id + org.testng.Assert.assertEquals(matchedResourceElements.get(0).getRelationshipList() + .getRelationship().get(0) + .getRelationshipData().get(0).getRelationshipValue(),entry.getKey()); + + org.testng.Assert.assertEquals(matchedResourceElements.get(0).getRelationshipList().getRelationship().get(0) + .getRelationshipData().get(1).getRelationshipValue(), nodeTemplateIdTypeStore + .get(entry.getKey()+ INV_UID)); + } else if(entry.getValue().contains("org.openecomp.resource.vl")){ + //validate l3-network in service tosca + List matchedResourceElements = + getModelElementbyRelationshipValue(baseServiceWidgetModelElements, entry.getKey()); + validateMatchedModelElementsInService(matchedResourceElements, + Widget.getWidget(Widget.Type.L3_NET).getName()); + //Validate uuid and invariantuuid are populated in model-ver.model-version-id and model.model-invariant-id + org.testng.Assert.assertEquals(matchedResourceElements.get(0).getRelationshipList() + .getRelationship().get(0) + .getRelationshipData().get(0).getRelationshipValue(),entry.getKey()); + + org.testng.Assert.assertEquals(matchedResourceElements.get(0).getRelationshipList().getRelationship().get(0) + .getRelationshipData().get(1).getRelationshipValue(), nodeTemplateIdTypeStore + .get(entry.getKey() + INV_UID)); + } } - } catch (IllegalArgumentException e) { - org.testng.Assert.fail(e.getMessage()); //Can come while populating metadata } } @@ -486,7 +467,7 @@ public class ArtifactGenerationServiceTest { } } if(e.getValue().getType().contains("org.openecomp.resource.vf.")&& (e.getValue() - .getMetadata().get("category").equals("Allotted Resource"))) + .getMetadata().get(CATEGORY).equals("Allotted Resource"))) { e.getValue().setType("org.openecomp.resource.vf.allottedResource"); } @@ -495,7 +476,7 @@ public class ArtifactGenerationServiceTest { ("version")); //Populate invraintUuId for V9 String invUuId = e.getValue().getMetadata().get("invariantUUID"); - nodeTemplateIdTypeStore.put(uuid+"-INV_UID" , invUuId); + nodeTemplateIdTypeStore.put(uuid + INV_UID , invUuId); } } return nodeTemplateIdTypeStore; @@ -511,7 +492,7 @@ public class ArtifactGenerationServiceTest { Map groupDefinitionIdTypeStore = new LinkedHashMap<>(); if (groupDefinitionMap != null) { for (Map.Entry e : groupDefinitionMap.entrySet()) { - if (e.getValue().getType().contains("org.openecomp.groups.VfModule")) { + if (e.getValue().getType().contains(VF_MODULE_NAMESPACE)) { String uuid = e.getValue().getMetadata().get("vfModuleModelUUID"); if (GeneratorUtil.isEmpty(uuid)) { uuid = e.getValue().getMetadata().get("UUID"); @@ -561,7 +542,7 @@ public class ArtifactGenerationServiceTest { .getModelVer().get(0).getModelName()); Assert.assertEquals(vfModuleModelMetadata.get("vfModuleModelVersion"), generatedAAIModel.getModelVers() .getModelVer().get(0).getModelVersion()); - Assert.assertEquals(vfModuleModelMetadata.get("vf_module_description"), generatedAAIModel.getModelVers() + Assert.assertEquals(vfModuleModelMetadata.get(VF_MODULE_DESCRIPTION), generatedAAIModel.getModelVers() .getModelVer().get(0).getModelDescription()); } @@ -590,7 +571,7 @@ public class ArtifactGenerationServiceTest { return matchedModelElements; } - public static void populateAAIGeneratedModelStore(Map outputArtifactMap,List resultData) { + public static void populateAAIGeneratedModelStore(Map outputArtifactMap,List resultData) throws JAXBException { for (Artifact outputArtifact : resultData) { if (outputArtifact.getType().equals(ArtifactType.MODEL_INVENTORY_PROFILE.name())) { byte[] decodedPayload = GeneratorUtil.decoder(outputArtifact.getPayload()); @@ -600,20 +581,16 @@ public class ArtifactGenerationServiceTest { } } - private static Model getUnmarshalledArtifactModel(String aaiModel) { + private static Model getUnmarshalledArtifactModel(String aaiModel) throws JAXBException { JAXBContext jaxbContext; - try { - jaxbContext = JAXBContext.newInstance(Model.class); - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - try (InputStream aaiModelStream = new ByteArrayInputStream(aaiModel.getBytes())) { - return (Model) unmarshaller.unmarshal(aaiModelStream); - } catch (IOException ignored) { /* ignore */ } + jaxbContext = JAXBContext.newInstance(Model.class); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - } catch (JAXBException e) { - e.printStackTrace(); - } - return null; + try (InputStream aaiModelStream = new ByteArrayInputStream(aaiModel.getBytes())) { + return (Model) unmarshaller.unmarshal(aaiModelStream); + } catch (IOException ignored) { /* ignore */ } + throw new RuntimeException("could not resolve artifact model"); } /** @@ -635,28 +612,15 @@ public class ArtifactGenerationServiceTest { } - private static ToscaTemplate getResourceTosca(List input) { - Iterator iter = input.iterator(); - while (iter.hasNext()) { - ToscaTemplate tosca = iter.next(); - if (!tosca.isService()) { - iter.remove(); - return tosca; - } - } - return null; - } - - private static Map getVFModuleMetadataTosca(ToscaTemplate toscaTemplate, String vfModuleModelUUID) { Map groupDefinitionMap = toscaTemplate.getTopology_template().getGroups(); Map vfModuleModelMetadata = new LinkedHashMap<>(); for (Map.Entry e : groupDefinitionMap.entrySet()) { - if (e.getValue().getType().contains("org.openecomp.groups.VfModule")) { + if (e.getValue().getType().contains(VF_MODULE_NAMESPACE)) { String uuid = e.getValue().getMetadata().get("vfModuleModelUUID"); if (uuid == vfModuleModelUUID) { vfModuleModelMetadata = e.getValue().getMetadata(); - vfModuleModelMetadata.put("vf_module_description", (String) e.getValue().getProperties().get("vf_module_description")); + vfModuleModelMetadata.put(VF_MODULE_DESCRIPTION, (String) e.getValue().getProperties().get(VF_MODULE_DESCRIPTION)); } } } @@ -667,9 +631,9 @@ public class ArtifactGenerationServiceTest { Map groupDefinitionMap = toscaTemplate.getTopology_template().getGroups(); Map nodeTemplateMaps = toscaTemplate.getTopology_template().getNode_templates(); Map vfModuleMembers = new LinkedHashMap<>(); - List vfModuleModelMetadata = new ArrayList<>(); + List vfModuleModelMetadata; for (Map.Entry e : groupDefinitionMap.entrySet()) { - if (e.getValue().getType().contains("org.openecomp.groups.VfModule")) { + if (e.getValue().getType().contains(VF_MODULE_NAMESPACE)) { String uuid = e.getValue().getMetadata().get("vfModuleModelUUID"); if (uuid == vfModuleModelUUID) { vfModuleModelMetadata = e.getValue().getMembers(); @@ -697,7 +661,7 @@ public class ArtifactGenerationServiceTest { private static String membersType(String toscaType) { String modelToBeReturned = null; - while (toscaType != null && toscaType.lastIndexOf(".") != -1 && modelToBeReturned == null) { + while (toscaType != null && toscaType.lastIndexOf('.') != -1 && modelToBeReturned == null) { switch (toscaType) { @@ -714,7 +678,7 @@ public class ArtifactGenerationServiceTest { case "org.openecomp.resource.vf": modelToBeReturned = "generic-vnf"; break; - case "org.openecomp.groups.VfModule": + case VF_MODULE_NAMESPACE: modelToBeReturned = "vf-module"; break; case "org.openecomp.resource.vfc.nodes.heat.cinder": diff --git a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-test/src/main/java/org/openecomp/sdc/generator/SampleJUnitTest.java b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-test/src/main/java/org/openecomp/sdc/generator/SampleJUnitTest.java index 6d44a37a92..089d773f94 100644 --- a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-test/src/main/java/org/openecomp/sdc/generator/SampleJUnitTest.java +++ b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-test/src/main/java/org/openecomp/sdc/generator/SampleJUnitTest.java @@ -38,32 +38,39 @@ import static org.openecomp.sdc.generator.data.GeneratorConstants.*; public class SampleJUnitTest extends TestCase { - public static final String aaiArtifactType = ArtifactType.AAI.name(); - public static final String aaiArtifactGroupType = GroupType.DEPLOYMENT.name(); - public static final String generatorConfig = "{\"artifactTypes\": [\"OTHER\",\"AAI\"]}"; - public static final String ARTIFACTGENERATOR_CONFIG = "artifactgenerator.config"; - public static final String CONFIG_PATH = "/qa-test-repo/jmeter3/apache-jmeter-3" + + private static final String AAI_ARTIFACT_TYPE = ArtifactType.AAI.name(); + private static final String AAI_ARTIFACT_GROUP_TYPE = GroupType.DEPLOYMENT.name(); + private static final String GENERATOR_CONFIG = "{\"artifactTypes\": [\"OTHER\",\"AAI\"]}"; + private static final String ARTIFACT_GENERATOR_CONFIG = "artifactgenerator.config"; + private static final String CONFIG_PATH = "/qa-test-repo/jmeter3/apache-jmeter-3" + ".0/lib/junit/"; - //public static final String CONFIG_PATH ="C:\\Jmeter-Copy\\jmeter3\\apache-jmeter-3" + - //".0\\lib\\junit\\"; - public static final String GENERATOR_AAI_CONFIGLPROP_NOT_FOUND = + private static final String GENERATOR_AAI_CONFIGLPROP_NOT_FOUND = "Cannot generate artifacts. Widget configuration not found for %s"; - public static final String GENERATOR_AAI_CONFIGFILE_NOT_FOUND = + private static final String GENERATOR_AAI_CONFIGFILE_NOT_FOUND = "Cannot generate artifacts. Artifact Generator Configuration file not found at %s"; - public static final String GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND = + private static final String GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND = "Cannot generate artifacts. artifactgenerator.config system property not configured"; - public static final String INVALID_VALUE_INVARIANT = + private static final String INVALID_VALUE_INVARIANT = "Invalid value for mandatory attribute in Artifact"; - public static final String INVALID_VALUE_UUID = + private static final String INVALID_VALUE_UUID = "Invalid value for mandatory attribute in Artifact:"; - public static final Map additionalParams = new HashMap<>(); + static final Map additionalParams = new HashMap<>(); + public static final String ARTIFACT_GENERATOR_PROPERTIES = "Artifact-Generator.properties"; + public static final String VF_VMME_TEMPLATE_NO_SYSTEM_PROP_CONFIGURED_YML = "vf_vmme_template_NoSystemPropConfigured.yml"; + public static final String SERVICE_VMME_TEMPLATE_NO_SYSTEM_PROP_CONFIGURED_YML = "service_vmme_template_NoSystemPropConfigured.yml"; static{ additionalParams.put(AdditionalParams.ServiceVersion.getName(),"1.0"); } + public SampleJUnitTest(String name) throws IOException { + super(name); + System.setProperty(ARTIFACT_GENERATOR_CONFIG,CONFIG_PATH + ARTIFACT_GENERATOR_PROPERTIES); + loadConfig(ArtifactGenerationServiceTest.properties); + } + private void loadConfig(Properties properties) throws IOException { - String configLocation = System.getProperty(ARTIFACTGENERATOR_CONFIG); + String configLocation = System.getProperty(ARTIFACT_GENERATOR_CONFIG); if (configLocation != null) { File file = new File(configLocation); if (file.exists()) { @@ -74,15 +81,10 @@ public class SampleJUnitTest extends TestCase { } } } - public SampleJUnitTest(String name) throws Exception { - super(name); - System.setProperty(ARTIFACTGENERATOR_CONFIG,CONFIG_PATH+"Artifact-Generator.properties"); - loadConfig(ArtifactGenerationServiceTest.properties); - } public SampleJUnitTest() { super(); - System.setProperty(ARTIFACTGENERATOR_CONFIG,CONFIG_PATH+"Artifact-Generator.properties"); + System.setProperty(ARTIFACT_GENERATOR_CONFIG,CONFIG_PATH + ARTIFACT_GENERATOR_PROPERTIES); } @Test @@ -95,7 +97,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -128,7 +130,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -161,7 +163,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -180,7 +182,7 @@ public class SampleJUnitTest extends TestCase { readPayloadFromResource(inputArtifacts2, "service_vmme_template_SameWidget2.yml"); ArtifactGenerationServiceImpl obj2 = new ArtifactGenerationServiceImpl(); - GenerationData data2 = obj2.generateArtifact(inputArtifacts2, generatorConfig,additionalParams); + GenerationData data2 = obj2.generateArtifact(inputArtifacts2, GENERATOR_CONFIG,additionalParams); List resultData2 = data2.getResultData(); List toscas2 = new LinkedList(); @@ -210,8 +212,8 @@ public class SampleJUnitTest extends TestCase { } } Assert.assertEquals(map.size(),map2.size()); - for(String name : map.keySet()){ - Assert.assertEquals(map.get(name),map2.get(name)); + for(Map.Entry entry : map.entrySet()){ + Assert.assertEquals(entry.getValue(), map2.get(entry.getKey())); } } catch (Exception e) { @@ -223,7 +225,6 @@ public class SampleJUnitTest extends TestCase { public void testArtifactGenerationMulVFModule() { try { List inputArtifacts = new ArrayList(); - String[] resourceFileList = {}; readPayloadFromResource(inputArtifacts, "vf_vmme_template_MulVFVFMod.yml"); readPayloadFromResource(inputArtifacts, "service_vmme_template_MulVFVFMod.yml"); @@ -231,7 +232,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -270,7 +271,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -303,7 +304,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -336,7 +337,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -368,7 +369,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -400,7 +401,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -431,7 +432,7 @@ public class SampleJUnitTest extends TestCase { readPayloadFromResource(inputArtifacts, "service_vmme_template_NullFields.yml"); ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); Assert.assertEquals(false,data.getErrorData().isEmpty()); Assert.assertEquals("Invalid Service/Resource definition mandatory attribute missing in Artifact: <"+inputArtifacts.get(0).getName()+">",data.getErrorData().get("AAI").get(0)); @@ -439,7 +440,6 @@ public class SampleJUnitTest extends TestCase { Assert.assertEquals(2,data.getResultData().size()); } catch (Exception e) { - e.printStackTrace(); Assert.fail(e.getMessage()); } } @@ -459,7 +459,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); Assert.assertEquals(false,data.getErrorData().isEmpty()); Assert.assertEquals("Invalid format for Tosca YML : "+inputArtifacts.get(1).getName(),data.getErrorData().get("AAI").get(0)); @@ -481,7 +481,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -517,7 +517,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -549,7 +549,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -587,7 +587,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -606,7 +606,6 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceTest.validateName(data.getResultData()); } catch (Exception e) { - e.printStackTrace(); Assert.fail(e.getMessage()); } } @@ -618,7 +617,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); Assert.assertEquals(false,data.getErrorData().isEmpty()); Assert.assertEquals("Service tosca missing from list of input artifacts",data.getErrorData().get("AAI").get(0)); @@ -665,7 +664,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -699,7 +698,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -733,7 +732,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -775,7 +774,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -811,7 +810,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -851,7 +850,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -891,7 +890,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -929,7 +928,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -971,7 +970,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -1004,7 +1003,7 @@ public class SampleJUnitTest extends TestCase { readPayloadFromResource(inputArtifacts, "service_vmme_template_WithInvIdGreaterThanSpecifiedLimit.yml"); ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); Assert.assertEquals(false,data.getErrorData().isEmpty()); Assert.assertEquals(INVALID_VALUE_INVARIANT + ": <" +inputArtifacts.get(1).getName()+">",data.getErrorData().get("AAI").get(0)); @@ -1012,7 +1011,6 @@ public class SampleJUnitTest extends TestCase { Assert.assertEquals(2,data.getResultData().size()); } catch (Exception e) { - e.printStackTrace(); Assert.fail(e.getMessage()); } } @@ -1026,7 +1024,7 @@ public class SampleJUnitTest extends TestCase { readPayloadFromResource(inputArtifacts, "service_vmme_template_WithInvIdLesserThanSpecifiedLimit.yml"); ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); Assert.assertEquals(false,data.getErrorData().isEmpty()); Assert.assertEquals(INVALID_VALUE_UUID + " <" @@ -1035,26 +1033,24 @@ public class SampleJUnitTest extends TestCase { Assert.assertEquals(2,data.getResultData().size()); } catch (Exception e) { - e.printStackTrace(); Assert.fail(e.getMessage()); } } @Test - public void testErrorWhenNoSystemPropConfigured() throws Exception { - String configLoc = System.getProperty(ARTIFACTGENERATOR_CONFIG); + public void testErrorWhenNoSystemPropConfigured() { + String configLoc = System.getProperty(ARTIFACT_GENERATOR_CONFIG); try { List inputArtifacts = new ArrayList(); - readPayloadFromResource(inputArtifacts, "vf_vmme_template_NoSystemPropConfigured.yml"); + readPayloadFromResource(inputArtifacts, VF_VMME_TEMPLATE_NO_SYSTEM_PROP_CONFIGURED_YML); - readPayloadFromResource(inputArtifacts, "service_vmme_template_NoSystemPropConfigured.yml"); + readPayloadFromResource(inputArtifacts, SERVICE_VMME_TEMPLATE_NO_SYSTEM_PROP_CONFIGURED_YML); - System.clearProperty(ARTIFACTGENERATOR_CONFIG); + System.clearProperty(ARTIFACT_GENERATOR_CONFIG); - Map outputArtifactMap = new HashMap<>(); ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); Assert.assertEquals(false,data.getErrorData().isEmpty()); Assert.assertEquals(data.getErrorData(). get("AAI").get(0), GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND); @@ -1062,48 +1058,46 @@ public class SampleJUnitTest extends TestCase { Assert.fail(e.getMessage()); } finally{ - System.setProperty(ARTIFACTGENERATOR_CONFIG,configLoc); + System.setProperty(ARTIFACT_GENERATOR_CONFIG,configLoc); } } @Test - public void testErrorWhenNoFileAtConfigLocation() throws Exception { - String configLoc = System.getProperty(ARTIFACTGENERATOR_CONFIG); + public void testErrorWhenNoFileAtConfigLocation() { + String configLoc = System.getProperty(ARTIFACT_GENERATOR_CONFIG); try { List inputArtifacts = new ArrayList(); - readPayloadFromResource(inputArtifacts, "vf_vmme_template_NoSystemPropConfigured.yml"); + readPayloadFromResource(inputArtifacts, VF_VMME_TEMPLATE_NO_SYSTEM_PROP_CONFIGURED_YML); - readPayloadFromResource(inputArtifacts, "service_vmme_template_NoSystemPropConfigured.yml"); + readPayloadFromResource(inputArtifacts, SERVICE_VMME_TEMPLATE_NO_SYSTEM_PROP_CONFIGURED_YML); - System.setProperty(ARTIFACTGENERATOR_CONFIG,configLoc + File.separator + "testErrorWhenNoFileAtConfigLocation"); - Map outputArtifactMap = new HashMap<>(); + System.setProperty(ARTIFACT_GENERATOR_CONFIG,configLoc + File.separator + "testErrorWhenNoFileAtConfigLocation"); ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); Assert.assertEquals(data.getErrorData().isEmpty(),false); Assert.assertEquals(data.getErrorData().get("AAI").get(0),String.format( GENERATOR_AAI_CONFIGFILE_NOT_FOUND,System.getProperty - (ARTIFACTGENERATOR_CONFIG))); + (ARTIFACT_GENERATOR_CONFIG))); } catch (Exception e) { Assert.fail(e.getMessage()); } finally{ - System.setProperty(ARTIFACTGENERATOR_CONFIG,configLoc); + System.setProperty(ARTIFACT_GENERATOR_CONFIG,configLoc); } } @Test - public void testErrorWhenNoWidgetInConfig() throws Exception { - System.setProperty(ARTIFACTGENERATOR_CONFIG,CONFIG_PATH+"Artifact-Generator1.properties"); + public void testErrorWhenNoWidgetInConfig() throws IOException { + System.setProperty(ARTIFACT_GENERATOR_CONFIG,CONFIG_PATH+"Artifact-Generator1.properties"); loadConfig(ArtifactGenerationServiceTest.properties); try { List inputArtifacts = new ArrayList(); - readPayloadFromResource(inputArtifacts, "vf_vmme_template_NoSystemPropConfigured.yml"); + readPayloadFromResource(inputArtifacts, VF_VMME_TEMPLATE_NO_SYSTEM_PROP_CONFIGURED_YML); - readPayloadFromResource(inputArtifacts, "service_vmme_template_NoSystemPropConfigured.yml"); + readPayloadFromResource(inputArtifacts, SERVICE_VMME_TEMPLATE_NO_SYSTEM_PROP_CONFIGURED_YML); - Map outputArtifactMap = new HashMap<>(); ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); String assertMsg = ArtifactType.AAI.name() + ".model-version-id." + Widget.getWidget (Widget.Type.SERVICE).getName(); @@ -1114,13 +1108,13 @@ public class SampleJUnitTest extends TestCase { } catch (Exception e) { Assert.fail(e.getMessage()); } finally { - System.setProperty(ARTIFACTGENERATOR_CONFIG, CONFIG_PATH+"Artifact-Generator.properties"); + System.setProperty(ARTIFACT_GENERATOR_CONFIG, CONFIG_PATH + ARTIFACT_GENERATOR_PROPERTIES); loadConfig(ArtifactGenerationServiceTest.properties); } } @Test - public void testArtifactGenerationWithUpdatedUUIDInConfig() throws Exception { + public void testArtifactGenerationWithUpdatedUUIDInConfig() throws IOException { try { List inputArtifacts = new ArrayList(); readPayloadFromResource(inputArtifacts, "vf_vmme_template_WithUpdatedUUIDInConfig.yml"); @@ -1128,7 +1122,7 @@ public class SampleJUnitTest extends TestCase { readPayloadFromResource(inputArtifacts, "service_vmme_template_WithUpdatedUUIDInConfig.yml"); ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); List toscas = new LinkedList(); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -1139,14 +1133,14 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceTest.testServiceTosca(outputArtifactMap, toscas); testResourceTosca(toscas.iterator(), outputArtifactMap); - System.setProperty(ARTIFACTGENERATOR_CONFIG,CONFIG_PATH+"Artifact-Generator2.properties"); + System.setProperty(ARTIFACT_GENERATOR_CONFIG,CONFIG_PATH+"Artifact-Generator2.properties"); loadConfig(ArtifactGenerationServiceTest.properties); List toscas2 = new LinkedList(); for (Artifact inputArtifact : inputArtifacts) { toscas2.add(getToscaModel(inputArtifact)); } - GenerationData data2 = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data2 = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); Map outputArtifactMap2 = new HashMap<>(); ArtifactGenerationServiceTest.populateAAIGeneratedModelStore(outputArtifactMap2, data2.getResultData()); @@ -1156,7 +1150,7 @@ public class SampleJUnitTest extends TestCase { } catch (Exception e) { Assert.fail(e.getMessage()); } finally { - System.setProperty(ARTIFACTGENERATOR_CONFIG,CONFIG_PATH+"Artifact-Generator.properties"); + System.setProperty(ARTIFACT_GENERATOR_CONFIG,CONFIG_PATH + ARTIFACT_GENERATOR_PROPERTIES); loadConfig(ArtifactGenerationServiceTest.properties); } } @@ -1170,8 +1164,7 @@ public class SampleJUnitTest extends TestCase { readPayloadFromResource(inputArtifacts, "service_vmme_template_VerifyMandatoryParameterServiceVersion.yml"); ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, new HashMap()); - List resultData = data.getResultData(); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, new HashMap()); Assert.assertEquals(data.getErrorData().isEmpty(),false); Assert.assertEquals(data.getErrorData().get("AAI").get(0),GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION); @@ -1190,23 +1183,20 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); additionalParams.put(AdditionalParams.ServiceVersion.getName(),"1"); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); - List resultData = data.getResultData(); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); Assert.assertEquals(data.getErrorData().isEmpty(),false); Assert.assertEquals(data.getErrorData().get("AAI").get(0),GENERATOR_AAI_INVALID_SERVICE_VERSION); additionalParams.put(AdditionalParams.ServiceVersion.getName(),"0.1"); - GenerationData data2 = obj.generateArtifact(inputArtifacts, generatorConfig, + GenerationData data2 = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); - List resultData2 = data.getResultData(); Assert.assertEquals(data2.getErrorData().isEmpty(),false); Assert.assertEquals(data2.getErrorData().get("AAI").get(0), GENERATOR_AAI_INVALID_SERVICE_VERSION); additionalParams.put(AdditionalParams.ServiceVersion.getName(),"0.0"); - GenerationData data3 = obj.generateArtifact(inputArtifacts, generatorConfig, + GenerationData data3 = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); - List resultData3 = data.getResultData(); Assert.assertEquals(data3.getErrorData().isEmpty(),false); Assert.assertEquals(data3.getErrorData().get("AAI").get(0), GENERATOR_AAI_INVALID_SERVICE_VERSION); @@ -1228,7 +1218,7 @@ public class SampleJUnitTest extends TestCase { List toscas = new LinkedList(); additionalParams.put(AdditionalParams.ServiceVersion.getName(),"9.0"); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -1270,8 +1260,7 @@ public class SampleJUnitTest extends TestCase { toscas.add(getToscaModel(inputArtifact)); } - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); - List resultData = data.getResultData(); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); Assert.assertEquals(data.getErrorData().isEmpty(),false); Assert.assertEquals(data.getErrorData().get("AAI").get(0), String.format(GENERATOR_AAI_ERROR_INVALID_RESOURCE_VERSION_IN_SERVICE_TOSCA, @@ -1280,9 +1269,8 @@ public class SampleJUnitTest extends TestCase { inputArtifacts.remove(1); readPayloadFromResource(inputArtifacts, "service_vmme_template_VerifyResourceVersionFormat2.yml"); - GenerationData data2 = obj.generateArtifact(inputArtifacts, generatorConfig, + GenerationData data2 = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); - List resultData2 = data2.getResultData(); Assert.assertEquals(data2.getErrorData().isEmpty(),false); Assert.assertEquals(data2.getErrorData().get("AAI").get(0), String.format(GENERATOR_AAI_ERROR_INVALID_RESOURCE_VERSION_IN_SERVICE_TOSCA, @@ -1306,8 +1294,7 @@ public class SampleJUnitTest extends TestCase { toscas.add(getToscaModel(inputArtifact)); } - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); - List resultData = data.getResultData(); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); Assert.assertEquals(data.getErrorData().isEmpty(),false); Assert.assertEquals(data.getErrorData().get("AAI").get(0),String.format(GENERATOR_AAI_ERROR_NULL_RESOURCE_VERSION_IN_SERVICE_TOSCA,toscas.get(0).getMetadata().get("UUID"))); } catch (Exception e) { @@ -1330,9 +1317,8 @@ public class SampleJUnitTest extends TestCase { for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); } - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); - List resultData = data.getResultData(); Assert.assertEquals(data.getErrorData().isEmpty(),false); Assert.assertEquals(data.getErrorData().get("AAI").get(0),String.format (GENERATOR_AAI_PROVIDING_SERVICE_MISSING, toscas.get(1).getModelId())); @@ -1354,7 +1340,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -1391,7 +1377,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -1427,7 +1413,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -1465,7 +1451,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); @@ -1509,8 +1495,7 @@ public class SampleJUnitTest extends TestCase { toscas.add(getToscaModel(inputArtifact)); } - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); - List resultData = data.getResultData(); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); Assert.assertEquals(data.getErrorData().isEmpty(),false); Assert.assertEquals(data.getErrorData().get("AAI").get(0),String.format (GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING, toscas.get(2).getModelId())); @@ -1537,7 +1522,7 @@ public class SampleJUnitTest extends TestCase { ArtifactGenerationServiceImpl obj = new ArtifactGenerationServiceImpl(); List toscas = new LinkedList(); - GenerationData data = obj.generateArtifact(inputArtifacts, generatorConfig, additionalParams); + GenerationData data = obj.generateArtifact(inputArtifacts, GENERATOR_CONFIG, additionalParams); for (Artifact inputArtifact : inputArtifacts) { toscas.add(getToscaModel(inputArtifact)); } @@ -1563,12 +1548,10 @@ public class SampleJUnitTest extends TestCase { fis.read(payload); String checksum = GeneratorUtil.checkSum(payload); byte[] encodedPayload = GeneratorUtil.encode(payload); - Artifact artifact = new Artifact(aaiArtifactType, aaiArtifactGroupType, checksum, encodedPayload); + Artifact artifact = new Artifact(AAI_ARTIFACT_TYPE, AAI_ARTIFACT_GROUP_TYPE, checksum, encodedPayload); artifact.setName(fileName); artifact.setLabel(fileName); artifact.setDescription(fileName); - //artifact.setVersion("1.0"); - System.out.println(artifact.getName()); inputArtifacts.add(artifact); } @@ -1580,14 +1563,13 @@ public class SampleJUnitTest extends TestCase { * @return Translated {@link ToscaTemplate tosca} object * @throws SecurityException */ - public static ToscaTemplate getToscaModel(Artifact input) throws SecurityException { + public static ToscaTemplate getToscaModel(Artifact input) { byte[] decodedInput = GeneratorUtil.decoder(input.getPayload()); String checksum = GeneratorUtil.checkSum(decodedInput); if (checksum.equals(input.getChecksum())) { try { return GeneratorUtil.translateTosca(new String(decodedInput), ToscaTemplate.class); } catch (Exception e) { - e.printStackTrace(); throw new IllegalArgumentException(String.format(GENERATOR_AAI_ERROR_INVALID_TOSCA, input.getName())); } } else { @@ -1603,15 +1585,6 @@ public class SampleJUnitTest extends TestCase { } } - /*public static void testResourceTosca(Iterator itr, Map outputArtifactMap) { - while(itr.hasNext()){ - ToscaTemplate toscaTemplate = itr.next(); - if("VF".equals(toscaTemplate.getMetadata().get("type"))){ - ArtifactGenerationServiceTest.testResourceTosca(outputArtifactMap, toscaTemplate); - } - } - }*/ - private void readPayloadFromResource(List inputArtifacts, String fileName) throws IOException { try (InputStream fis = SampleJUnitTest.class.getResourceAsStream("/" + fileName)) { diff --git a/onboarding/pom.xml b/onboarding/pom.xml index ee9c7ec5dc..5ed5e4ba33 100644 --- a/onboarding/pom.xml +++ b/onboarding/pom.xml @@ -94,17 +94,15 @@ 2.5 1.7.21 1.17 - 4.1.3.RELEASE - + 4.3.4.RELEASE 1.5.3 6.9.10 4.4.1 - 2.0.1 - - 0.2.4 - 0.2.4 - 0.2.4 - 0.2.4 + 2.0.1 + 0.3.0 + 0.3.0 + 0.3.0 + 0.3.0 5.8.1 ${project.version} 2.4.1.Final 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 5dc79ebdfe..5a7232bdd6 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 @@ -26,7 +26,6 @@ import io.swagger.annotations.ApiOperation; 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.Consumes; import javax.ws.rs.HeaderParam; @@ -38,6 +37,7 @@ 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; @Path("/workflow/v1.0/actions") 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 875b51548e..b186852bfd 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 @@ -31,7 +31,11 @@ import org.openecomp.sdc.action.errors.ActionErrorConstants; import org.openecomp.sdc.action.errors.ActionException; import org.openecomp.sdc.action.logging.CategoryLogLevel; import org.openecomp.sdc.action.logging.StatusCode; -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.ActionRequest; +import org.openecomp.sdc.action.types.OpenEcompComponent; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdcrests.action.rest.Actions; @@ -53,11 +57,85 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.util.*; - -import static org.openecomp.sdc.action.ActionConstants.*; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.*; -import static org.openecomp.sdc.action.util.ActionUtil.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.openecomp.sdc.action.ActionConstants.ACTION_REQUEST_PARAM_NAME; +import static org.openecomp.sdc.action.ActionConstants.ACTION_REQUEST_PARAM_SUPPORTED_MODELS; +import static org.openecomp.sdc.action.ActionConstants.ARTIFACT_FILE; +import static org.openecomp.sdc.action.ActionConstants.ARTIFACT_NAME; +import static org.openecomp.sdc.action.ActionConstants.BE_FQDN; +import static org.openecomp.sdc.action.ActionConstants.CATEGORY_LOG_LEVEL; +import static org.openecomp.sdc.action.ActionConstants.CLIENT_IP; +import static org.openecomp.sdc.action.ActionConstants.ERROR_DESCRIPTION; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_CATEGORY; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_MODEL; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_NAME; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_NONE; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_OPEN_ECOMP_COMPONENT; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_VENDOR; +import static org.openecomp.sdc.action.ActionConstants.INSTANCE_UUID; +import static org.openecomp.sdc.action.ActionConstants.LOCAL_ADDR; +import static org.openecomp.sdc.action.ActionConstants.MAX_ACTION_ARTIFACT_SIZE; +import static org.openecomp.sdc.action.ActionConstants.MDC_ASDC_INSTANCE_UUID; +import static org.openecomp.sdc.action.ActionConstants.PARTNER_NAME; +import static org.openecomp.sdc.action.ActionConstants.REMOTE_HOST; +import static org.openecomp.sdc.action.ActionConstants.REQUEST_EMPTY_BODY; +import static org.openecomp.sdc.action.ActionConstants.REQUEST_ID; +import static org.openecomp.sdc.action.ActionConstants.REQUEST_TYPE_CREATE_ACTION; +import static org.openecomp.sdc.action.ActionConstants.REQUEST_TYPE_UPDATE_ACTION; +import static org.openecomp.sdc.action.ActionConstants.REQUEST_TYPE_VERSION_ACTION; +import static org.openecomp.sdc.action.ActionConstants.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.action.ActionConstants.SERVICE_METRIC_BEGIN_TIMESTAMP; +import static org.openecomp.sdc.action.ActionConstants.SERVICE_NAME; +import static org.openecomp.sdc.action.ActionConstants.STATUS; +import static org.openecomp.sdc.action.ActionConstants.STATUS_CODE; +import static org.openecomp.sdc.action.ActionConstants.SUPPORTED_COMPONENTS_ID; +import static org.openecomp.sdc.action.ActionConstants.SUPPORTED_MODELS_VERSION_ID; +import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY; +import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY_API; +import static org.openecomp.sdc.action.ActionConstants.TARGET_SERVICE_NAME; +import static org.openecomp.sdc.action.ActionConstants.TIMESTAMP; +import static org.openecomp.sdc.action.ActionConstants.UPDATED_BY; +import static org.openecomp.sdc.action.ActionConstants.X_OPEN_ECOMP_INSTANCE_ID_HEADER_PARAM; +import static org.openecomp.sdc.action.ActionConstants.X_OPEN_ECOMP_REQUEST_ID_HEADER_PARAM; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_CHECKSUM_ERROR_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_INVALID_NAME; +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_READ_FILE_ERROR; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_TOO_BIG_ERROR; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_TOO_BIG_ERROR_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_NOT_EXIST; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_NOT_EXIST_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_FILTER_MULTIPLE_QUERY_PARAM_NOT_SUPPORTED; +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_REQUEST_ARTIFACT_CHECKSUM_ERROR; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_REQUEST_ARTIFACT_OPERATION_ALLOWED; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_REQUEST_BODY_EMPTY; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_REQUEST_CONTENT_TYPE_INVALID; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_REQUEST_FILTER_PARAM_INVALID; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_REQUEST_INVALID_GENERIC_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_REQUEST_INVALID_NAME; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_REQUEST_MISSING_MANDATORY_PARAM; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_REQUEST_OPEN_ECOMP_INSTANCE_ID_INVALID; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_REQUEST_OPEN_ECOMP_REQUEST_ID_INVALID; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UNSUPPORTED_OPERATION; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE_NOT_ALLOWED_CODE; +import static org.openecomp.sdc.action.util.ActionUtil.actionErrorLogProcessor; +import static org.openecomp.sdc.action.util.ActionUtil.actionLogPostProcessor; +import static org.openecomp.sdc.action.util.ActionUtil.getUtcDateStringFromTimestamp; /** * Implements various CRUD API that can be performed on Action diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/pom.xml deleted file mode 100644 index 10685dbac0..0000000000 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/pom.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - 4.0.0 - - activity-log-rest-services - - - org.openecomp.sdc - activity-log-rest - 1.2.0-SNAPSHOT - - - - - - - javax.ws.rs - javax.ws.rs-api - ${ws.rs.version} - - - org.springframework - spring-context - ${spring.framework.version} - - - javax.inject - javax.inject - 1 - - - org.openecomp.sdc - openecomp-sdc-activity-log-manager - ${project.version} - - - org.openecomp.sdc - activity-log-rest-types - ${project.version} - - - org.openecomp.sdc - openecomp-sdc-common-rest - ${project.version} - - - - org.apache.cxf - cxf-rt-frontend-jaxrs - ${cxf.version} - - - - - - diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/src/main/java/org/openecomp/sdcrests/activitylog/rest/ActivityLog.java b/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/src/main/java/org/openecomp/sdcrests/activitylog/rest/ActivityLog.java deleted file mode 100644 index be4cc1bbf5..0000000000 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/src/main/java/org/openecomp/sdcrests/activitylog/rest/ActivityLog.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdcrests.activitylog.rest; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import org.openecomp.sdcrests.activitylog.types.ActivityLogDto; -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/activity-logs") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -@Api(value = "Item Activity Log") -@Validated -public interface ActivityLog { - - @GET - @Path("/{itemId}/versions/{versionId}") - @ApiOperation(value = "List actions log of item", - response = ActivityLogDto.class, - responseContainer = "List") - Response getActivityLog(@ApiParam("Item Id") @PathParam("itemId") String itemId, - @ApiParam("Version Id") @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/activity-log-rest/activity-log-rest-services/src/main/java/org/openecomp/sdcrests/activitylog/rest/mapping/MapActivityLogEntityToActivityLogDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/src/main/java/org/openecomp/sdcrests/activitylog/rest/mapping/MapActivityLogEntityToActivityLogDto.java deleted file mode 100644 index 023dedf12c..0000000000 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/src/main/java/org/openecomp/sdcrests/activitylog/rest/mapping/MapActivityLogEntityToActivityLogDto.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdcrests.activitylog.rest.mapping; - -import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; -import org.openecomp.sdcrests.activitylog.types.ActivityLogDto; -import org.openecomp.sdcrests.activitylog.types.ActivityStatus; -import org.openecomp.sdcrests.mapping.MappingBase; - -public class MapActivityLogEntityToActivityLogDto extends MappingBase { - - - @Override - public void doMapping(ActivityLogEntity source, ActivityLogDto target) { - target.setId(source.getId()); - target.setTimestamp(source.getTimestamp()); - target.setType(source.getType()); - 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/activity-log-rest/activity-log-rest-services/src/main/java/org/openecomp/sdcrests/activitylog/rest/services/ActivityLogImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/src/main/java/org/openecomp/sdcrests/activitylog/rest/services/ActivityLogImpl.java deleted file mode 100644 index c42d72b7a5..0000000000 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-services/src/main/java/org/openecomp/sdcrests/activitylog/rest/services/ActivityLogImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdcrests.activitylog.rest.services; - -import org.openecomp.sdc.activityLog.ActivityLogManager; -import org.openecomp.sdc.activityLog.ActivityLogManagerFactory; -import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; -import org.openecomp.sdc.logging.context.MdcUtil; -import org.openecomp.sdc.logging.types.LoggerServiceName; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdcrests.activitylog.rest.ActivityLog; -import org.openecomp.sdcrests.activitylog.rest.mapping.MapActivityLogEntityToActivityLogDto; -import org.openecomp.sdcrests.activitylog.types.ActivityLogDto; -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("activityLog") -@Scope(value = "prototype") -public class ActivityLogImpl implements ActivityLog { - - private ActivityLogManager activityLogManager = - ActivityLogManagerFactory.getInstance().createInterface(); - - - @Override - public Response getActivityLog(String vspId, String versionId, String user) { - MdcUtil.initMdc(LoggerServiceName.Get_List_Activity_Log.toString()); - - Collection activityLogs = - activityLogManager.listActivityLogs(vspId, Version.valueOf(versionId), user); - - MapActivityLogEntityToActivityLogDto mapper = new MapActivityLogEntityToActivityLogDto(); - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); - for (ActivityLogEntity activityLog : activityLogs) { - results.add(mapper.applyMapping(activityLog, ActivityLogDto.class)); - } - - return Response.ok(results).build(); - } -} - diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/pom.xml deleted file mode 100644 index 70f029a0e3..0000000000 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/pom.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - 4.0.0 - - activity-log-rest-types - - - org.openecomp.sdc - activity-log-rest - 1.2.0-SNAPSHOT - - - diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityLogDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityLogDto.java deleted file mode 100644 index dde579554f..0000000000 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityLogDto.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdcrests.activitylog.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; - - public ActivityLogDto(){} - - public String getId() { return id; } - - public void setId(String id) { this.id = id; } - - public Date getTimestamp() { - return timestamp; - } - - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getComment() { - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public ActivityStatus getStatus() { - return status; - } - - public void setStatus(ActivityStatus status) { - this.status = status; - } -} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityStatus.java b/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityStatus.java deleted file mode 100644 index 326b1b624d..0000000000 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityStatus.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ -package org.openecomp.sdcrests.activitylog.types; - -public class ActivityStatus { - - private boolean success; - private String message; - - public ActivityStatus() { - } - - public ActivityStatus(boolean success) { - this(success, null); - } - - public ActivityStatus(boolean success, String message) { - this.success = success; - this.message = message; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityType.java b/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityType.java deleted file mode 100644 index 80160bc202..0000000000 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityType.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdcrests.activitylog.types; - -import java.io.Serializable; - -public enum ActivityType implements Serializable { - - CREATE_NEW("Create New"), - CHECKOUT("Check Out"), - UNDO_CHECKOUT("Undo Check Out"), - CHECKIN("Check In"), - UPLOAD_HEAT("Upload Heat"), - UPLOAD_MONITORING_FILE("Upload Monitoring File"), - SUBMIT("Submit"); - - // after collaboration will be added - this will be added: - /* - CREATE_NEW, - COMMIT, - ADD_PERMISSION, - REMOVE_PERMISSION, - */ - - private String name; - - ActivityType(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } -} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/pom.xml deleted file mode 100644 index 0b3c83c610..0000000000 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/pom.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - 4.0.0 - - org.openecomp.sdc - activity-log-rest - pom - - - org.openecomp.sdc - openecomp-sdc-rest-webapp - 1.2.0-SNAPSHOT - - - - activity-log-rest-services - activity-log-rest-types - - - 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 6c95a14319..6042060480 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 @@ -26,7 +26,6 @@ import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.openecomp.sdcrests.applicationconfiguration.types.ConfigurationDataDto; import org.springframework.validation.annotation.Validated; -import java.io.InputStream; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; @@ -36,6 +35,7 @@ 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.InputStream; @Path("/v1.0/application-configuration") @Produces(MediaType.APPLICATION_JSON) 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 c7f3f2598c..27557e1d56 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 @@ -38,10 +38,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import java.io.InputStream; -import java.util.Collection; 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. diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/pom.xml new file mode 100644 index 0000000000..534aea1a73 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + + + org.openecomp.sdc + conflict-rest + 1.2.0-SNAPSHOT + + + conflict-rest-services + + + + + + + org.openecomp.sdc + openecomp-sdc-common-rest + ${project.version} + + + javax.inject + javax.inject + 1 + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf.version} + + + org.openecomp.sdc + openecomp-sdc-conflict-manager + ${project.version} + + + org.openecomp.sdc + conflict-rest-types + ${project.version} + + + org.openecomp.sdc.onboarding + vendor-software-products-rest-services + ${project.version} + + + org.openecomp.sdc.onboarding + vendor-license-rest-services + ${project.version} + + + + + \ No newline at end of file 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 new file mode 100644 index 0000000000..396c4ee5d2 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/Conflicts.java @@ -0,0 +1,61 @@ +package org.openecomp.sdcrests.conflict.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +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.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; + +@Path("/v1.0/items/{itemId}/versions/{versionId}/conflicts") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +@Api(value = "Item Version Conflicts") +@Validated +public interface Conflicts { + + @GET + @Path("/") + @ApiOperation(value = "item version conflicts", + notes = "Item version private copy conflicts against its public copy", + response = ItemVersionConflictDto.class) + Response getConflict(@ApiParam("Item Id") @PathParam("itemId") String itemId, + @ApiParam("Version Id") @PathParam("versionId") String versionId, + @NotNull(message = RestConstants.USER_MISSING_ERROR_MSG) + @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); + + @GET + @Path("/{conflictId}") + @ApiOperation(value = "Gets item version conflict", + notes = "Gets an item version private copy conflict against its public copy", + response = ConflictDto.class) + Response getConflict(@ApiParam("Item Id") @PathParam("itemId") String itemId, + @ApiParam("Version Id") @PathParam("versionId") String versionId, + @ApiParam("Version Id") @PathParam("conflictId") String conflictId, + @NotNull(message = RestConstants.USER_MISSING_ERROR_MSG) + @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); + + @PUT + @Path("/{conflictId}") + @ApiOperation(value = "Resolves item version conflict", + notes = "Resolves an item version private copy conflict against its public copy") + Response resolveConflict(ConflictResolutionDto conflictResolution, + @ApiParam("Item Id") @PathParam("itemId") String itemId, + @ApiParam("Version Id") @PathParam("versionId") String versionId, + @ApiParam("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 new file mode 100644 index 0000000000..e80ef5653d --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapConflictInfoToDto.java @@ -0,0 +1,14 @@ +package org.openecomp.sdcrests.conflict.rest.mapping; + +import org.openecomp.conflicts.types.ConflictInfo; +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()); + } +} 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 new file mode 100644 index 0000000000..83a0f52155 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapConflictToDto.java @@ -0,0 +1,134 @@ +package org.openecomp.sdcrests.conflict.rest.mapping; + +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.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; + +import java.util.AbstractMap; +import java.util.HashMap; +import java.util.Map; + +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())); + } + + 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); + } + 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 new file mode 100644 index 0000000000..1a03a6b15e --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapDtoToConflictResolution.java @@ -0,0 +1,15 @@ +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 { + + @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 new file mode 100644 index 0000000000..fb5d013aba --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapItemVersionConflictToDto.java @@ -0,0 +1,22 @@ +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)); + + 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 new file mode 100644 index 0000000000..fda12ef4c6 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/services/ConflictsImpl.java @@ -0,0 +1,62 @@ +package org.openecomp.sdcrests.conflict.rest.services; + +import org.openecomp.conflicts.types.Conflict; +import org.openecomp.conflicts.types.ConflictResolution; +import org.openecomp.conflicts.types.ItemVersionConflict; +import org.openecomp.sdc.conflicts.ConflictsManager; +import org.openecomp.sdc.conflicts.ConflictsManagerFactory; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdcrests.conflict.rest.Conflicts; +import org.openecomp.sdcrests.conflict.rest.mapping.MapConflictToDto; +import org.openecomp.sdcrests.conflict.rest.mapping.MapDtoToConflictResolution; +import org.openecomp.sdcrests.conflict.rest.mapping.MapItemVersionConflictToDto; +import org.openecomp.sdcrests.conflict.types.ConflictDto; +import org.openecomp.sdcrests.conflict.types.ConflictResolutionDto; +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(); + + 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/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/pom.xml new file mode 100644 index 0000000000..e0169332c8 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + + org.openecomp.sdc + conflict-rest + 1.2.0-SNAPSHOT + + + conflict-rest-types + + + + org.openecomp.sdc + openecomp-sdc-conflict-manager + ${project.version} + + + \ No newline at end of file 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 new file mode 100644 index 0000000000..47f0abd794 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictDto.java @@ -0,0 +1,24 @@ +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; + } + + public void setYours(Map yours) { + this.yours = yours; + } + + public Map getTheirs() { + return 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 new file mode 100644 index 0000000000..e2e842a74e --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictInfoDto.java @@ -0,0 +1,33 @@ +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; + } + + public void setId(String id) { + this.id = id; + } + + public ElementType getType() { + return type; + } + + public void setType(ElementType type) { + this.type = type; + } + + public String getName() { + return 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 new file mode 100644 index 0000000000..1aaf18f859 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictResolutionDto.java @@ -0,0 +1,27 @@ +package org.openecomp.sdcrests.conflict.types; + +import org.openecomp.conflicts.types.Resolution; + +import java.util.Map; + +public class ConflictResolutionDto { + private Resolution resolution; + // sits in lower level... + private Map otherResolution; + + public Resolution getResolution() { + return resolution; + } + + public void setResolution(Resolution resolution) { + this.resolution = resolution; + } + + public Map getOtherResolution() { + return 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 new file mode 100644 index 0000000000..3dbfcf03cf --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ItemVersionConflictDto.java @@ -0,0 +1,29 @@ +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 ConflictDto getConflict() { + return conflict; + } + + public void setConflict(ConflictDto conflict) { + this.conflict = conflict; + } + + public Collection getConflictInfoList() { + return conflictInfoList; + } + + public void setConflictInfoList(Collection conflictInfoList) { + this.conflictInfoList = conflictInfoList; + } + + public void addConflictInfo(ConflictInfoDto conflictInfo){ + conflictInfoList.add(conflictInfo); + } +} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/pom.xml new file mode 100644 index 0000000000..d29b22a680 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + + + org.openecomp.sdc + openecomp-sdc-conflict-manager + ${project.version} + + + org.openecomp.sdc + openecomp-sdc-common-rest + ${project.version} + + + + + org.openecomp.sdc + openecomp-sdc-rest-webapp + 1.2.0-SNAPSHOT + + + conflict-rest + + pom + + + + conflict-rest-services + conflict-rest-types + + + \ No newline at end of file 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 446a80e3cc..4be72a5999 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 @@ -39,10 +39,10 @@ import javax.ws.rs.core.Response; @Validated public interface HealthCheck { - @GET - @ApiOperation(value = "Perform health check", - response = HealthInfoDtos.class, - responseContainer = "List") - Response checkHealth( ); + @GET + @ApiOperation(value = "Perform health check", + response = HealthInfoDtos.class, + responseContainer = "List") + 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/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 38858c0e7c..5bdc034673 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 @@ -21,6 +21,7 @@ package org.openecomp.sdcrests.health.rest.services; import org.apache.cxf.jaxrs.impl.ResponseBuilderImpl; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; import org.openecomp.sdc.health.HealthCheckManager; import org.openecomp.sdc.health.HealthCheckManagerFactory; import org.openecomp.sdc.health.data.HealthCheckResult; @@ -35,58 +36,60 @@ import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import java.util.Arrays; -import java.util.Collection; 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 HealthCheckManager healthCheckManager; + private static final Logger logger = LoggerFactory.getLogger(HealthCheckImpl.class); - 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(); + @Override + public Response checkHealth() { + HealthCheckResult healthCheckResult = new HealthCheckResult(); + SessionContextProviderFactory.getInstance().createInterface().create("public"); - try { - MdcUtil.initMdc(LoggerServiceName.Health_check.toString()); - 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(); - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); - 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(); - } + try { + MdcUtil.initMdc(LoggerServiceName.Health_check.toString()); + 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(); + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + 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/item-permissions-rest/item-permissions-rest-services/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/pom.xml new file mode 100644 index 0000000000..cec27da833 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + + org.openecomp.sdc + item-permissions-rest + 1.2.0-SNAPSHOT + + + item-permissions-rest-services + + + + + + org.openecomp.sdc + item-permissions-rest-types + ${project.version} + + + + org.openecomp.sdc + openecomp-sdc-common-rest + ${project.version} + + + + org.openecomp.sdc + openecomp-sdc-item-permissions-manager + ${project.version} + + + + javax.inject + javax.inject + 1 + + + + + + + + + + + + + + + + + io.swagger + swagger-models + RELEASE + + + org.springframework + spring-context + ${spring.framework.version} + + + + + \ No newline at end of file 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 new file mode 100644 index 0000000000..e73595c67b --- /dev/null +++ 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 @@ -0,0 +1,53 @@ +package org.openecomp.sdcrests.itempermissions.rest; + + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +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.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; + +/** + * Created by ayalaben on 6/18/2017. + */ +@Path("/v1.0/items/{itemId}/permissions") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +@Api(value = "Item Permissions") +@Validated +public interface ItemPermissions { + + @GET + @Path("/") + @ApiOperation(value = "List users permissions assigned on item", + response = ItemPermissionsDto.class, + responseContainer = "List") + + Response list(@PathParam("itemId") String itemId, + @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @PUT + @Path("/{permission}") + @ApiOperation(value = "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 new file mode 100644 index 0000000000..88c3d4d74e --- /dev/null +++ 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 @@ -0,0 +1,20 @@ +package org.openecomp.sdcrests.itempermissions.rest.mapping; + +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; +import org.openecomp.sdcrests.itempermissions.types.ItemPermissionsDto; +import org.openecomp.sdcrests.mapping.MappingBase; + +/** + * Created by ayalaben on 6/18/2017. + */ + +public class MapItemPermissionsToItemPermissionsDto extends + MappingBase { + + + @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 new file mode 100644 index 0000000000..4fe93c20ac --- /dev/null +++ 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 @@ -0,0 +1,52 @@ +//package org.openecomp.sdcrests.itempermissions.rest.mapping.mapping.services; +package org.openecomp.sdcrests.itempermissions.rest.services; + + +import org.openecomp.sdc.itempermissions.ItemPermissionsManager; +import org.openecomp.sdc.itempermissions.ItemPermissionsManagerFactory; +import org.openecomp.sdcrests.itempermissions.rest.ItemPermissions; +import org.openecomp.sdcrests.itempermissions.rest.mapping.MapItemPermissionsToItemPermissionsDto; +import org.openecomp.sdcrests.itempermissions.types.ItemPermissionsDto; +import org.openecomp.sdcrests.itempermissions.types.ItemPermissionsRequestDto; +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 ItemPermissionsManager itemPermissionsManager = + ItemPermissionsManagerFactory.getInstance().createInterface(); + + @Override + public Response list(String itemId, String user) { + + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + MapItemPermissionsToItemPermissionsDto mapper = new MapItemPermissionsToItemPermissionsDto(); + + itemPermissionsManager.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) { + + itemPermissionsManager.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/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-types/pom.xml new file mode 100644 index 0000000000..49f1f2b6d3 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-types/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + + + io.swagger + swagger-annotations + 1.5.3 + + + + + + org.openecomp.sdc + item-permissions-rest + 1.2.0-SNAPSHOT + + + item-permissions-rest-types + + + \ No newline at end of file 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 new file mode 100644 index 0000000000..d7f0b9f259 --- /dev/null +++ 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 @@ -0,0 +1,27 @@ +package org.openecomp.sdcrests.itempermissions.types; + +/** + * Created by ayalaben on 6/18/2017. + */ +public class ItemPermissionsDto { + + private String userId; + private String permission; + + public String getUserId() { + return userId; + } + + public void setUserId(String id) { + this.userId = id; + } + + 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 new file mode 100644 index 0000000000..82a960c7fd --- /dev/null +++ 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 @@ -0,0 +1,32 @@ +package org.openecomp.sdcrests.itempermissions.types; + +import io.swagger.annotations.ApiModel; + +import java.util.Set; + +/** + * Created by ayalaben on 6/20/2017. + */ + +@ApiModel(value = "ItemPermissionsRequest") +public class ItemPermissionsRequestDto { + + private Set addedUsersIds; + private Set removedUsersIds; + + public Set getAddedUsersIds() { + return addedUsersIds; + } + + public void setAddedUsersIds(Set addedUsersIds) { + this.addedUsersIds = addedUsersIds; + } + + public Set getRemovedUsersIds() { + return removedUsersIds; + } + + public void setRemovedUsersIds(Set removedUsersIds) { + this.removedUsersIds = removedUsersIds; + } +} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/pom.xml new file mode 100644 index 0000000000..f89fb0760a --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + + + org.openecomp.sdc + openecomp-sdc-rest-webapp + 1.2.0-SNAPSHOT + + + org.openecomp.sdc + item-permissions-rest + + pom + + + + item-permissions-rest-types + item-permissions-rest-services + + + \ No newline at end of file diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/pom.xml new file mode 100644 index 0000000000..6b96a4d328 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + + org.openecomp.sdc + item-rest + 1.2.0-SNAPSHOT + + + item-rest-services + + + + org.openecomp.sdc + openecomp-sdc-item-permissions-manager + ${project.version} + + + org.openecomp.sdc + item-rest-types + ${project.version} + + + org.openecomp.sdc + openecomp-sdc-common-rest + ${project.version} + + + javax.inject + javax.inject + 1 + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf.version} + + + org.openecomp.sdc + openecomp-sdc-conflict-manager + ${project.version} + + + org.springframework + spring-context + ${spring.framework.version} + + + + + \ 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/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 new file mode 100644 index 0000000000..7d7b0854d9 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/Versions.java @@ -0,0 +1,88 @@ +package org.openecomp.sdcrests.item.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.openecomp.sdcrests.item.types.ActivityLogDto; +import org.openecomp.sdcrests.item.types.RevisionDto; +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; + +import javax.validation.constraints.NotNull; +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; + +@Path("/v1.0/items/{itemId}/versions") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +@Api(value = "Item Versions") +@Validated +public interface Versions { + + @GET + @Path("/") + @ApiOperation(value = "Lists item versions", + response = VersionDto.class, + responseContainer = "List") + Response list(@PathParam("itemId") String itemId, + @NotNull(message = USER_MISSING_ERROR_MSG) + @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @POST + @Path("/{versionId}") + @ApiOperation(value = "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}") + @ApiOperation(value = "Gets item version", response = 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") + @ApiOperation(value = "Gets item version activity log", + response = ActivityLogDto.class, + responseContainer = "List") + Response getActivityLog(@ApiParam("Item Id") @PathParam("itemId") String itemId, + @ApiParam("Version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) + @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @GET + @Path("/{versionId}/revisions") + @ApiOperation(value = "Gets item version revisions", response = RevisionDto.class, + responseContainer = "List") + 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") + @ApiOperation(value = "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 new file mode 100644 index 0000000000..307b555720 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapActivityLogEntityToDto.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdcrests.item.rest.mapping; + +import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; +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 { + + + @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 new file mode 100644 index 0000000000..26bd58d950 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapItemToDto.java @@ -0,0 +1,15 @@ +package org.openecomp.sdcrests.item.rest.mapping; + +import org.openecomp.sdc.versioning.types.Item; +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()); + } +} 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 new file mode 100644 index 0000000000..861f571c5f --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapRevisionToDto.java @@ -0,0 +1,15 @@ +package org.openecomp.sdcrests.item.rest.mapping; + +import org.openecomp.sdc.versioning.dao.types.Revision; +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()); + } +} 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 new file mode 100644 index 0000000000..5fbd9a9e8d --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapVersionToDto.java @@ -0,0 +1,20 @@ +package org.openecomp.sdcrests.item.rest.mapping; + +import org.openecomp.sdc.versioning.dao.types.Version; +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()); + } +} 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 new file mode 100644 index 0000000000..466734208d --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/VersionsImpl.java @@ -0,0 +1,270 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdcrests.item.rest.services; + +import org.openecomp.sdc.activitylog.ActivityLogManager; +import org.openecomp.sdc.activitylog.ActivityLogManagerFactory; +import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; +import org.openecomp.sdc.activitylog.dao.type.ActivityType; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.conflicts.ConflictsManager; +import org.openecomp.sdc.conflicts.ConflictsManagerFactory; +import org.openecomp.sdc.itempermissions.ItemPermissionsManager; +import org.openecomp.sdc.itempermissions.ItemPermissionsManagerFactory; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.logging.context.MdcUtil; +import org.openecomp.sdc.logging.types.LoggerServiceName; +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.ItemManager; +import org.openecomp.sdc.versioning.ItemManagerFactory; +import org.openecomp.sdc.versioning.VersioningManager; +import org.openecomp.sdc.versioning.VersioningManagerFactory; +import org.openecomp.sdc.versioning.dao.types.SynchronizationState; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.errors.RevisionIdNotFoundErrorBuilder; +import org.openecomp.sdc.versioning.types.NotificationEventTypes; +import org.openecomp.sdcrests.item.rest.Versions; +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.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.Map; + +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; + +@Named +@Service("versions") +@Scope(value = "prototype") +public class VersionsImpl implements Versions { + + private static final String COMMIT_ITEM_ACTION = "Commit_Item"; + private static final Logger LOGGER = LoggerFactory.getLogger(VersionsImpl.class); + + private ItemPermissionsManager permissionsManager = + ItemPermissionsManagerFactory.getInstance().createInterface(); + private ItemManager itemManager = + ItemManagerFactory.getInstance().createInterface(); + private VersioningManager versioningManager = + VersioningManagerFactory.getInstance().createInterface(); + private ConflictsManager conflictsManager = + ConflictsManagerFactory.getInstance().createInterface(); + private ActivityLogManager activityLogManager = + ActivityLogManagerFactory.getInstance().createInterface(); + private NotificationPropagationManager notifier = + NotificationPropagationManagerFactory.getInstance().createInterface(); + + @Override + public Response list(String itemId, String user) { + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + MapVersionToDto mapper = new MapVersionToDto(); + + versioningManager.list(itemId) + .forEach(version -> results.add(mapper.applyMapping(version, VersionDto.class))); + return Response.ok(results).build(); + } + + @Override + public Response create(VersionRequestDto request, String itemId, String baseVersionId, + String user) { + Version version = new Version(); + version.setBaseId(baseVersionId); + version.setDescription(request.getDescription()); + + version = versioningManager.create(itemId, version, request.getCreationMethod()); + + VersionDto versionDto = new MapVersionToDto().applyMapping(version, VersionDto.class); + + activityLogManager.logActivity(new ActivityLogEntity(itemId, version, + ActivityType.Create_Version, user, true, "", "")); + + return Response.ok(versionDto).build(); + } + + @Override + public Response get(String itemId, String versionId, String user) { + Version version = getVersion(itemId, new Version(versionId)); + VersionDto versionDto = new MapVersionToDto().applyMapping(version, VersionDto.class); + return Response.ok(versionDto).build(); + } + + @Override + public Response getActivityLog(String itemId, String versionId, String user) { + MdcUtil.initMdc(LoggerServiceName.Get_List_Activity_Log.toString()); + + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + MapActivityLogEntityToDto mapper = new MapActivityLogEntityToDto(); + + activityLogManager.listLoggedActivities(itemId, new Version(versionId)) + .forEach(loggedActivity -> results + .add(mapper.applyMapping(loggedActivity, ActivityLogDto.class))); + + return Response.ok(results).build(); + } + + @Override + public Response listRevisions(String itemId, String versionId, String user) { + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + MapRevisionToDto mapper = new MapRevisionToDto(); + + versioningManager.listRevisions(itemId, new Version(versionId)) + .forEach(revision -> results.add(mapper.applyMapping(revision, RevisionDto.class))); + return Response.ok(results).build(); + } + + @Override + public Response actOn(VersionActionRequestDto request, String itemId, String versionId, + String user) { + Version version = new Version(versionId); + switch (request.getAction()) { + case Sync: + sync(itemId, version); + break; + case Commit: + if (!permissionsManager.isAllowed(itemId, user, COMMIT_ITEM_ACTION)) { + return Response.status(Response.Status.FORBIDDEN) + .entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build(); + } + commit(request.getCommitRequest(), itemId, version, user); + break; + case Revert: + revert(request.getRevisionRequest(), itemId, versionId); + break; + case Reset: + throw new UnsupportedOperationException("Action reset not supported."); + default: + } + return Response.ok().build(); + } + + + private void revert(RevisionRequestDto request, String itemId, String versionId) { + if (request.getRevisionId() == null) { + throw new CoreException(new RevisionIdNotFoundErrorBuilder().build()); + } + + versioningManager.revert(itemId, new Version(versionId), request.getRevisionId()); + } + + private void sync(String itemId, Version version) { + versioningManager.sync(itemId, version); + conflictsManager.finalizeMerge(itemId, version); + } + + private void commit(CommitRequestDto request, String itemId, Version version, String user) { + + String message = request == null ? "" : request.getMessage(); + + versioningManager.publish(itemId, version, message); + notifyUsers(itemId, version, message, user, NotificationEventTypes.COMMIT); + + activityLogManager.logActivity(new ActivityLogEntity(itemId, version, + ActivityType.Commit, user, true, "", message)); + } + + private void notifyUsers(String itemId, Version version, String message, + String userName, NotificationEventTypes eventType) { + Map eventProperties = new HashMap<>(); + eventProperties.put(ITEM_NAME, itemManager.get(itemId).getName()); + eventProperties.put(ITEM_ID, itemId); + + Version ver = versioningManager.get(itemId, version); + eventProperties.put(VERSION_NAME, ver.getName()); + eventProperties.put(VERSION_ID, ver.getId()); + + eventProperties.put(SUBMIT_DESCRIPTION, message); + eventProperties.put(PERMISSION_USER, userName); + + Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId); + try { + notifier.notifySubscribers(syncEvent, userName); + } catch (Exception e) { + LOGGER.error("Failed to send sync notification to users subscribed o item '" + itemId); + } + } + + private class SyncEvent implements Event { + + private String eventType; + private String originatorId; + private Map attributes; + private String entityId; + + public SyncEvent(String eventType, String originatorId, + Map attributes, String entityId) { + this.eventType = eventType; + this.originatorId = originatorId; + this.attributes = attributes; + this.entityId = entityId; + } + + @Override + public String getEventType() { + return eventType; + } + + @Override + public String getOriginatorId() { + return originatorId; + } + + @Override + public Map getAttributes() { + return attributes; + } + + @Override + public String getEntityId() { + return entityId; + } + } + + private Version getVersion(String itemId, Version version) { + version = versioningManager.get(itemId, version); + + if (version.getState().getSynchronizationState() != SynchronizationState.Merging && + conflictsManager.isConflicted(itemId, version)) { // looks for sdc applicative conflicts + version.getState().setSynchronizationState(SynchronizationState.Merging); + } + return version; + } +} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/pom.xml new file mode 100644 index 0000000000..6b974809b2 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + + + org.openecomp.sdc + item-rest + 1.2.0-SNAPSHOT + + + item-rest-types + + + + org.openecomp.sdc + openecomp-sdc-versioning-api + ${project.version} + + + org.openecomp.sdc + openecomp-sdc-activity-log-manager + ${project.version} + + + org.openecomp.sdc + openecomp-sdc-conflict-manager + ${project.version} + + + + + \ No newline at end of file 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 new file mode 100644 index 0000000000..40fb91867e --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ActivityLogDto.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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; + + public ActivityLogDto() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Date getTimestamp() { + return timestamp; + } + + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public ActivityStatus getStatus() { + return 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/ActivityStatus.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ActivityStatus.java new file mode 100644 index 0000000000..601a211e5b --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ActivityStatus.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ +package org.openecomp.sdcrests.item.types; + +public class ActivityStatus { + + private boolean success; + private String message; + + public ActivityStatus() { + } + + public ActivityStatus(boolean success) { + this(success, null); + } + + public ActivityStatus(boolean success, String message) { + this.success = success; + this.message = message; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public String getMessage() { + return 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/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 new file mode 100644 index 0000000000..a1d46cbdf1 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/CommitRequestDto.java @@ -0,0 +1,13 @@ +package org.openecomp.sdcrests.item.types; + +public class CommitRequestDto { + private String message; + + public String getMessage() { + return 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/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 new file mode 100644 index 0000000000..afba96f6c8 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemCreationDto.java @@ -0,0 +1,22 @@ +package org.openecomp.sdcrests.item.types; + +public class ItemCreationDto { + private String itemId; + private VersionDto version; + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public VersionDto getVersion() { + return 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 new file mode 100644 index 0000000000..1eebf19750 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemDto.java @@ -0,0 +1,40 @@ +package org.openecomp.sdcrests.item.types; + +public class ItemDto { + private String id; + private String type; + private String name; + private String description; + + 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; + } +} 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 new file mode 100644 index 0000000000..241d28541e --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/RevisionDto.java @@ -0,0 +1,43 @@ +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; + } + + public void setId(String id) { + this.id = id; + } + + public void setMessage(String message) { + this.message = message; + } + + public void setTime(Date time) { + this.time = time; + } + + public String getMessage() { + return message; + } + + public Date getTime() { + return time; + } + + 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 new file mode 100644 index 0000000000..49ea9fc7f2 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/RevisionRequestDto.java @@ -0,0 +1,14 @@ +package org.openecomp.sdcrests.item.types; + +public class RevisionRequestDto { + + private String revisionId; + + public String getRevisionId() { + return 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 new file mode 100644 index 0000000000..2591560fbb --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/SubmitRequestDto.java @@ -0,0 +1,13 @@ +package org.openecomp.sdcrests.item.types; + +public class SubmitRequestDto { + private String message; + + public String getMessage() { + return 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 new file mode 100644 index 0000000000..c9d6f4e293 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionAction.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdcrests.item.types; + +public enum VersionAction { + Sync, + Commit, + Revert, + Reset +} 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 new file mode 100644 index 0000000000..98a5bb94ee --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionActionRequestDto.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdcrests.item.types; + +public class VersionActionRequestDto { + private VersionAction action; + private CommitRequestDto commitRequest; + + private RevisionRequestDto revisionRequest; + + public VersionAction getAction() { + return action; + } + + public void setAction(VersionAction action) { + this.action = action; + } + + public CommitRequestDto getCommitRequest() { + return commitRequest; + } + + public void setCommitRequest(CommitRequestDto commitRequest) { + this.commitRequest = commitRequest; + } + + public RevisionRequestDto getRevisionRequest() { + return 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 new file mode 100644 index 0000000000..a0c1942b03 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionDto.java @@ -0,0 +1,94 @@ +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; + +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; + } +} 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 new file mode 100644 index 0000000000..629bc2d2db --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionRequestDto.java @@ -0,0 +1,24 @@ +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; + } + + public void setDescription(String description) { + this.description = description; + } + + public VersionCreationMethod getCreationMethod() { + return creationMethod; + } + + public void setCreationMethod(VersionCreationMethod creationMethod) { + this.creationMethod = creationMethod; + } +} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/pom.xml new file mode 100644 index 0000000000..6623de8cce --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + + org.openecomp.sdc + openecomp-sdc-rest-webapp + 1.2.0-SNAPSHOT + + + item-rest + pom + + + + item-rest-services + item-rest-types + + + \ No newline at end of file diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/pom.xml new file mode 100644 index 0000000000..319b0285cb --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/pom.xml @@ -0,0 +1,161 @@ + + 4.0.0 + + org.openecomp.sdc.onboarding + notifications-fe + notification-war + war + + + org.openecomp.sdc + openecomp-sdc + ../../.. + 1.2.0-SNAPSHOT + + + + 4.3.4.RELEASE + 9.3.6.v20151106 + + + + + org.openecomp.sdc + openecomp-sdc-notification-websocket + ${project.version} + + + javax.servlet + servlet-api + ${javax.servlet.version} + + + + org.codehaus.jackson + jackson-jaxrs + ${org.codehaus.jackson.version} + + + org.codehaus.jackson + jackson-core-asl + ${org.codehaus.jackson.version} + + + javax.inject + javax.inject + 1 + + + org.eclipse.jetty + jetty-servlets + ${jetty.version} + + + + org.eclipse.jetty + jetty-util + ${jetty.version} + + + + javax.validation + validation-api + 1.0.0.GA + + + org.hibernate + hibernate-validator + 4.3.1.Final + + + javax.ws.rs + javax.ws.rs-api + 2.0.1 + + + org.codehaus.groovy + groovy + ${groovy.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + ch.qos.logback + logback-core + ${logback.version} + + + org.codehaus.janino + janino + compile + + + org.springframework + spring-context + ${spring.framework.version} + + + org.springframework + spring-core + ${spring.framework.version} + + + org.springframework + spring-web + ${spring.framework.version} + + + org.springframework + spring-aop + ${spring.framework.version} + + + org.springframework + spring-webmvc + ${spring.framework.version} + + + org.aspectj + aspectjweaver + 1.8.9 + + + org.aspectj + aspectjrt + 1.8.9 + + + org.aspectj + aspectjtools + 1.8.9 + + + org.apache.httpcomponents + httpclient + 4.3.6 + + + org.apache.cxf + cxf-rt-transports-http + 2.2.2 + + + + + + + + maven-war-plugin + 3.0.0 + + WEB-INF/lib/togglz*.jar + + + + + 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 new file mode 100644 index 0000000000..96300b5cbb --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/java/org/openecomp/server/listeners/OnboardingAppStartupListener.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.server.listeners; + + +import org.springframework.web.context.ContextLoaderListener; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +public class OnboardingAppStartupListener implements ServletContextListener { + + ContextLoaderListener springListener; + + @Override + public void contextInitialized(ServletContextEvent servletContextEvent) { + springListener = new ContextLoaderListener(); + springListener.initWebApplicationContext(servletContextEvent.getServletContext()); + } + + @Override + public void contextDestroyed(ServletContextEvent servletContextEvent) { + springListener.closeWebApplicationContext(servletContextEvent.getServletContext()); + } +} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/resources/keyfile.txt b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/resources/keyfile.txt new file mode 100644 index 0000000000..d6c2c253f8 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/resources/keyfile.txt @@ -0,0 +1,27 @@ +hfLSGGYWU2SyTlltV0HVwU6o3GtrtccAU8aFwq65OHsl6JeEAirXaNl73xz2uTrfiFqVJD7GTxXr +_qlY4BnLFZ7q3KNRZ0VQssjF_REjB8p7YMkEiTzbJL0pSaI6s0GRotuM432Jbsoksh8WZeui7svx +I_KD124t73d1EpIAQwHldZXRZEoDrLjfJUSCAcmsXSu5OlIMZDKOy7vR0aXPw6Dpn9sZBcpFHFQL +Xkp63yTf81snlVBGXApwS852_u4nEYmQrGQo9u6iLRg4dodOUD7wG7jbNB_KtmIspxL87i75hJ_0 +PXkLN8H2K14Rvk9ILYjdASpPOyVMK8avylRRyRy5HFBUJfeWk4YJEPus79Ol-j3QefWxX2hEOe_Y +AcA5xYgwsYylSARWcQ7aZ8M781-CNaM1yDkFCBRNLQoOo3k_yyspfHC0fOwIOPZdh9YiXIop3MAM +FC0SdPTUQrQxlF3IOC7tfEp7Wu2XezkcbIBe8mDy7dcYa87KqrL0zRju80R_gl-UCkxMLZpEKhnB +zWxjDNOGCC4VaLMrW6uREFlanw2yg3XAXZD2vl60r1WNUrRUJcYRs9FwNkdVhKH7o_D7GLXCxlEF +ltapyC4i1xgeXiEH35WrqlmS1PexaWkRloFmpLXY56D3iqg9RYrZnqQAift20LLQ_ZMFS_fOlb8w +pu-VqjifrOthE9B375Nq-_YdMCLRAdAXf5wiMC1AlimLE6gmE6cl0SopHpmtmLX--4jy8IUSOceG +xhTKpfO_7Gnn-V5m-ourtkj_UivEiM3eIyzilamlEtac50e-mg1sEHjPvAQd7p_oqaGd4NveSUeG +_WsLUZJgKI6Nu0545J1tDmlgZ4atd1b4Mkutl1CbijYg9c6Nu_zxMs9RwN9_-C3JJJxQpBUieXFY +f38PD62P8Ihb8VmNmBhOT8abRmH7Zx1adz6fcjFtaO0wSsfWr8M04W_GrbrGO_yr7GeJwqdYEP8r +rUoQWkNRuapL09KUHhHTdc8hQoCNUx4p2H2_ADA8j6gp62z54LUQDaTOHJI3Vs6mdfP7oDr2H_VK +LLWR7fHcDzS89opwtp7NO56jpmmq4q-U9kxpY1lMYJhKBuVMCm038l_eMGL35jD6OcgOCC2GL9U9 +wfyjwumJMNIND8I3viuyouMy_B5q00v27M2im6Q814Mg5Cw-RCiKy4kjhutkqTw8hXh7RLkm-QeJ +KlsrH98snwWLaw9LBeGoMbqzHzWl93inEsTyLutMPA8xSIj5kySLIcJCXq9-RMp8cnOYy8TY9Jix +oaB2u4ofHDDrrMzKY88ZPdMiGQX2BNdsOG6o4ifSVyyYwIWBtQvtO7SDvGhRUGEV1JHloBdIos0M +87SMERYd_UPKK_yl2RaqloQZRlDSgUR7i0hoqrhtPe5Ef4cJFX_CSt_oQnEu0JatwAuwybkLLPbO +mArd3rtrOh-uR_0Y77zb7Uw4H5_oX_ANIecH0sgRcvQESaq-ioYrvS94VqvxU8ByuxqxJLMo90Rc +oOAk3pq0b-16x_WRxWTfbnnNLDSQ_DwS-Xeav1nPwm-ELy1AVEQdpgbjONThjkZp3AuljaH_1Fs4 +u0A8HeCgIa4g7jsvIRxw6zLKspYENdvoHvQLWGRpaA-vfT3i3lR0MEu53v8M9hI8U8MqJo_J0xe6 +z2mtQWPiCLtW99vTqhKOm621_GNYmp10TEXVMkXumEk2rTgLBDaFEFwpgS5LqkEOObVChd9jx9oa +DW4LjhzO1EE5twGvbTiRAJsO6j5UNTonGFLLttYKq9CMvDiBZ8-whFGOM8D2qAWYiwDCI-dLqwat +jxQP1cYKGHMS2-VJ5QJa6EINEx2zo3VmnHYCE9gM71fC26018Y2T-sQfE1MRE9SU_Xma7Qbl5OBp +IflyJCTyhZfgFlqU9f2cq12bjoNuMrgOlKwap6325LGZK1XsmsHuHmASRE4-E-qmQY7GI9oJLmbl +425swlxRA-mr1eGZU0hK3ZFjz_4clBMLJBYMFYhdGzi4VYGPzaO0z0wNJzOQf3V5NbReFjxl \ No newline at end of file diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/beans-services.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/beans-services.xml new file mode 100644 index 0000000000..c41bc03473 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/beans-services.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/jetty-web.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/jetty-web.xml new file mode 100644 index 0000000000..443b6a1fd3 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/jetty-web.xml @@ -0,0 +1,8 @@ + + + + + /notification-api + diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/spring-mapper-servlet.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/spring-mapper-servlet.xml new file mode 100644 index 0000000000..2851d560ce --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/spring-mapper-servlet.xml @@ -0,0 +1,12 @@ + + + + + + + + + + diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/web.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..354fcbfac6 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,81 @@ + + + + + + contextConfigLocation + WEB-INF/beans-services.xml + + + + org.openecomp.server.listeners.OnboardingAppStartupListener + + + + cross-origin + org.eclipse.jetty.servlets.CrossOriginFilter + + allowedOrigins + * + + + allowedMethods + * + + + allowedHeaders + * + + + + cross-origin + /* + + + + spring-mapper + + org.springframework.web.servlet.DispatcherServlet + + 1 + + + + CXFServlet + CXF Servlet + + org.apache.cxf.transport.servlet.CXFServlet + + + redirects-list + + /docs/(\S)+\.json + + + + redirect-attributes + + javax.servlet.include.request_uri + + + + redirect-servlet-name + default + + 1 + + + + spring-mapper + /ws/* + + + CXFServlet + /* + + + diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/pom.xml new file mode 100644 index 0000000000..597b017b0f --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + + org.openecomp.sdc + notifications-rest + 1.2.0-SNAPSHOT + + + notifications-rest-services + + + + org.openecomp.sdc + openecomp-sdc-application-config-manager + ${project.version} + provided + + + org.openecomp.sdc + openecomp-sdc-common-rest + ${project.version} + + + javax.inject + javax.inject + 1 + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf.version} + + + org.openecomp.sdc + notifications-rest-types + ${project.version} + + + org.openecomp.sdc + openecomp-sdc-notification-api + ${project.version} + + + org.springframework + spring-context + ${spring.framework.version} + + + + + \ No newline at end of file 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 new file mode 100644 index 0000000000..41376b040f --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/mapping/MapNotificationsStatusToDto.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdcrests.notifications.rest.mapping; + +import com.datastax.driver.core.utils.UUIDs; +import org.openecomp.core.utilities.json.JsonUtil; +import org.openecomp.sdc.notification.dao.types.NotificationEntity; +import org.openecomp.sdc.notification.dtos.NotificationsStatus; +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 { + + 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)))); + target.setNotifications(entityDtos); + } + + private String extractDate(NotificationEntity notification) { + 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 new file mode 100644 index 0000000000..558453b7b6 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/mapping/MapNotificationsToDto.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdcrests.notifications.rest.mapping; + +import com.datastax.driver.core.utils.UUIDs; +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.core.utilities.json.JsonUtil; +import org.openecomp.sdc.notification.dao.types.NotificationEntity; +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); + @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)))); + target.setNotifications(entityDtos); + target.setLastScanned(source.get(0).getEventId()); + } + } + + private String extractDate(NotificationEntity notification) { + 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 new file mode 100644 index 0000000000..97199f604f --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/services/Notifications.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdcrests.notifications.rest.services; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.openecomp.sdcrests.notifications.types.NotificationsStatusDto; +import org.openecomp.sdcrests.notifications.types.UpdateNotificationResponseStatus; +import org.springframework.validation.annotation.Validated; + +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.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.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; + +@Path("/v1.0/notifications") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +@Api(value = "Notifications") +@Validated +public interface Notifications { + String LIMIT_QUERY_PARAM = "NOTIFICATION_ROWS_LIMIT"; + String END_OF_PAGE_QUERY_PARAM = "END_OF_PAGE_EVENT_ID"; + + @GET + @ApiOperation(value = "Retrive all user notifications", + response = NotificationsStatusDto.class, + responseContainer = "List") + 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("/{notificationId}") + @ApiOperation(value = "Mark notification as read", + response = UpdateNotificationResponseStatus.class) + Response markAsRead( + @ApiParam(value = "Notification Id") @PathParam("notificationId") String notificationId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) + throws InvocationTargetException, IllegalAccessException; + + @PUT + @Path("/last-seen/{notificationId}") + @ApiOperation(value = "Update Last Seen Notification", + response = UpdateNotificationResponseStatus.class) + Response updateLastSeenNotification( + @ApiParam(value = "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") + @ApiOperation(value = "Retrive user not delivered notifications", + response = NotificationsStatusDto.class, + responseContainer = "List") + 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 new file mode 100644 index 0000000000..8ff0ac0eea --- /dev/null +++ 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 @@ -0,0 +1,117 @@ +package org.openecomp.sdcrests.notifications.rest.services.impl; + +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.datatypes.error.ErrorMessage; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.logging.context.MdcUtil; +import org.openecomp.sdc.logging.types.LoggerServiceName; +import org.openecomp.sdc.notification.dao.types.NotificationEntity; +import org.openecomp.sdc.notification.dtos.NotificationsStatus; +import org.openecomp.sdc.notification.exceptons.NotificationNotExistException; +import org.openecomp.sdc.notification.factories.NotificationsServiceFactory; +import org.openecomp.sdc.notification.services.NotificationsService; +import org.openecomp.sdcrests.notifications.rest.mapping.MapNotificationsStatusToDto; +import org.openecomp.sdcrests.notifications.rest.mapping.MapNotificationsToDto; +import org.openecomp.sdcrests.notifications.rest.services.Notifications; +import org.openecomp.sdcrests.notifications.types.NotificationsStatusDto; +import org.openecomp.sdcrests.notifications.types.UpdateNotificationResponseStatus; +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 + */ +@Named +@Service("notifications") +@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(); + + @Override + public Response getNotifications(String user, UUID lastDelivered, UUID endOfPage) { + MdcUtil.initMdc(LoggerServiceName.notifications.toString()); + 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(); + try { + notificationsService.updateLastSeenNotification(user, UUID.fromString(notificationId)); + } catch (Exception 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())); + } + return Response.ok(updateNotificationResponseStatus).build(); + } + + @Override + 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())); + } + return Response.ok(updateNotificationResponseStatus).build(); + } + + @Override + public Response getNewNotificationsByOwnerId(String user, String eventId, String limitStr) { + MdcUtil.initMdc(LoggerServiceName.notifications.toString()); + + int limit = selectionLimit; + + if (Objects.nonNull(limitStr)) { + try { + limit = Integer.parseInt(limitStr); + } + catch (NumberFormatException f) { + LOGGER.error("Non numeric selection list size value specified: " + limitStr); + } + } + + 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/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/pom.xml new file mode 100644 index 0000000000..4a3300ad12 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + + + org.openecomp.sdc + openecomp-sdc-datatypes-lib + ${project.version} + + + + + org.openecomp.sdc + notifications-rest + 1.2.0-SNAPSHOT + + + notifications-rest-types + + + \ No newline at end of file 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 new file mode 100644 index 0000000000..d41deb3a4d --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationEntityDto.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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; + } +} 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 new file mode 100644 index 0000000000..a0273d51e0 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationResponseStatus.java @@ -0,0 +1,26 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdcrests.notifications.types; + +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 new file mode 100644 index 0000000000..182245cc12 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationsStatusDto.java @@ -0,0 +1,61 @@ +package org.openecomp.sdcrests.notifications.types; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * @author avrahamg + * @since June 29, 2017 + */ +public class NotificationsStatusDto { + private List notifications; + private List newEntries = new ArrayList<>(); + private UUID lastScanned; + private UUID endOfPage; + private long numOfNotSeenNotifications; + + public NotificationsStatusDto() { + } + + public List getNotifications() { + return notifications; + } + + public void setNotifications( + List notifications) { + this.notifications = notifications; + } + + public List getNewEntries() { + return newEntries; + } + + public void setNewEntries(List newEntries) { + this.newEntries = newEntries; + } + + public UUID getLastScanned() { + return lastScanned; + } + + public void setLastScanned(UUID lastScanned) { + this.lastScanned = lastScanned; + } + + public UUID getEndOfPage() { + return endOfPage; + } + + public void setEndOfPage(UUID endOfPage) { + this.endOfPage = endOfPage; + } + + public long getNumOfNotSeenNotifications() { + return numOfNotSeenNotifications; + } + + public void setNumOfNotSeenNotifications(long numOfNotSeenNotifications) { + this.numOfNotSeenNotifications = numOfNotSeenNotifications; + } +} 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 new file mode 100644 index 0000000000..9e985726dc --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/UpdateNotificationResponseStatus.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdcrests.notifications.types; + +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 static org.openecomp.sdcrests.notifications.types.NotificationResponseStatus.Failure; +import static org.openecomp.sdcrests.notifications.types.NotificationResponseStatus.Success; + +/** + * Created by TALIO on 4/27/2016. + */ +public class UpdateNotificationResponseStatus { + private Map> errors = new HashMap<>(); + private NotificationResponseStatus status = Success; + + public Map> getErrors() { + return errors; + } + + public void setErrors(Map> errors) { + this.errors = errors; + } + + public NotificationResponseStatus getStatus() { + return status; + } + + public void setStatus(NotificationResponseStatus status) { + this.status = status; + } + + public void addStructureError(String notificationId, ErrorMessage errorMessage) { + 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/notifications-rest/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/pom.xml new file mode 100644 index 0000000000..d35c5afbee --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + + + org.openecomp.sdc + openecomp-sdc-rest-webapp + 1.2.0-SNAPSHOT + + + org.openecomp.sdc + notifications-rest + + pom + + + + notifications-rest-types + notifications-rest-services + + + \ No newline at end of file diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/pom.xml index 84c4eb408a..32975b3ebf 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/pom.xml +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/pom.xml @@ -15,6 +15,11 @@ + + org.openecomp.sdc + item-rest-services + ${project.version} + org.openecomp.sdc.onboarding vendor-license-rest-services @@ -22,7 +27,12 @@ org.openecomp.sdc - activity-log-rest-services + openecomp-sdc-notification-api + ${project.version} + + + org.openecomp.sdc + openecomp-sdc-notification-core ${project.version} @@ -40,6 +50,21 @@ healthcheck-rest-services ${project.version} + + org.openecomp.sdc + conflict-rest-services + ${project.version} + + + org.openecomp.sdc + item-permissions-rest-services + ${project.version} + + + org.openecomp.sdc + notifications-rest-services + ${project.version} + org.openecomp.sdc application-config-rest-services @@ -106,6 +131,11 @@ janino compile + + org.springframework + spring-context + ${spring.framework.version} + org.springframework spring-core 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 18465cd00c..e10f6a57ab 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 @@ -23,9 +23,6 @@ package org.openecomp.server.filters; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import java.io.IOException; -import java.security.Principal; -import java.util.Base64; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -35,6 +32,9 @@ import javax.servlet.ServletResponse; 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; public class ActionAuthenticationFilter implements Filter { 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 82e4fa80d9..f54b06d46a 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 @@ -20,7 +20,6 @@ package org.openecomp.server.filters; -import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -29,6 +28,7 @@ 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 { diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/SessionContextFilter.java b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/SessionContextFilter.java new file mode 100644 index 0000000000..b317fa6bf5 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/SessionContextFilter.java @@ -0,0 +1,45 @@ +package org.openecomp.server.filters; + +import org.openecomp.sdc.common.session.SessionContextProvider; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; + +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 java.io.IOException; + +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; + +public class SessionContextFilter implements Filter { + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, + FilterChain filterChain) throws IOException, ServletException { + SessionContextProvider contextProvider = + SessionContextProviderFactory.getInstance().createInterface(); + + try { + if (servletRequest instanceof HttpServletRequest) { + String userName = ((HttpServletRequest) servletRequest).getHeader(USER_ID_HEADER_PARAM); + contextProvider.create(userName); + } + + filterChain.doFilter(servletRequest, servletResponse); + } finally { + contextProvider.close(); + } + } + + @Override + public void destroy() { + + } +} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/webapp/WEB-INF/beans-services.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/webapp/WEB-INF/beans-services.xml index 8f4a2db73e..e43fa017d8 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/webapp/WEB-INF/beans-services.xml +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/webapp/WEB-INF/beans-services.xml @@ -36,24 +36,14 @@ - - - - - + + + + @@ -75,9 +65,10 @@ - - + + + diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/webapp/WEB-INF/spring-mapper-servlet.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/webapp/WEB-INF/spring-mapper-servlet.xml new file mode 100644 index 0000000000..437df7945f --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/webapp/WEB-INF/spring-mapper-servlet.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/webapp/WEB-INF/web.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/webapp/WEB-INF/web.xml index 35865f988e..de88197a8a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/webapp/WEB-INF/web.xml +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/webapp/WEB-INF/web.xml @@ -22,6 +22,19 @@ org.openecomp.server.listeners.OnboardingAppStartupListener + + PermissionsFilter + org.openecomp.sdc.itempermissions.servlet.PermissionsFilter + + + PermissionsFilter + /v1.0/vendor-license-models/* + + + PermissionsFilter + /v1.0/vendor-software-products/* + + cross-origin org.eclipse.jetty.servlets.CrossOriginFilter @@ -68,6 +81,22 @@ LoggingServletFilter /* + + SessionContextFilter + org.openecomp.server.filters.SessionContextFilter + + + SessionContextFilter + /* + + + + spring-mapper + + org.springframework.web.servlet.DispatcherServlet + + 1 + CXFServlet @@ -94,7 +123,10 @@ 1 - + spring-mapper + /ws/* + + CXFServlet /* 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 7bc1082ebe..302af10dc2 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 @@ -21,10 +21,12 @@ package org.openecomp.sdcrests.common; public class RestConstants { - public static final String USER_ID_HEADER_PARAM = "USER_ID"; // 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"; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/types/VersionDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/types/VersionDto.java deleted file mode 100644 index b5b86c65a2..0000000000 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/types/VersionDto.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.openecomp.sdcrests.common.types; - -/** - * Created by SVISHNEV on 3/5/2017. - */ -public class VersionDto { - String id; - String label; - - public VersionDto(){ - - } - - public VersionDto(String id, String label) { - this.id = id; - this.label = label; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getLabel() { - return label; - } - - public void setLabel(String label) { - this.label = label; - } -} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/mapping/EchoMapMapping.java b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/mapping/EchoMapMapping.java new file mode 100644 index 0000000000..81c2f37a66 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/mapping/EchoMapMapping.java @@ -0,0 +1,14 @@ +package org.openecomp.sdcrests.mapping; + +import java.util.HashMap; + +/** + * Created by ayalaben on 9/12/2017 + */ +public class EchoMapMapping extends MappingBase,HashMap> { + + @Override +public void doMapping(HashMap source, HashMap 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/EchoMapping.java b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/mapping/EchoMapping.java new file mode 100644 index 0000000000..4e5a22e3c7 --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/mapping/EchoMapping.java @@ -0,0 +1,8 @@ +package org.openecomp.sdcrests.mapping; + +public class EchoMapping extends MappingBase { + @Override + public void doMapping(Object source, Object target) { + target = 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 2310c0f6ce..25c2be9158 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 @@ -23,15 +23,11 @@ package org.openecomp.sdcrests.mapping; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerServiceName; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - /** * 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 @@ -55,8 +51,6 @@ public abstract class MappingBase { * @return T - instance of type T */ - private final Logger logger = (Logger) LoggerFactory.getLogger(this.getClass().getName()); - public final T applyMapping(final S source, Class clazz) { T target = (T) instantiateTarget(clazz); if (source == null || target == null) { diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/pom.xml index 9970dfbdfd..d44e0c8b98 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/pom.xml +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/pom.xml @@ -22,8 +22,12 @@ /validation-rest /action-library-rest /application-config-rest - /activity-log-rest /healthcheck-rest + conflict-rest + item-permissions-rest + item-rest + notifications-fe + notifications-rest 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 b08bc10727..349f0bdecf 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 @@ -24,7 +24,6 @@ import io.swagger.annotations.Api; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.springframework.validation.annotation.Validated; -import java.io.InputStream; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; @@ -32,6 +31,7 @@ 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; @Path("/v1.0/validation") 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 fd5bea3380..399f665655 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 @@ -25,7 +25,6 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.validation.annotation.Validated; -import java.io.InputStream; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; @@ -33,6 +32,7 @@ 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; @Path("/v1.0/validation") 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 15675f14de..f43ff60b9f 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 @@ -39,10 +39,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import java.io.IOException; -import java.io.InputStream; import javax.inject.Named; import javax.ws.rs.core.Response; +import java.io.IOException; +import java.io.InputStream; @Named @Service("validation") diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/pom.xml index 643addc0aa..cec09f0e8f 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/pom.xml +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/pom.xml @@ -30,13 +30,13 @@ org.openecomp.sdc - openecomp-sdc-vendor-license-manager + openecomp-sdc-item-permissions-manager ${project.version} - + @@ -79,11 +79,11 @@ ${http.client.version} - + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file 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 1d1ce4f03c..924235d799 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 @@ -25,10 +25,10 @@ import org.apache.commons.collections4.MapUtils; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.validation.api.ValidationManager; -import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; +import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; 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 53b05eb953..7a78f09f69 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 @@ -23,8 +23,8 @@ package org.openecomp.sdc.validation.util; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.validation.api.ValidationManager; -import org.openecomp.sdc.common.errors.Messages; import org.openecomp.core.validation.factory.ValidationManagerFactory; +import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; 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 a76b9b865d..9184afe823 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 @@ -28,8 +28,6 @@ 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.vendorlicense.errors.LimitErrorBuilder; -import org.openecomp.sdc.vendorlicense.types.VersionedVendorLicenseModel; import org.openecomp.sdc.versioning.dao.types.Version; import java.util.Collection; @@ -37,88 +35,71 @@ import java.util.Set; public interface VendorLicenseManager { - void checkout(String vendorLicenseModelId, String user); + void validate(String vendorLicenseModelId, Version version); - void undoCheckout(String vendorLicenseModelId, String user); + VendorLicenseModelEntity createVendorLicenseModel(VendorLicenseModelEntity licenseModel); - void checkin(String vendorLicenseModelId, String user); + void updateVendorLicenseModel(VendorLicenseModelEntity licenseModel); - void submit(String vendorLicenseModelId, String user); + VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version); - Collection listVendorLicenseModels(String versionFilter, - String user); + void deleteVendorLicenseModel(String vlmId, Version version); - VendorLicenseModelEntity createVendorLicenseModel(VendorLicenseModelEntity licenseModel, - String user); - void updateVendorLicenseModel(VendorLicenseModelEntity licenseModel, String user); + Collection listLicenseAgreements(String vlmId, Version version); - VersionedVendorLicenseModel getVendorLicenseModel(String vlmId, Version version, String user); - - void deleteVendorLicenseModel(String vlmId, String user); - - - Collection listLicenseAgreements(String vlmId, Version version, - String user); - - LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement, - String user); + LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement); void updateLicenseAgreement(LicenseAgreementEntity licenseAgreement, - Set addedFeatureGroupIds, Set removedFeatureGroupIds, - String user); + Set addedFeatureGroupIds, Set removedFeatureGroupIds); LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, - String licenseAgreementId, String user); + String licenseAgreementId); - void deleteLicenseAgreement(String vlmId, Version version, String licenseAgreementId, String user); + void deleteLicenseAgreement(String vlmId, Version version, String licenseAgreementId); - Collection listFeatureGroups(String vlmId, Version version, String user); + Collection listFeatureGroups(String vlmId, Version version); - FeatureGroupEntity createFeatureGroup(FeatureGroupEntity fg, String user); + FeatureGroupEntity createFeatureGroup(FeatureGroupEntity fg); void updateFeatureGroup(FeatureGroupEntity featureGroup, Set addedLicenseKeyGroups, Set removedLicenseKeyGroups, - Set addedEntitlementPools, Set removedEntitlementPools, - String user); - - FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup, String user); + Set addedEntitlementPools, Set removedEntitlementPools); - void deleteFeatureGroup(FeatureGroupEntity featureGroup, String user); + FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup); + void deleteFeatureGroup(FeatureGroupEntity featureGroup); - Collection listEntitlementPools(String vlmId, Version version, - String user); - EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool, String user); + Collection listEntitlementPools(String vlmId, Version version); - void updateEntitlementPool(EntitlementPoolEntity entitlementPool, String user); + EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool); - EntitlementPoolEntity getEntitlementPool(EntitlementPoolEntity entitlementPool, String user); + void updateEntitlementPool(EntitlementPoolEntity entitlementPool); - void deleteEntitlementPool(EntitlementPoolEntity entitlementPool, String user); + EntitlementPoolEntity getEntitlementPool(EntitlementPoolEntity entitlementPool); + void deleteEntitlementPool(EntitlementPoolEntity entitlementPool); - Collection listLicenseKeyGroups(String vlmId, Version version, - String user); - LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, String user); + Collection listLicenseKeyGroups(String vlmId, Version version); - void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, String user); + LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); - LicenseKeyGroupEntity getLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, String user); + void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); - void deleteLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, String user); + LicenseKeyGroupEntity getLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); - LimitEntity createLimit(LimitEntity limitEntity, String user); + void deleteLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); - Collection listLimits(String vlmId, Version version, String epLkgId, String user); + LimitEntity createLimit(LimitEntity limitEntity); - void deleteLimit(LimitEntity limitEntity, String user); + Collection listLimits(String vlmId, Version version, String epLkgId); - void updateLimit(LimitEntity limitEntity, String user); + void deleteLimit(LimitEntity limitEntity); - LimitEntity getLimit(LimitEntity entitlementPool, String user); + void updateLimit(LimitEntity limitEntity); + LimitEntity getLimit(LimitEntity entitlementPool); } 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 152ddd0e13..472473fdb0 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 @@ -1,6 +1,5 @@ package org.openecomp.sdc.vendorlicense.impl; -import org.openecomp.sdc.activityLog.ActivityLogManagerFactory; import org.openecomp.sdc.vendorlicense.VendorLicenseManager; import org.openecomp.sdc.vendorlicense.VendorLicenseManagerFactory; import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDaoFactory; @@ -10,22 +9,19 @@ 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; -import org.openecomp.sdc.versioning.VersioningManagerFactory; /** * Created by ayalaben on 8/3/2017 */ -public class VendorLicenseManagerFactoryImpl extends VendorLicenseManagerFactory { +public class VendorLicenseManagerFactoryImpl extends VendorLicenseManagerFactory { private static final VendorLicenseManager INSTANCE = new VendorLicenseManagerImpl( - VersioningManagerFactory.getInstance().createInterface(), VendorLicenseFacadeFactory.getInstance().createInterface(), VendorLicenseModelDaoFactory.getInstance().createInterface(), LicenseAgreementDaoFactory.getInstance().createInterface(), FeatureGroupDaoFactory.getInstance().createInterface(), EntitlementPoolDaoFactory.getInstance().createInterface(), LicenseKeyGroupDaoFactory.getInstance().createInterface(), - ActivityLogManagerFactory.getInstance().createInterface(), LimitDaoFactory.getInstance().createInterface()); @Override 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 e07a13c2e8..2489b5a89b 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 @@ -20,16 +20,10 @@ package org.openecomp.sdc.vendorlicense.impl; -import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE; - import org.openecomp.core.util.UniqueValueUtil; -import org.openecomp.sdc.activityLog.ActivityLogManager; -import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; @@ -57,26 +51,16 @@ import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdc.vendorlicense.errors.InvalidDateErrorBuilder; import org.openecomp.sdc.vendorlicense.errors.LimitErrorBuilder; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; -import org.openecomp.sdc.vendorlicense.types.VersionedVendorLicenseModel; -import org.openecomp.sdc.versioning.VersioningManager; import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionStatus; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; -import org.openecomp.sdcrests.activitylog.types.ActivityType; import java.time.LocalDate; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.Set; public class VendorLicenseManagerImpl implements VendorLicenseManager { - private VersioningManager versioningManager; private VendorLicenseFacade vendorLicenseFacade; private VendorLicenseModelDao vendorLicenseModelDao; private LicenseAgreementDao licenseAgreementDao; @@ -84,278 +68,134 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { private EntitlementPoolDao entitlementPoolDao; private LicenseKeyGroupDao licenseKeyGroupDao; private LimitDao limitDao; - private ActivityLogManager activityLogManager; private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private static final Logger logger = - LoggerFactory.getLogger(VendorLicenseManagerImpl.class); - public VendorLicenseManagerImpl(VersioningManager versioningManager, - VendorLicenseFacade vendorLicenseFacade, + public VendorLicenseManagerImpl(VendorLicenseFacade vendorLicenseFacade, VendorLicenseModelDao vendorLicenseModelDao, LicenseAgreementDao licenseAgreementDao, FeatureGroupDao featureGroupDao, EntitlementPoolDao entitlementPoolDao, LicenseKeyGroupDao licenseKeyGroupDao, - ActivityLogManager activityLogManager, LimitDao limitDao) { - this.versioningManager = versioningManager; this.vendorLicenseFacade = vendorLicenseFacade; this.vendorLicenseModelDao = vendorLicenseModelDao; this.licenseAgreementDao = licenseAgreementDao; this.featureGroupDao = featureGroupDao; this.entitlementPoolDao = entitlementPoolDao; this.licenseKeyGroupDao = licenseKeyGroupDao; - this.activityLogManager = activityLogManager; this.limitDao = limitDao; } - private static void sortVlmListByModificationTimeDescOrder( - List vendorLicenseModels) { - vendorLicenseModels.sort((o1, o2) -> o2.getVendorLicenseModel().getWritetimeMicroSeconds() - .compareTo(o1.getVendorLicenseModel().getWritetimeMicroSeconds())); - } - @Override - public void checkout(String vendorLicenseModelId, String user) { - + public void validate(String vendorLicenseModelId, Version version) { mdcDataDebugMessage.debugEntryMessage("VLM id", vendorLicenseModelId); - Version newVersion = versioningManager - .checkout(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vendorLicenseModelId, user); - - ActivityLogEntity activityLogEntity = new ActivityLogEntity(vendorLicenseModelId, String.valueOf(newVersion.getMajor()+1), - ActivityType.CHECKOUT.toString(), user, true, "", ""); - activityLogManager.addActionLog(activityLogEntity, user); - - newVersion.setStatus(VersionStatus.Locked); - vendorLicenseFacade.updateVlmLastModificationTime(vendorLicenseModelId, newVersion); + vendorLicenseFacade.validate(vendorLicenseModelId, version); mdcDataDebugMessage.debugExitMessage("VLM id", vendorLicenseModelId); } @Override - public void undoCheckout(String vendorLicenseModelId, String user) { - - mdcDataDebugMessage.debugEntryMessage("VLM id", vendorLicenseModelId); - - Version newVersion = versioningManager - .undoCheckout(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vendorLicenseModelId, user); - - ActivityLogEntity activityLogEntity = - new ActivityLogEntity(vendorLicenseModelId, String.valueOf(newVersion.getMajor() + 1), - ActivityType.UNDO_CHECKOUT.toString(), user, true, "", ""); - activityLogManager.addActionLog(activityLogEntity, user); - - vendorLicenseFacade.updateVlmLastModificationTime(vendorLicenseModelId, newVersion); - - mdcDataDebugMessage.debugExitMessage("VLM id", vendorLicenseModelId); - } - - @Override - public void checkin(String vendorLicenseModelId, String user) { - - mdcDataDebugMessage.debugEntryMessage("VLM id", vendorLicenseModelId); - - Version newVersion = vendorLicenseFacade.checkin(vendorLicenseModelId, user); - - ActivityLogEntity activityLogEntity = new ActivityLogEntity(vendorLicenseModelId, - String.valueOf(newVersion.getMajor()+1), ActivityType.CHECKIN.toString(), user, true, "", ""); - activityLogManager.addActionLog(activityLogEntity, user); - - mdcDataDebugMessage.debugExitMessage("VLM id", vendorLicenseModelId); - } - - @Override - public void submit(String vendorLicenseModelId, String user) { - - mdcDataDebugMessage.debugEntryMessage("VLM id", vendorLicenseModelId); - - Version newVersion = vendorLicenseFacade.submit(vendorLicenseModelId, user); - - ActivityLogEntity activityLogEntity = new ActivityLogEntity(vendorLicenseModelId, String.valueOf(newVersion.getMajor()), - ActivityType.SUBMIT.toString(), user, true, "", ""); - activityLogManager.addActionLog(activityLogEntity, user); - - mdcDataDebugMessage.debugExitMessage("VLM id", vendorLicenseModelId); - } - - @Override - public Collection listVendorLicenseModels(String versionFilter, - String user) { + public VendorLicenseModelEntity createVendorLicenseModel( + VendorLicenseModelEntity vendorLicenseModelEntity) { mdcDataDebugMessage.debugEntryMessage(null); - Map idToVersionsInfo = versioningManager - .listEntitiesVersionInfo(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, user, - VersionableEntityAction.Read); - - List vendorLicenseModels = new ArrayList<>(); - for (Map.Entry entry : idToVersionsInfo.entrySet()) { - VersionInfo versionInfo = entry.getValue(); - if (versionFilter != null && versionFilter.equals(VersionStatus.Final.name())) { - if (versionInfo.getLatestFinalVersion() == null) { - continue; - } - versionInfo.setActiveVersion(versionInfo.getLatestFinalVersion()); - versionInfo.setStatus(VersionStatus.Final); - versionInfo.setLockingUser(null); - } - - Version version = versionInfo.getActiveVersion(); - if (user.equals(versionInfo.getLockingUser())) { - version.setStatus(VersionStatus.Locked); - } - - try { - VendorLicenseModelEntity vlm = - vendorLicenseModelDao.get(new VendorLicenseModelEntity(entry.getKey(), version)); - if (vlm != null) { - VersionedVendorLicenseModel versionedVlm = new VersionedVendorLicenseModel(); - versionedVlm.setVendorLicenseModel(vlm); - versionedVlm.setVersionInfo(versionInfo); - vendorLicenseModels.add(versionedVlm); - } - }catch(RuntimeException rte){ - logger.error("Error trying to retrieve vlm["+entry.getKey()+"] version["+version.toString - ()+"] " + - "message:"+rte - .getMessage()); - } - } - - sortVlmListByModificationTimeDescOrder(vendorLicenseModels); - + vendorLicenseModelDao.create(vendorLicenseModelEntity); mdcDataDebugMessage.debugExitMessage(null); - return vendorLicenseModels; - } - - @Override - public VendorLicenseModelEntity createVendorLicenseModel(VendorLicenseModelEntity vendorLicenseModelEntity, String user) { - - VendorLicenseModelEntity vendorLicenseModelCreated = vendorLicenseFacade.createVendorLicenseModel(vendorLicenseModelEntity, user); - - ActivityLogEntity activityLogEntity = new ActivityLogEntity(vendorLicenseModelCreated.getId(), - String.valueOf(vendorLicenseModelCreated.getVersion().getMajor()+1), - ActivityType.CREATE_NEW.toString(), user, true, "", ""); - activityLogManager.addActionLog(activityLogEntity, user); - return vendorLicenseModelCreated; + return vendorLicenseModelEntity; } @Override - public void updateVendorLicenseModel(VendorLicenseModelEntity vendorLicenseModelEntity, - String user) { + public void updateVendorLicenseModel(VendorLicenseModelEntity vendorLicenseModelEntity) { mdcDataDebugMessage.debugEntryMessage("VLM id", vendorLicenseModelEntity.getId()); - Version version = resloveVersion(vendorLicenseModelEntity.getId(),null, - getVersionInfo(vendorLicenseModelEntity.getId(), VersionableEntityAction.Write, user), - user); - vendorLicenseModelEntity.setVersion(version); - String existingVendorName = vendorLicenseModelDao.get(vendorLicenseModelEntity).getVendorName(); updateUniqueName(VendorLicenseConstants.UniqueValues.VENDOR_NAME, existingVendorName, - vendorLicenseModelEntity.getVendorName()); + vendorLicenseModelEntity.getVendorName()); vendorLicenseModelDao.update(vendorLicenseModelEntity); - vendorLicenseFacade - .updateVlmLastModificationTime(vendorLicenseModelEntity.getId(), version); - mdcDataDebugMessage.debugExitMessage("VLM id", vendorLicenseModelEntity.getId()); } @Override - public VersionedVendorLicenseModel getVendorLicenseModel(String vlmId, Version version, - String user) { - return vendorLicenseFacade.getVendorLicenseModel(vlmId, version, user); + public VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version) { + return vendorLicenseFacade.getVendorLicenseModel(vlmId, version); } @Override - public void deleteVendorLicenseModel(String vlmId, String user) { + public void deleteVendorLicenseModel(String vlmId, Version version) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.DELETE_ENTITY, ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.UNSUPPORTED_OPERATION); + LoggerTragetServiceName.DELETE_ENTITY, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.UNSUPPORTED_OPERATION); throw new UnsupportedOperationException(VendorLicenseConstants.UNSUPPORTED_OPERATION_ERROR); } @Override - public Collection listLicenseAgreements(String vlmId, Version version, - String user) { + public Collection listLicenseAgreements(String vlmId, Version version) { mdcDataDebugMessage.debugEntryMessage("VLM id", vlmId); mdcDataDebugMessage.debugExitMessage("VLM id", vlmId); - LicenseAgreementEntity licenseAgreementEntity = createLicenseAgreementForList(vlmId, version, - user); -// return licenseAgreementDao.list(new LicenseAgreementEntity(vlmId, VersioningUtil -// .resolveVersion(version, getVersionInfo(vlmId, VersionableEntityAction.Read, user), user), -// null)); - return licenseAgreementDao.list(licenseAgreementEntity); + return licenseAgreementDao.list(new LicenseAgreementEntity(vlmId, version, null)); } @Override - public LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement, - String user) { + public LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement) { mdcDataDebugMessage - .debugEntryMessage("VLM id", licenseAgreement.getVendorLicenseModelId()); + .debugEntryMessage("VLM id", licenseAgreement.getVendorLicenseModelId()); mdcDataDebugMessage - .debugExitMessage("VLM id", licenseAgreement.getVendorLicenseModelId()); - return vendorLicenseFacade.createLicenseAgreement(licenseAgreement, user); + .debugExitMessage("VLM id", licenseAgreement.getVendorLicenseModelId()); + return vendorLicenseFacade.createLicenseAgreement(licenseAgreement); } @Override public void updateLicenseAgreement(LicenseAgreementEntity licenseAgreement, Set addedFeatureGroupIds, - Set removedFeatureGroupIds, String user) { + Set removedFeatureGroupIds) { mdcDataDebugMessage.debugEntryMessage("VLM id, LA id", licenseAgreement - .getVendorLicenseModelId(), licenseAgreement.getId()); + .getVendorLicenseModelId(), licenseAgreement.getId()); - Version version = VersioningUtil.resolveVersion(licenseAgreement.getVersion(), - getVersionInfo(licenseAgreement.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user); - licenseAgreement.setVersion(version); LicenseAgreementEntity retrieved = licenseAgreementDao.get(licenseAgreement); VersioningUtil - .validateEntityExistence(retrieved, licenseAgreement, VendorLicenseModelEntity.ENTITY_TYPE); + .validateEntityExistence(retrieved, licenseAgreement, VendorLicenseModelEntity.ENTITY_TYPE); VersioningUtil.validateContainedEntitiesExistence(new FeatureGroupEntity().getEntityType(), - removedFeatureGroupIds, retrieved, retrieved.getFeatureGroupIds()); + removedFeatureGroupIds, retrieved, retrieved.getFeatureGroupIds()); VersioningUtil.validateEntitiesExistence(addedFeatureGroupIds, - new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), version, null), - featureGroupDao, VendorLicenseModelEntity.ENTITY_TYPE); + 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().toString()); + retrieved.getName(), licenseAgreement.getName(), licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId()); licenseAgreementDao.updateColumnsAndDeltaFeatureGroupIds(licenseAgreement, addedFeatureGroupIds, - removedFeatureGroupIds); + removedFeatureGroupIds); addFeatureGroupsToLicenseAgreementRef(addedFeatureGroupIds, licenseAgreement); removeFeatureGroupsToLicenseAgreementRef(removedFeatureGroupIds, licenseAgreement); - vendorLicenseFacade - .updateVlmLastModificationTime(licenseAgreement.getVendorLicenseModelId(), version); - mdcDataDebugMessage.debugExitMessage("VLM id, LA id", licenseAgreement - .getVendorLicenseModelId(), licenseAgreement.getId()); + .getVendorLicenseModelId(), licenseAgreement.getId()); } @Override public LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, - String licenseAgreementId, String user) { + String licenseAgreementId) { mdcDataDebugMessage.debugEntryMessage("VLM id, LA id", vlmId, licenseAgreementId); mdcDataDebugMessage.debugExitMessage("VLM id, LA id", vlmId, licenseAgreementId); - return vendorLicenseFacade.getLicenseAgreementModel(vlmId, version, licenseAgreementId, user); + return vendorLicenseFacade.getLicenseAgreementModel(vlmId, version, licenseAgreementId); } @Override - public void deleteLicenseAgreement(String vlmId, Version version, String licenseAgreementId, - String user) { + public void deleteLicenseAgreement(String vlmId, Version version, String licenseAgreementId) { mdcDataDebugMessage.debugEntryMessage("VLM id, LA id", vlmId, licenseAgreementId); - version = VersioningUtil - .resolveVersion(version, getVersionInfo(vlmId, VersionableEntityAction.Write, user), user); LicenseAgreementEntity input = - new LicenseAgreementEntity(vlmId, version, licenseAgreementId); + new LicenseAgreementEntity(vlmId, version, licenseAgreementId); LicenseAgreementEntity retrieved = licenseAgreementDao.get(input); VersioningUtil.validateEntityExistence(retrieved, input, VendorLicenseModelEntity.ENTITY_TYPE); @@ -364,29 +204,25 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { licenseAgreementDao.delete(retrieved); deleteUniqueName(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME, - retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(), - retrieved.getName()); - - vendorLicenseFacade - .updateVlmLastModificationTime(input.getVendorLicenseModelId(), input.getVersion()); + retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(), + retrieved.getName()); mdcDataDebugMessage.debugExitMessage("VLM id, LA id", vlmId, licenseAgreementId); } @Override - public Collection listFeatureGroups(String vlmId, Version version, - String user) { + public Collection listFeatureGroups(String vlmId, Version version) { mdcDataDebugMessage.debugEntryMessage("VLM id", vlmId); mdcDataDebugMessage.debugExitMessage("VLM id", vlmId); - return vendorLicenseFacade.listFeatureGroups(vlmId, version, user); + return vendorLicenseFacade.listFeatureGroups(vlmId, version); } @Override - public FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup, String user) { + public FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup) { mdcDataDebugMessage - .debugEntryMessage("VLM id", featureGroup.getVendorLicenseModelId()); + .debugEntryMessage("VLM id", featureGroup.getVendorLicenseModelId()); mdcDataDebugMessage.debugExitMessage("VLM id", featureGroup.getId()); - return vendorLicenseFacade.createFeatureGroup(featureGroup, user); + return vendorLicenseFacade.createFeatureGroup(featureGroup); } @Override @@ -394,35 +230,31 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { Set addedLicenseKeyGroups, Set removedLicenseKeyGroups, Set addedEntitlementPools, - Set removedEntitlementPools, - String user) { + Set removedEntitlementPools) { mdcDataDebugMessage.debugEntryMessage("VLM id, FG id", featureGroup - .getVendorLicenseModelId(), featureGroup.getId()); - - Version version = VersioningUtil.resolveVersion(featureGroup.getVersion(), - getVersionInfo(featureGroup.getVendorLicenseModelId(), VersionableEntityAction.Write, user), - user); - featureGroup.setVersion(version); + .getVendorLicenseModelId(), featureGroup.getId()); FeatureGroupEntity retrieved = featureGroupDao.get(featureGroup); VersioningUtil - .validateEntityExistence(retrieved, featureGroup, VendorLicenseModelEntity.ENTITY_TYPE); + .validateEntityExistence(retrieved, featureGroup, VendorLicenseModelEntity.ENTITY_TYPE); VersioningUtil.validateContainedEntitiesExistence(new LicenseKeyGroupEntity().getEntityType(), - removedLicenseKeyGroups, retrieved, retrieved.getLicenseKeyGroupIds()); + removedLicenseKeyGroups, retrieved, retrieved.getLicenseKeyGroupIds()); VersioningUtil.validateContainedEntitiesExistence(new EntitlementPoolEntity().getEntityType(), - removedEntitlementPools, retrieved, retrieved.getEntitlementPoolIds()); + removedEntitlementPools, retrieved, retrieved.getEntitlementPoolIds()); VersioningUtil.validateEntitiesExistence(addedLicenseKeyGroups, - new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), version, null), - licenseKeyGroupDao, VendorLicenseModelEntity.ENTITY_TYPE); + new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), + null), + licenseKeyGroupDao, VendorLicenseModelEntity.ENTITY_TYPE); VersioningUtil.validateEntitiesExistence(addedEntitlementPools, - new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), version, null), - entitlementPoolDao, VendorLicenseModelEntity.ENTITY_TYPE); + 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().toString()); + retrieved.getName(), featureGroup.getName(), featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); addLicenseKeyGroupsToFeatureGroupsRef(addedLicenseKeyGroups, featureGroup); removeLicenseKeyGroupsToFeatureGroupsRef(removedLicenseKeyGroups, featureGroup); @@ -430,413 +262,364 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { removeEntitlementPoolsToFeatureGroupsRef(removedEntitlementPools, featureGroup); featureGroupDao.updateFeatureGroup(featureGroup, addedEntitlementPools, removedEntitlementPools, - addedLicenseKeyGroups, removedLicenseKeyGroups); - - vendorLicenseFacade - .updateVlmLastModificationTime(featureGroup.getVendorLicenseModelId(), version); + addedLicenseKeyGroups, removedLicenseKeyGroups); mdcDataDebugMessage.debugExitMessage("VLM id, FG id", featureGroup - .getVendorLicenseModelId(), featureGroup.getId()); + .getVendorLicenseModelId(), featureGroup.getId()); } @Override - public FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup, String user) { + public FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup) { mdcDataDebugMessage.debugEntryMessage("VLM id, FG id", - featureGroup.getVendorLicenseModelId(), featureGroup.getId()); + featureGroup.getVendorLicenseModelId(), featureGroup.getId()); mdcDataDebugMessage.debugExitMessage("VLM id, FG id", - featureGroup.getVendorLicenseModelId(), featureGroup.getId()); - return vendorLicenseFacade.getFeatureGroupModel(featureGroup, user); + featureGroup.getVendorLicenseModelId(), featureGroup.getId()); + return vendorLicenseFacade.getFeatureGroupModel(featureGroup); } @Override - public void deleteFeatureGroup(FeatureGroupEntity featureGroup, String user) { + public void deleteFeatureGroup(FeatureGroupEntity featureGroup) { mdcDataDebugMessage.debugEntryMessage("VLM id, FG id", - featureGroup.getVendorLicenseModelId(), featureGroup.getId()); + featureGroup.getVendorLicenseModelId(), featureGroup.getId()); - Version version = VersioningUtil.resolveVersion(featureGroup.getVersion(), - getVersionInfo(featureGroup.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user); - featureGroup.setVersion(version); FeatureGroupEntity retrieved = featureGroupDao.get(featureGroup); VersioningUtil - .validateEntityExistence(retrieved, featureGroup, VendorLicenseModelEntity.ENTITY_TYPE); + .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(), version, - licenceAgreementId), featureGroup.getId()); + 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()); - - vendorLicenseFacade.updateVlmLastModificationTime(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion()); + retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(), + retrieved.getName()); mdcDataDebugMessage - .debugExitMessage("VLM id, FG id", - featureGroup.getVendorLicenseModelId(), featureGroup.getId()); + .debugExitMessage("VLM id, FG id", + featureGroup.getVendorLicenseModelId(), featureGroup.getId()); } @Override - public Collection listEntitlementPools(String vlmId, Version version, - String user) { + public Collection listEntitlementPools(String vlmId, Version version) { mdcDataDebugMessage.debugEntryMessage("VLM id", vlmId); mdcDataDebugMessage.debugExitMessage("VLM id", vlmId); - return vendorLicenseFacade.listEntitlementPools(vlmId, version, user); + return vendorLicenseFacade.listEntitlementPools(vlmId, version); } @Override - public EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool, - String user) { + public EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool) { mdcDataDebugMessage - .debugEntryMessage("VLM id", entitlementPool.getVendorLicenseModelId()); + .debugEntryMessage("VLM id", entitlementPool.getVendorLicenseModelId()); mdcDataDebugMessage - .debugExitMessage("VLM id", entitlementPool.getVendorLicenseModelId()); + .debugExitMessage("VLM id", entitlementPool.getVendorLicenseModelId()); entitlementPool.setStartDate(entitlementPool.getStartDate() != null ? (entitlementPool - .getStartDate().trim().length() != 0 ? entitlementPool.getStartDate()+"T00:00:00Z" - : null) : null); + .getStartDate().trim().length() != 0 ? entitlementPool.getStartDate() + "T00:00:00Z" + : null) : null); entitlementPool.setExpiryDate(entitlementPool.getExpiryDate() != null ? (entitlementPool - .getExpiryDate().trim().length() != 0 ? entitlementPool.getExpiryDate()+"T23:59:59Z" - : null) : null); + .getExpiryDate().trim().length() != 0 ? entitlementPool.getExpiryDate() + "T23:59:59Z" + : null) : null); validateCreateDate(entitlementPool.getStartDate(), entitlementPool.getExpiryDate(), - entitlementPool.getVendorLicenseModelId()); - return vendorLicenseFacade.createEntitlementPool(entitlementPool, user); + entitlementPool.getVendorLicenseModelId()); + return vendorLicenseFacade.createEntitlementPool(entitlementPool); } - private void validateCreateDate(String startDate, String expiryDate, String vendorLicenseModelId){ + private void validateCreateDate(String startDate, String expiryDate, + String vendorLicenseModelId) { mdcDataDebugMessage.debugEntryMessage("Start date and end date", startDate - +" "+expiryDate); + + " " + expiryDate); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy'T'HH:mm:ss'Z'"); - if(startDate != null && expiryDate != null) { + if (startDate != null && expiryDate != null) { if (LocalDate.parse(startDate, formatter).atStartOfDay().isBefore - (LocalDate.now().atStartOfDay()) || LocalDate.parse(expiryDate, formatter).atStartOfDay() - .isEqual(LocalDate.parse(startDate, formatter).atStartOfDay()) || LocalDate - .parse(expiryDate, formatter).isBefore(LocalDate.parse(startDate, formatter))) { + (LocalDate.now().atStartOfDay()) || LocalDate.parse(expiryDate, formatter).atStartOfDay() + .isEqual(LocalDate.parse(startDate, formatter).atStartOfDay()) || LocalDate + .parse(expiryDate, formatter).isBefore(LocalDate.parse(startDate, formatter))) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.VALIDATE_DATE_RANGE,ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE); + LoggerTragetServiceName.VALIDATE_DATE_RANGE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE); throw new CoreException( - new InvalidDateErrorBuilder(vendorLicenseModelId) - .build()); + new InvalidDateErrorBuilder(vendorLicenseModelId) + .build()); } } - if(startDate != null && expiryDate == null) { + if (startDate != null && expiryDate == null) { if (LocalDate.parse(startDate, formatter).atStartOfDay().isBefore - (LocalDate.now().atStartOfDay())) { + (LocalDate.now().atStartOfDay())) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.VALIDATE_DATE_RANGE,ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE); + LoggerTragetServiceName.VALIDATE_DATE_RANGE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE); throw new CoreException( - new InvalidDateErrorBuilder(vendorLicenseModelId) - .build()); + new InvalidDateErrorBuilder(vendorLicenseModelId) + .build()); } } - if(startDate == null && expiryDate != null) { + if (startDate == null && expiryDate != null) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.VALIDATE_DATE_RANGE,ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE); + LoggerTragetServiceName.VALIDATE_DATE_RANGE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE); throw new CoreException( - new InvalidDateErrorBuilder(vendorLicenseModelId) - .build()); + new InvalidDateErrorBuilder(vendorLicenseModelId) + .build()); } - mdcDataDebugMessage.debugExitMessage(null,null); + mdcDataDebugMessage.debugExitMessage(null); } - private void validateUpdateDate(String startDate, String expiryDate, String vendorLicenseModelId){ + private void validateUpdateDate(String startDate, String expiryDate, + String vendorLicenseModelId) { mdcDataDebugMessage.debugEntryMessage("Start date and end date", startDate - +" "+ expiryDate); + + " " + expiryDate); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy'T'HH:mm:ss'Z'"); - if(startDate != null && expiryDate != null) { + if (startDate != null && expiryDate != null) { if (LocalDate.parse(expiryDate, formatter).atStartOfDay() - .isEqual(LocalDate.parse(startDate, formatter).atStartOfDay()) || - LocalDate.parse(expiryDate, formatter).isBefore(LocalDate.parse(startDate, formatter))) { + .isEqual(LocalDate.parse(startDate, formatter).atStartOfDay()) || + LocalDate.parse(expiryDate, formatter).isBefore(LocalDate.parse(startDate, formatter))) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.VALIDATE_DATE_RANGE,ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE); + LoggerTragetServiceName.VALIDATE_DATE_RANGE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE); throw new CoreException( - new InvalidDateErrorBuilder(vendorLicenseModelId) - .build()); + new InvalidDateErrorBuilder(vendorLicenseModelId) + .build()); } } - if(startDate == null && expiryDate != null) { + if (startDate == null && expiryDate != null) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.VALIDATE_DATE_RANGE,ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE); + LoggerTragetServiceName.VALIDATE_DATE_RANGE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE); throw new CoreException( - new InvalidDateErrorBuilder(vendorLicenseModelId) - .build()); + new InvalidDateErrorBuilder(vendorLicenseModelId) + .build()); } - mdcDataDebugMessage.debugExitMessage(null,null); + mdcDataDebugMessage.debugExitMessage(null); } @Override - public void updateEntitlementPool(EntitlementPoolEntity entitlementPool, String user) { + public void updateEntitlementPool(EntitlementPoolEntity entitlementPool) { mdcDataDebugMessage.debugEntryMessage("VLM id, EP id", entitlementPool - .getVendorLicenseModelId(), entitlementPool.getId()); + .getVendorLicenseModelId(), entitlementPool.getId()); entitlementPool.setStartDate(entitlementPool.getStartDate() != null ? (entitlementPool - .getStartDate().trim().length() != 0 ? entitlementPool.getStartDate()+"T00:00:00Z" - : null) : null); + .getStartDate().trim().length() != 0 ? entitlementPool.getStartDate() + "T00:00:00Z" + : null) : null); entitlementPool.setExpiryDate(entitlementPool.getExpiryDate() != null ? (entitlementPool - .getExpiryDate().trim().length() != 0 ? entitlementPool.getExpiryDate()+"T23:59:59Z" - : null) : null); + .getExpiryDate().trim().length() != 0 ? entitlementPool.getExpiryDate() + "T23:59:59Z" + : null) : null); validateUpdateDate(entitlementPool.getStartDate(), entitlementPool.getExpiryDate(), - entitlementPool.getVendorLicenseModelId()); - Version version = VersioningUtil.resolveVersion(entitlementPool.getVersion(), - getVersionInfo(entitlementPool.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user); - vendorLicenseFacade - .updateVlmLastModificationTime(entitlementPool.getVendorLicenseModelId(), version); - vendorLicenseFacade.updateEntitlementPool(entitlementPool, user); + entitlementPool.getVendorLicenseModelId()); + vendorLicenseFacade.updateEntitlementPool(entitlementPool); mdcDataDebugMessage.debugExitMessage("VLM id, EP id", entitlementPool - .getVendorLicenseModelId(), entitlementPool.getId()); + .getVendorLicenseModelId(), entitlementPool.getId()); } @Override - public EntitlementPoolEntity getEntitlementPool(EntitlementPoolEntity entitlementPool, - String user) { + public EntitlementPoolEntity getEntitlementPool(EntitlementPoolEntity entitlementPool) { mdcDataDebugMessage.debugEntryMessage("VLM id, EP id", entitlementPool - .getVendorLicenseModelId(), entitlementPool.getId()); - - entitlementPool.setVersion(VersioningUtil.resolveVersion(entitlementPool.getVersion(), - getVersionInfo(entitlementPool.getVendorLicenseModelId(), VersionableEntityAction.Read, - user), user)); + .getVendorLicenseModelId(), entitlementPool.getId()); EntitlementPoolEntity retrieved = entitlementPoolDao.get(entitlementPool); VersioningUtil - .validateEntityExistence(retrieved, entitlementPool, VendorLicenseModelEntity.ENTITY_TYPE); + .validateEntityExistence(retrieved, entitlementPool, VendorLicenseModelEntity.ENTITY_TYPE); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy'T'HH:mm:ss'Z'"); DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); - if(retrieved.getStartDate() != null){ - retrieved.setStartDate(LocalDate.parse(retrieved.getStartDate(),formatter).format - (targetFormatter)); + 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)); + if (retrieved.getExpiryDate() != null) { + retrieved.setExpiryDate(LocalDate.parse(retrieved.getExpiryDate(), formatter).format + (targetFormatter)); } mdcDataDebugMessage.debugExitMessage("VLM id, EP id", entitlementPool - .getVendorLicenseModelId(), entitlementPool.getId()); + .getVendorLicenseModelId(), entitlementPool.getId()); return retrieved; } @Override - public void deleteEntitlementPool(EntitlementPoolEntity entitlementPool, String user) { + public void deleteEntitlementPool(EntitlementPoolEntity entitlementPool) { mdcDataDebugMessage.debugEntryMessage("VLM id, EP id", entitlementPool - .getVendorLicenseModelId(), entitlementPool.getId()); - - Version version = VersioningUtil.resolveVersion(entitlementPool.getVersion(), - getVersionInfo(entitlementPool.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user); - entitlementPool.setVersion(version); + .getVendorLicenseModelId(), entitlementPool.getId()); EntitlementPoolEntity retrieved = entitlementPoolDao.get(entitlementPool); VersioningUtil - .validateEntityExistence(retrieved, entitlementPool, VendorLicenseModelEntity.ENTITY_TYPE); + .validateEntityExistence(retrieved, entitlementPool, VendorLicenseModelEntity.ENTITY_TYPE); for (String referencingFeatureGroupId : retrieved.getReferencingFeatureGroups()) { featureGroupDao.removeEntitlementPool( - new FeatureGroupEntity(entitlementPool.getVendorLicenseModelId(), version, - referencingFeatureGroupId), entitlementPool.getId()); + new FeatureGroupEntity(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion(), + referencingFeatureGroupId), entitlementPool.getId()); } - deleteChildLimits(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion(), entitlementPool.getId(), user); + deleteChildLimits(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion(), + entitlementPool.getId()); entitlementPoolDao.delete(entitlementPool); deleteUniqueName(VendorLicenseConstants.UniqueValues.ENTITLEMENT_POOL_NAME, - retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(), - retrieved.getName()); - - vendorLicenseFacade.updateVlmLastModificationTime(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion()); + retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(), + retrieved.getName()); mdcDataDebugMessage.debugExitMessage("VLM id, EP id", entitlementPool - .getVendorLicenseModelId(), entitlementPool.getId()); + .getVendorLicenseModelId(), entitlementPool.getId()); } - protected void deleteChildLimits(String vlmId, Version version, String epLkgId, String user) { + protected void deleteChildLimits(String vlmId, Version version, String epLkgId) { Optional> limitEntities = Optional.ofNullable( - listLimits(vlmId, version, epLkgId, user)); - limitEntities.ifPresent(entities-> - entities.forEach(entity-> - deleteLimit(entity, user))); + listLimits(vlmId, version, epLkgId)); + limitEntities.ifPresent(entities -> entities.forEach(this::deleteLimit)); } @Override - public Collection listLicenseKeyGroups(String vlmId, Version version, - String user) { + public Collection listLicenseKeyGroups(String vlmId, Version version) { mdcDataDebugMessage.debugEntryMessage("VLM id", vlmId); mdcDataDebugMessage.debugExitMessage("VLM id", vlmId); - return vendorLicenseFacade.listLicenseKeyGroups(vlmId, version, user); + return vendorLicenseFacade.listLicenseKeyGroups(vlmId, version); } @Override - public LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, - String user) { + public LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { mdcDataDebugMessage - .debugEntryMessage("VLM id", licenseKeyGroup.getVendorLicenseModelId()); + .debugEntryMessage("VLM id", licenseKeyGroup.getVendorLicenseModelId()); mdcDataDebugMessage.debugExitMessage("VLM id", licenseKeyGroup - .getVendorLicenseModelId()); + .getVendorLicenseModelId()); licenseKeyGroup.setStartDate(licenseKeyGroup.getStartDate() != null ? (licenseKeyGroup - .getStartDate().trim().length() != 0 ? licenseKeyGroup.getStartDate()+"T00:00:00Z" - : null) : null); + .getStartDate().trim().length() != 0 ? licenseKeyGroup.getStartDate() + "T00:00:00Z" + : null) : null); licenseKeyGroup.setExpiryDate(licenseKeyGroup.getExpiryDate() != null ? (licenseKeyGroup - .getExpiryDate().trim().length() != 0 ? licenseKeyGroup.getExpiryDate()+"T23:59:59Z" - : null) : null); + .getExpiryDate().trim().length() != 0 ? licenseKeyGroup.getExpiryDate() + "T23:59:59Z" + : null) : null); validateCreateDate(licenseKeyGroup.getStartDate(), licenseKeyGroup.getExpiryDate(), - licenseKeyGroup.getVendorLicenseModelId()); - return vendorLicenseFacade.createLicenseKeyGroup(licenseKeyGroup, user); + licenseKeyGroup.getVendorLicenseModelId()); + return vendorLicenseFacade.createLicenseKeyGroup(licenseKeyGroup); } @Override - public void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, String user) { + public void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { mdcDataDebugMessage.debugEntryMessage("VLM id, LKG id", licenseKeyGroup - .getVendorLicenseModelId(), licenseKeyGroup.getId()); + .getVendorLicenseModelId(), licenseKeyGroup.getId()); licenseKeyGroup.setStartDate(licenseKeyGroup.getStartDate() != null ? (licenseKeyGroup - .getStartDate().trim().length() != 0 ? licenseKeyGroup.getStartDate()+"T00:00:00Z" - : null) : null); + .getStartDate().trim().length() != 0 ? licenseKeyGroup.getStartDate() + "T00:00:00Z" + : null) : null); licenseKeyGroup.setExpiryDate(licenseKeyGroup.getExpiryDate() != null ? (licenseKeyGroup - .getExpiryDate().trim().length() != 0 ? licenseKeyGroup.getExpiryDate()+"T23:59:59Z" - : null) : null); + .getExpiryDate().trim().length() != 0 ? licenseKeyGroup.getExpiryDate() + "T23:59:59Z" + : null) : null); validateUpdateDate(licenseKeyGroup.getStartDate(), licenseKeyGroup.getExpiryDate(), - licenseKeyGroup.getVendorLicenseModelId()); - - Version version = VersioningUtil.resolveVersion(licenseKeyGroup.getVersion(), - getVersionInfo(licenseKeyGroup.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user); - vendorLicenseFacade - .updateVlmLastModificationTime(licenseKeyGroup.getVendorLicenseModelId(), version); - - vendorLicenseFacade.updateLicenseKeyGroup(licenseKeyGroup, user); + licenseKeyGroup.getVendorLicenseModelId()); + vendorLicenseFacade.updateLicenseKeyGroup(licenseKeyGroup); mdcDataDebugMessage.debugExitMessage("VLM id, LKG id", licenseKeyGroup - .getVendorLicenseModelId(), licenseKeyGroup.getId()); + .getVendorLicenseModelId(), licenseKeyGroup.getId()); } @Override - public LicenseKeyGroupEntity getLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, - String user) { + public LicenseKeyGroupEntity getLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { mdcDataDebugMessage.debugEntryMessage("VLM id, LKG id", licenseKeyGroup - .getVendorLicenseModelId(), licenseKeyGroup.getId()); - - licenseKeyGroup.setVersion(VersioningUtil.resolveVersion(licenseKeyGroup.getVersion(), - getVersionInfo(licenseKeyGroup.getVendorLicenseModelId(), VersionableEntityAction.Read, - user), user)); + .getVendorLicenseModelId(), licenseKeyGroup.getId()); LicenseKeyGroupEntity retrieved = licenseKeyGroupDao.get(licenseKeyGroup); VersioningUtil - .validateEntityExistence(retrieved, licenseKeyGroup, VendorLicenseModelEntity.ENTITY_TYPE); + .validateEntityExistence(retrieved, licenseKeyGroup, VendorLicenseModelEntity.ENTITY_TYPE); mdcDataDebugMessage.debugExitMessage("VLM id, LKG id", licenseKeyGroup - .getVendorLicenseModelId(), licenseKeyGroup.getId()); + .getVendorLicenseModelId(), licenseKeyGroup.getId()); return retrieved; } @Override - public void deleteLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, String user) { + public void deleteLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { mdcDataDebugMessage.debugEntryMessage("VLM id, LKG id", licenseKeyGroup - .getVendorLicenseModelId(), licenseKeyGroup.getId()); - - Version version = VersioningUtil.resolveVersion(licenseKeyGroup.getVersion(), - getVersionInfo(licenseKeyGroup.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user); - licenseKeyGroup.setVersion(version); + .getVendorLicenseModelId(), licenseKeyGroup.getId()); LicenseKeyGroupEntity retrieved = licenseKeyGroupDao.get(licenseKeyGroup); VersioningUtil - .validateEntityExistence(retrieved, licenseKeyGroup, VendorLicenseModelEntity.ENTITY_TYPE); + .validateEntityExistence(retrieved, licenseKeyGroup, VendorLicenseModelEntity.ENTITY_TYPE); for (String referencingFeatureGroupId : retrieved.getReferencingFeatureGroups()) { featureGroupDao.removeLicenseKeyGroup( - new FeatureGroupEntity(licenseKeyGroup.getVendorLicenseModelId(), version, - referencingFeatureGroupId), licenseKeyGroup.getId()); + new FeatureGroupEntity(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion(), + referencingFeatureGroupId), licenseKeyGroup.getId()); } - deleteChildLimits(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion(), licenseKeyGroup.getId(), user); + deleteChildLimits(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion(), + licenseKeyGroup.getId()); licenseKeyGroupDao.delete(licenseKeyGroup); deleteUniqueName(VendorLicenseConstants.UniqueValues.LICENSE_KEY_GROUP_NAME, - retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(), - retrieved.getName()); - - vendorLicenseFacade.updateVlmLastModificationTime(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion()); + retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(), + retrieved.getName()); mdcDataDebugMessage.debugExitMessage("VLM id, LKG id", licenseKeyGroup - .getVendorLicenseModelId(), licenseKeyGroup.getId()); + .getVendorLicenseModelId(), licenseKeyGroup.getId()); } @Override - public LimitEntity createLimit(LimitEntity limit, String user) { + public LimitEntity createLimit(LimitEntity limit) { mdcDataDebugMessage - .debugEntryMessage("VLM id", limit.getVendorLicenseModelId(), "EP/LKGId", limit - .getEpLkgId()); + .debugEntryMessage("VLM id", limit.getVendorLicenseModelId(), "EP/LKGId", limit + .getEpLkgId()); mdcDataDebugMessage - .debugExitMessage("VLM id", limit.getVendorLicenseModelId(), "EP/LKGId", limit - .getEpLkgId()); - validateLimit(limit, user); - LimitEntity createdLimit = vendorLicenseFacade.createLimit(limit, user); - updateParentForLimit(limit,user); + .debugExitMessage("VLM id", limit.getVendorLicenseModelId(), "EP/LKGId", limit + .getEpLkgId()); + validateLimit(limit); + LimitEntity createdLimit = vendorLicenseFacade.createLimit(limit); + updateParentForLimit(limit); return createdLimit; } - private void validateLimit(LimitEntity limit, String user) { - Version version = VersioningUtil.resolveVersion(limit.getVersion(), - getVersionInfo(limit.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user); - Collection limitList = listLimits(limit.getVendorLicenseModelId(),version - ,limit.getEpLkgId(), user); + private void validateLimit(LimitEntity limit) { + Collection limitList = + listLimits(limit.getVendorLicenseModelId(), limit.getVersion() + , limit.getEpLkgId()); - if (!isLimitNameUnique(limitList,limit.getName(), limit.getType(), limit.getId())) { + if (!isLimitNameUnique(limitList, limit.getName(), limit.getType(), limit.getId())) { final ErrorCode duplicateLimitNameErrorBuilder = - LimitErrorBuilder.getDuplicateNameErrorbuilder(limit.getName(), limit.getType().name()); + LimitErrorBuilder.getDuplicateNameErrorbuilder(limit.getName(), limit.getType().name()); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerServiceName.Create_LIMIT.toString(), ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), - duplicateLimitNameErrorBuilder.message()); + LoggerServiceName.Create_LIMIT.toString(), ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), + duplicateLimitNameErrorBuilder.message()); throw new CoreException(duplicateLimitNameErrorBuilder); } } private boolean isLimitNameUnique(Collection limitList, String name, LimitType - type, String id) { + 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)){ + if (limit.getName().equalsIgnoreCase(name) && + limit.getType().name().equalsIgnoreCase(type.name())) { + if (id != null && limit.getId().equals(id)) { continue; } return false; @@ -846,54 +629,45 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { } @Override - public Collection listLimits(String vlmId, Version version, String epLkgId, - String user) { + public Collection listLimits(String vlmId, Version version, String epLkgId) { mdcDataDebugMessage.debugEntryMessage("VLM id", vlmId, "EP/LKGId", epLkgId); mdcDataDebugMessage.debugExitMessage("VLM id", vlmId, "EP/LKGId", epLkgId); - return vendorLicenseFacade.listLimits(vlmId, version, epLkgId, user); + return vendorLicenseFacade.listLimits(vlmId, version, epLkgId); } @Override - public void deleteLimit(LimitEntity limitEntity, String user) { + public void deleteLimit(LimitEntity limitEntity) { mdcDataDebugMessage.debugEntryMessage("VLM id, EP id, Limit Id", limitEntity - .getVendorLicenseModelId(), limitEntity.getEpLkgId(), limitEntity.getId()); - - Version version = VersioningUtil.resolveVersion(limitEntity.getVersion(), - getVersionInfo(limitEntity.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user); - limitEntity.setVersion(version); + .getVendorLicenseModelId(), limitEntity.getEpLkgId(), limitEntity.getId()); - if ( !isLimitPresent(limitEntity)) { + if (!isLimitPresent(limitEntity)) { VersioningUtil - .validateEntityExistence(null, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); + .validateEntityExistence(null, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); } LimitEntity retrieved = limitDao.get(limitEntity); VersioningUtil - .validateEntityExistence(retrieved, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); + .validateEntityExistence(retrieved, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); limitDao.delete(limitEntity); - vendorLicenseFacade.updateVlmLastModificationTime(limitEntity.getVendorLicenseModelId(), - limitEntity.getVersion()); - - updateParentForLimit(limitEntity,user); + updateParentForLimit(limitEntity); mdcDataDebugMessage.debugExitMessage("VLM id, EP id, Limit Id", limitEntity - .getVendorLicenseModelId(), limitEntity.getEpLkgId(), limitEntity.getId()); + .getVendorLicenseModelId(), limitEntity.getEpLkgId(), limitEntity.getId()); } @Override - public void updateLimit(LimitEntity limit, String user) { + public void updateLimit(LimitEntity limit) { mdcDataDebugMessage - .debugEntryMessage("VLM id", limit.getVendorLicenseModelId(), "EP/LKGId", limit - .getEpLkgId()); - getLimit(limit,user); - validateLimit(limit, user); - vendorLicenseFacade.updateLimit(limit, user); - updateParentForLimit(limit,user); + .debugEntryMessage("VLM id", limit.getVendorLicenseModelId(), "EP/LKGId", limit + .getEpLkgId()); + getLimit(limit); + validateLimit(limit); + vendorLicenseFacade.updateLimit(limit); + updateParentForLimit(limit); mdcDataDebugMessage - .debugExitMessage("VLM id", limit.getVendorLicenseModelId(), "EP/LKGId", limit - .getEpLkgId()); + .debugExitMessage("VLM id", limit.getVendorLicenseModelId(), "EP/LKGId", limit + .getEpLkgId()); } private boolean isLimitPresent(LimitEntity limit) { @@ -901,52 +675,46 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { } @Override - public LimitEntity getLimit(LimitEntity limitEntity, - String user) { + public LimitEntity getLimit(LimitEntity limitEntity) { mdcDataDebugMessage.debugEntryMessage("VLM id", limitEntity.getVendorLicenseModelId(), - "EP/LKGId", limitEntity.getEpLkgId()); + "EP/LKGId", limitEntity.getEpLkgId()); - limitEntity.setVersion(VersioningUtil.resolveVersion(limitEntity.getVersion(), - getVersionInfo(limitEntity.getVendorLicenseModelId(), VersionableEntityAction.Read, - user), user)); - if(!isLimitPresent(limitEntity)){ + if (!isLimitPresent(limitEntity)) { VersioningUtil - .validateEntityExistence(null, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); + .validateEntityExistence(null, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); } LimitEntity retrieved = limitDao.get(limitEntity); VersioningUtil - .validateEntityExistence(retrieved, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); + .validateEntityExistence(retrieved, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); mdcDataDebugMessage.debugExitMessage("VLM id", limitEntity.getVendorLicenseModelId(), - "EP/LKGId", limitEntity.getEpLkgId()); + "EP/LKGId", limitEntity.getEpLkgId()); return retrieved; } /** * update Parent of limit (EP/LKG) versionuuid when limit is modified so that limit updates are * captured in VLM XML - * @param limit - * @param user */ - private void updateParentForLimit(LimitEntity limit, String user) { + private void updateParentForLimit(LimitEntity limit) { mdcDataDebugMessage.debugEntryMessage("VLM id", limit.getVendorLicenseModelId(), - "EP/LKGId", limit.getEpLkgId(), "Limit Parent ", limit.getParent()); - if ("EntitlementPool".equals(limit.getParent()) ) { + "EP/LKGId", limit.getEpLkgId(), "Limit Parent ", limit.getParent()); + if ("EntitlementPool".equals(limit.getParent())) { EntitlementPoolEntity entitlementPoolEntity = - entitlementPoolDao.get(new EntitlementPoolEntity(limit.getVendorLicenseModelId(), - limit.getVersion(), limit.getEpLkgId())); - vendorLicenseFacade.updateEntitlementPool(entitlementPoolEntity, user); + entitlementPoolDao.get(new EntitlementPoolEntity(limit.getVendorLicenseModelId(), + limit.getVersion(), limit.getEpLkgId())); + vendorLicenseFacade.updateEntitlementPool(entitlementPoolEntity); } if ("LicenseKeyGroup".equals(limit.getParent())) { LicenseKeyGroupEntity licenseKeyGroupEntity = licenseKeyGroupDao.get( - new LicenseKeyGroupEntity(limit.getVendorLicenseModelId(), limit.getVersion(), - limit.getEpLkgId())); - vendorLicenseFacade.updateLicenseKeyGroup(licenseKeyGroupEntity, user); + new LicenseKeyGroupEntity(limit.getVendorLicenseModelId(), limit.getVersion(), + limit.getEpLkgId())); + vendorLicenseFacade.updateLicenseKeyGroup(licenseKeyGroupEntity); } mdcDataDebugMessage.debugEntryMessage("VLM id", limit.getVendorLicenseModelId(), - "EP/LKGId", limit.getEpLkgId(), "Limit Parent ", limit.getParent()); + "EP/LKGId", limit.getEpLkgId(), "Limit Parent ", limit.getParent()); } protected void addFeatureGroupsToLicenseAgreementRef(Set featureGroupIds, @@ -954,8 +722,8 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { if (featureGroupIds != null) { for (String featureGroupId : featureGroupIds) { featureGroupDao.addReferencingLicenseAgreement( - new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion(), featureGroupId), licenseAgreement.getId()); + new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion(), featureGroupId), licenseAgreement.getId()); } } } @@ -965,8 +733,8 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { if (featureGroupIds != null) { for (String featureGroupId : featureGroupIds) { featureGroupDao.removeReferencingLicenseAgreement( - new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion(), featureGroupId), licenseAgreement.getId()); + new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion(), featureGroupId), licenseAgreement.getId()); } } } @@ -976,8 +744,8 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { if (licenseKeyGroupIds != null) { for (String licenseKeyGroupId : licenseKeyGroupIds) { licenseKeyGroupDao.addReferencingFeatureGroup( - new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion(), licenseKeyGroupId), featureGroup.getId()); + new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion(), licenseKeyGroupId), featureGroup.getId()); } } } @@ -987,8 +755,8 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { if (licenseKeyGroupIds != null) { for (String licenseKeyGroupId : licenseKeyGroupIds) { licenseKeyGroupDao.removeReferencingFeatureGroup( - new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion(), licenseKeyGroupId), featureGroup.getId()); + new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion(), licenseKeyGroupId), featureGroup.getId()); } } } @@ -998,8 +766,8 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { if (entitlementPoolIds != null) { for (String entitlementPoolId : entitlementPoolIds) { entitlementPoolDao.addReferencingFeatureGroup( - new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion(), entitlementPoolId), featureGroup.getId()); + new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion(), entitlementPoolId), featureGroup.getId()); } } } @@ -1009,38 +777,19 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { if (entitlementPoolIds != null) { for (String entitlementPoolId : entitlementPoolIds) { entitlementPoolDao.removeReferencingFeatureGroup( - new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion(), entitlementPoolId), featureGroup.getId()); + new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion(), entitlementPoolId), featureGroup.getId()); } } } - protected VersionInfo getVersionInfo(String vendorLicenseModelId, VersionableEntityAction action, - String user) { - return vendorLicenseFacade.getVersionInfo(vendorLicenseModelId, action, user); - } - - protected LicenseAgreementEntity createLicenseAgreementForList(String vlmId, Version version, - String user) { - return new LicenseAgreementEntity(vlmId, VersioningUtil - .resolveVersion(version, getVersionInfo(vlmId, VersionableEntityAction.Read, user), user), - null); - } - - protected void updateUniqueName(String uniqueValueType ,String oldName, String newName,String ... - context) { + protected void updateUniqueName(String uniqueValueType, String oldName, String newName, String... + context) { UniqueValueUtil - .updateUniqueValue(uniqueValueType, oldName, newName,context); + .updateUniqueValue(uniqueValueType, oldName, newName, context); } - protected void deleteUniqueName(String uniqueValueType,String ... uniqueCombination) { + protected void deleteUniqueName(String uniqueValueType, String... uniqueCombination) { UniqueValueUtil.deleteUniqueValue(uniqueValueType, uniqueCombination); } - - protected Version resloveVersion(String vlmId,Version requestedVersion, VersionInfo versionInfo, - String user){ - return VersioningUtil.resolveVersion(null, - getVersionInfo(vlmId, VersionableEntityAction.Write, user), user); - } - } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/ArtifactTestUtils.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/ArtifactTestUtils.java index 5d9729de53..c005e9696f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/ArtifactTestUtils.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/ArtifactTestUtils.java @@ -20,41 +20,6 @@ package org.openecomp.sdc.vendorlicense; -import org.openecomp.core.utilities.CommonMethods; -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.EntitlementPoolEntity; -import org.openecomp.sdc.vendorlicense.dao.types.EntitlementTime; -import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyType; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseTerm; -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 org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; -import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacadeFactory; -import org.openecomp.sdc.vendorlicense.impl.VendorLicenseManagerImpl; -import org.openecomp.sdc.vendorlicense.licenseartifacts.VendorLicenseArtifactsService; -import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; -import org.openecomp.sdc.vendorsoftwareproduct.impl.VendorSoftwareProductManagerImpl; -import org.openecomp.sdc.versioning.VersioningManager; -import org.openecomp.sdc.versioning.VersioningManagerFactory; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; -import org.testng.annotations.BeforeMethod; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE; - /** * Created by Katyr on 29-May-16 */ diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/LimitTest.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/LimitTest.java index 07fdeeeee8..0197dd9d28 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/LimitTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/LimitTest.java @@ -20,17 +20,11 @@ package org.openecomp.sdc.vendorlicense; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.verify; - import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; 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.vendorlicense.dao.LimitDao; import org.openecomp.sdc.vendorlicense.dao.types.AggregationFunction; import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; @@ -45,19 +39,19 @@ import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; -public class LimitTest { +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); +public class LimitTest { - private final String USER1 = "limitTestUser1"; - private final String LT1_NAME = "LT1 name"; + private final String USER1 = "limitTestUser1"; + private final String LT1_NAME = "LT1 name"; private static final String VLM_ID = "VLM_ID"; private static final Version VERSION = new Version(0, 1); @@ -76,8 +70,8 @@ public class LimitTest { private VendorLicenseManagerImpl vendorLicenseManagerImpl; public static LimitEntity createLimitEntity(String name, LimitType type, String description, - Version version, String metric, - AggregationFunction aggregationFunction, int unit, + Version version, String metric, + AggregationFunction aggregationFunction, int unit, String time) { LimitEntity limitEntity = new LimitEntity(); limitEntity.setName(name); @@ -92,22 +86,22 @@ public class LimitTest { } @BeforeMethod - public void setUp() { + public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @Test public void testUpdateLimit() { Version version = new Version(); - LimitEntity limitEntity1 = createLimitEntity(LT1_NAME,LimitType.Vendor,"string",version, - "Core",AggregationFunction.Average,10,"Hour"); - LimitEntity limitEntity2 = createLimitEntity(LT1_NAME,LimitType.Vendor,"string",version, - "Tokens",AggregationFunction.Peak,12,"Month"); + LimitEntity limitEntity1 = createLimitEntity(LT1_NAME, LimitType.Vendor, "string", version, + "Core", AggregationFunction.Average, 10, "Hour"); + LimitEntity limitEntity2 = createLimitEntity(LT1_NAME, LimitType.Vendor, "string", version, + "Tokens", AggregationFunction.Peak, 12, "Month"); VersionInfo info = new VersionInfo(); info.getViewableVersions().add(version); info.setActiveVersion(version); - doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(),anyObject(),anyObject()); + /*doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(), anyObject(), anyObject());*/ doReturn(true).when(limitDao).isLimitPresent(anyObject()); doReturn(limitEntity1).when(limitDao).get(anyObject()); @@ -116,27 +110,28 @@ public class LimitTest { limitEntityList.add(limitEntity2); limitEntity1.setId("1234"); limitEntity2.setId("1234"); - doReturn(limitEntityList).when(vendorLicenseFacade).listLimits(anyObject(),anyObject(), - anyObject(),anyObject()); + doReturn(limitEntityList).when(vendorLicenseFacade) + .listLimits(anyObject(), anyObject(), anyObject()); - vendorLicenseManagerImpl.updateLimit(limitEntity2,USER1); + vendorLicenseManagerImpl.updateLimit(limitEntity2); - verify(vendorLicenseFacade).updateLimit(anyObject(), anyObject()); + verify(vendorLicenseFacade).updateLimit(anyObject()); } @Test public void testUpdateLimitErrorWithSameNameType() { try { Version version = new Version(); - LimitEntity limitEntity1 = createLimitEntity(LT1_NAME,LimitType.Vendor,"string",version, - "Core",AggregationFunction.Average,10,"Hour"); - LimitEntity limitEntity2 = createLimitEntity(LT1_NAME,LimitType.Vendor,"string",version, - "Tokens",AggregationFunction.Peak,12,"Month"); + LimitEntity limitEntity1 = createLimitEntity(LT1_NAME, LimitType.Vendor, "string", version, + "Core", AggregationFunction.Average, 10, "Hour"); + LimitEntity limitEntity2 = createLimitEntity(LT1_NAME, LimitType.Vendor, "string", version, + "Tokens", AggregationFunction.Peak, 12, "Month"); VersionInfo info = new VersionInfo(); info.getViewableVersions().add(version); info.setActiveVersion(version); - doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(),anyObject(),anyObject()); +/* doReturn(info).when(vendorLicenseFacade) + .getVersionInfo(anyObject(), anyObject(), anyObject());*/ doReturn(limitEntity1).when(limitDao).get(anyObject()); List limitEntityList = new ArrayList<>(); @@ -144,13 +139,12 @@ public class LimitTest { limitEntityList.add(limitEntity2); limitEntity1.setId("1234"); limitEntity2.setId("9632"); - doReturn(limitEntityList).when(vendorLicenseFacade).listLimits(anyObject(),anyObject(), - anyObject(),anyObject()); + doReturn(limitEntityList).when(vendorLicenseFacade) + .listLimits(anyObject(), anyObject(), anyObject()); - vendorLicenseManagerImpl.updateLimit(limitEntity2,USER1); + vendorLicenseManagerImpl.updateLimit(limitEntity2); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @@ -159,13 +153,13 @@ public class LimitTest { @Test public void testDeleteLimit() { Version version = new Version(); - LimitEntity limitEntity = createLimitEntity(LT1_NAME,LimitType.Vendor,"string",version, - "Core",AggregationFunction.Average,10,"Hour"); + LimitEntity limitEntity = createLimitEntity(LT1_NAME, LimitType.Vendor, "string", version, + "Core", AggregationFunction.Average, 10, "Hour"); VersionInfo info = new VersionInfo(); info.getViewableVersions().add(version); info.setActiveVersion(version); - doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(),anyObject(),anyObject()); + /*doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(), anyObject(), anyObject());*/ doReturn(true).when(limitDao).isLimitPresent(anyObject()); doReturn(limitEntity).when(limitDao).get(anyObject()); @@ -173,27 +167,28 @@ public class LimitTest { limitEntityList.add(limitEntity); limitEntity.setId("1234"); - vendorLicenseManagerImpl.deleteLimit(limitEntity,LT1_NAME); + vendorLicenseManagerImpl.deleteLimit(limitEntity); - verify(vendorLicenseManagerImpl).deleteLimit(anyObject(), anyObject()); + verify(vendorLicenseManagerImpl).deleteLimit(anyObject()); } @Test public void testUpdateLimitErrorWithInvalidId() { try { Version version = new Version(); - LimitEntity limitEntity1 = createLimitEntity(LT1_NAME,LimitType.Vendor,"string",version, - "Core",AggregationFunction.Average,10,"Hour"); - LimitEntity limitEntity2 = createLimitEntity(LT1_NAME,LimitType.Vendor,"string",version, - "Tokens",AggregationFunction.Peak,12,"Month"); + LimitEntity limitEntity1 = createLimitEntity(LT1_NAME, LimitType.Vendor, "string", version, + "Core", AggregationFunction.Average, 10, "Hour"); + LimitEntity limitEntity2 = createLimitEntity(LT1_NAME, LimitType.Vendor, "string", version, + "Tokens", AggregationFunction.Peak, 12, "Month"); VersionInfo info = new VersionInfo(); info.getViewableVersions().add(version); info.setActiveVersion(version); - doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(),anyObject(),anyObject()); +/* doReturn(info).when(vendorLicenseFacade) + .getVersionInfo(anyObject(), anyObject(), anyObject());*/ doReturn(null).when(limitDao).get(anyObject()); - vendorLicenseManagerImpl.updateLimit(limitEntity2,USER1); + vendorLicenseManagerImpl.updateLimit(limitEntity2); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), @@ -206,14 +201,14 @@ public class LimitTest { doReturn(Arrays.asList( createLimit(VLM_ID, VERSION, EPLKG_ID, LIMIT1_ID), createLimit(VLM_ID, VERSION, EPLKG_ID, LIMIT2_ID))) - .when(vendorLicenseFacade).listLimits(VLM_ID, VERSION, EPLKG_ID, USER1); + .when(vendorLicenseFacade).listLimits(VLM_ID, VERSION, EPLKG_ID); final Collection limits = - vendorLicenseManagerImpl.listLimits(VLM_ID, VERSION, EPLKG_ID, USER1); + vendorLicenseManagerImpl.listLimits(VLM_ID, VERSION, EPLKG_ID); Assert.assertEquals(limits.size(), 2); for (LimitEntity limit : limits) { Assert.assertEquals(limit.getName(), - LIMIT1_ID.equals(limit.getId()) ? LIMIT1_ID+" name" : LIMIT2_ID+" name" ); + LIMIT1_ID.equals(limit.getId()) ? LIMIT1_ID + " name" : LIMIT2_ID + " name"); } } @@ -224,10 +219,10 @@ public class LimitTest { info.getViewableVersions().add(VERSION); info.setActiveVersion(VERSION); - doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(),anyObject(),anyObject()); + /*doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(), anyObject(), anyObject());*/ - vendorLicenseManagerImpl.createLimit(expected, USER1); - verify(vendorLicenseFacade).createLimit(expected,USER1); + vendorLicenseManagerImpl.createLimit(expected); + verify(vendorLicenseFacade).createLimit(expected); } @Test @@ -241,20 +236,19 @@ public class LimitTest { List vfcImageList = new ArrayList(); vfcImageList.add(expectedDiffName); - doReturn(vfcImageList).when(vendorLicenseFacade).listLimits(anyObject(), anyObject(), anyObject(), - anyObject()); + doReturn(vfcImageList).when(vendorLicenseFacade) + .listLimits(anyObject(), anyObject(), anyObject()); VersionInfo info = new VersionInfo(); info.getViewableVersions().add(VERSION); info.setActiveVersion(VERSION); - doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(),anyObject(),anyObject()); +/* doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(), anyObject(), anyObject());*/ try { - vendorLicenseManagerImpl.createLimit(expected, USER1); + vendorLicenseManagerImpl.createLimit(expected); Assert.fail(); - } - catch (CoreException ex) { + } catch (CoreException ex) { Assert.assertEquals(ex.code().id(), VendorLicenseErrorCodes.DUPLICATE_LIMIT_NAME_NOT_ALLOWED); } @@ -267,13 +261,14 @@ public class LimitTest { info.getViewableVersions().add(VERSION); info.setActiveVersion(VERSION); - doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(),anyObject(),anyObject()); + /*doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(), anyObject(), anyObject());*/ try { - vendorLicenseManagerImpl.getLimit(limit , USER1); + vendorLicenseManagerImpl.getLimit(limit); Assert.fail(); } catch (CoreException exception) { - Assert.assertEquals(exception.code().id(), VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); + Assert.assertEquals(exception.code().id(), + VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } } @@ -293,10 +288,10 @@ public class LimitTest { info.getViewableVersions().add(VERSION); info.setActiveVersion(VERSION); - doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(),anyObject(),anyObject()); + /*doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(), anyObject(), anyObject());*/ LimitEntity actual = createLimit(VLM_ID, VERSION, EPLKG_ID, LIMIT1_ID); - vendorLicenseManagerImpl.getLimit(actual, USER1); + vendorLicenseManagerImpl.getLimit(actual); Assert.assertEquals(actual.getId(), expected.getId()); Assert.assertEquals(actual.getName(), expected.getName()); Assert.assertEquals(actual.getUnit(), expected.getUnit()); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/VendorLicenseFacadeImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/VendorLicenseFacadeImplTest.java index ab6262d8ca..e3719ab515 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/VendorLicenseFacadeImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/VendorLicenseFacadeImplTest.java @@ -1,39 +1,5 @@ package org.openecomp.sdc.vendorlicense; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDao; -import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDao; -import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDao; -import org.openecomp.sdc.vendorlicense.dao.LicenseKeyGroupDao; -import org.openecomp.sdc.vendorlicense.dao.VendorLicenseModelDao; -import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; -import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; -import org.openecomp.sdc.vendorlicense.facade.impl.VendorLicenseFacadeImpl; -import org.openecomp.sdc.versioning.VersioningManager; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; -import static org.openecomp.sdc.vendorlicense.errors.UncompletedVendorLicenseModelErrorType.SUBMIT_UNCOMPLETED_VLM_MSG_FG_MISSING_EP; -import static org.openecomp.sdc.vendorlicense.errors.UncompletedVendorLicenseModelErrorType.SUBMIT_UNCOMPLETED_VLM_MSG_LA_MISSING_FG; - /** * This test just verifies Feature Group Get and List APIs. */ diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/EntitlementPoolTest.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/EntitlementPoolTest.java index 178d05e6c8..57d22544ad 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/EntitlementPoolTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/EntitlementPoolTest.java @@ -28,12 +28,16 @@ import org.mockito.Spy; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDao; import org.openecomp.sdc.vendorlicense.dao.LimitDao; -import org.openecomp.sdc.vendorlicense.dao.types.*; +import org.openecomp.sdc.vendorlicense.dao.types.AggregationFunction; +import org.openecomp.sdc.vendorlicense.dao.types.EntitlementMetric; +import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; +import org.openecomp.sdc.vendorlicense.dao.types.EntitlementTime; +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 org.openecomp.sdc.vendorlicense.errors.VendorLicenseErrorCodes; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -41,7 +45,6 @@ import org.testng.annotations.Test; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; @@ -54,353 +57,323 @@ import static org.mockito.Mockito.verify; public class EntitlementPoolTest { - //JUnit Test Cases using Mockito - private final String USER1 = "epTestUser1"; - private final String EP1_NAME = "EP1 name"; - private final String EP2_NAME = "EP2 name"; - private final String LT1_NAME = "LT1 name"; - private static String vlm1_id = "vlm1_id"; - private static String ep1_id = "ep1_id"; - private static String ep2_id = "ep2_id"; - public static final Version VERSION01 = new Version(0, 1); - - @Mock - private VendorLicenseFacade vendorLicenseFacade; - - @Mock - private EntitlementPoolDao entitlementPoolDao; - @Mock - private LimitDao limitDao; - - @InjectMocks - @Spy - private VendorLicenseManagerImpl vendorLicenseManagerImpl; - - public EntitlementPoolEntity createEntitlementPool(String vlmId, Version version,String id, - String name, String desc, int threshold, - ThresholdUnit thresholdUnit, - EntitlementMetric entitlementMetricChoice, - String entitlementMetricOther, - String increments, - AggregationFunction aggregationFunctionChoice, - String aggregationFunctionOther, - Set operationalScopeChoices, - String operationalScopeOther, - EntitlementTime timeChoice, - String timeOther, String sku) { - EntitlementPoolEntity entitlementPool = new EntitlementPoolEntity(); - entitlementPool.setVendorLicenseModelId(vlmId); - entitlementPool.setId(id); - entitlementPool.setVersion(version); - entitlementPool.setName(name); - entitlementPool.setDescription(desc); - entitlementPool.setThresholdValue(threshold); - entitlementPool.setThresholdUnit(thresholdUnit); - entitlementPool.setIncrements(increments); - entitlementPool.setOperationalScope( - new MultiChoiceOrOther<>(operationalScopeChoices, operationalScopeOther)); - return entitlementPool; - } - - @BeforeMethod - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } + //JUnit Test Cases using Mockito + private final String USER1 = "epTestUser1"; + private final String EP1_NAME = "EP1 name"; + private final String EP2_NAME = "EP2 name"; + private final String LT1_NAME = "LT1 name"; + private static String vlm1_id = "vlm1_id"; + private static String ep1_id = "ep1_id"; + private static String ep2_id = "ep2_id"; + public static final Version VERSION01 = new Version(0, 1); + + @Mock + private VendorLicenseFacade vendorLicenseFacade; + + @Mock + private EntitlementPoolDao entitlementPoolDao; + @Mock + private LimitDao limitDao; + + @InjectMocks + @Spy + private VendorLicenseManagerImpl vendorLicenseManagerImpl; + + public EntitlementPoolEntity createEntitlementPool(String vlmId, Version version, String id, + String name, String desc, int threshold, + ThresholdUnit thresholdUnit, + EntitlementMetric entitlementMetricChoice, + String entitlementMetricOther, + String increments, + AggregationFunction aggregationFunctionChoice, + String aggregationFunctionOther, + Set operationalScopeChoices, + String operationalScopeOther, + EntitlementTime timeChoice, + String timeOther, String sku) { + EntitlementPoolEntity entitlementPool = new EntitlementPoolEntity(); + entitlementPool.setVendorLicenseModelId(vlmId); + entitlementPool.setId(id); + entitlementPool.setVersion(version); + entitlementPool.setName(name); + entitlementPool.setDescription(desc); + entitlementPool.setThresholdValue(threshold); + entitlementPool.setThresholdUnit(thresholdUnit); + entitlementPool.setIncrements(increments); + entitlementPool.setOperationalScope( + new MultiChoiceOrOther<>(operationalScopeChoices, operationalScopeOther)); + return entitlementPool; + } - @Test - public void createTest() { - Set opScopeChoices; - opScopeChoices = new HashSet<>(); - opScopeChoices.add(OperationalScope.Core); - opScopeChoices.add(OperationalScope.CPU); - opScopeChoices.add(OperationalScope.Network_Wide); - EntitlementPoolEntity ep2 = - createEntitlementPool("vlm1Id", null, ep1_id,EP1_NAME, "EP2 dec", 70, ThresholdUnit - .Absolute, - EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, - opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); - ep2.setStartDate(LocalDate.now().format(formatter)); - ep2.setExpiryDate(LocalDate.now().plusDays(1L).format(formatter)); + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } - vendorLicenseManagerImpl.createEntitlementPool(ep2, USER1); - verify(vendorLicenseFacade).createEntitlementPool(ep2,USER1); + @Test + public void createTest() { + Set opScopeChoices; + opScopeChoices = new HashSet<>(); + opScopeChoices.add(OperationalScope.Core); + opScopeChoices.add(OperationalScope.CPU); + opScopeChoices.add(OperationalScope.Network_Wide); + EntitlementPoolEntity ep2 = + createEntitlementPool("vlm1Id", null, ep1_id, EP1_NAME, "EP2 dec", 70, ThresholdUnit + .Absolute, + EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, + opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); + ep2.setStartDate(LocalDate.now().format(formatter)); + ep2.setExpiryDate(LocalDate.now().plusDays(1L).format(formatter)); - } + vendorLicenseManagerImpl.createEntitlementPool(ep2); + verify(vendorLicenseFacade).createEntitlementPool(ep2); - @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = "Vendor " + - "license model with id vlm1_id has invalid date range.") - public void createWithInvalidStartExpiryDateTest() { + } - Set opScopeChoices; - opScopeChoices = new HashSet<>(); - opScopeChoices.add(OperationalScope.Core); - opScopeChoices.add(OperationalScope.CPU); - opScopeChoices.add(OperationalScope.Network_Wide); - EntitlementPoolEntity ep2 = - createEntitlementPool("vlm2Id", null, ep1_id,EP1_NAME, "EP2 dec", 70, - ThresholdUnit.Absolute, - EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, - opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); - ep2.setStartDate(LocalDate.now().format(formatter)); - ep2.setExpiryDate(LocalDate.now().minusDays(2L).format(formatter)); - ep2.setVendorLicenseModelId(vlm1_id); - vendorLicenseManagerImpl.createEntitlementPool(ep2, USER1).getId(); - Assert.fail(); + @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = "Vendor " + + "license model with id vlm1_id has invalid date range.") + public void createWithInvalidStartExpiryDateTest() { - } + Set opScopeChoices; + opScopeChoices = new HashSet<>(); + opScopeChoices.add(OperationalScope.Core); + opScopeChoices.add(OperationalScope.CPU); + opScopeChoices.add(OperationalScope.Network_Wide); + EntitlementPoolEntity ep2 = + createEntitlementPool("vlm2Id", null, ep1_id, EP1_NAME, "EP2 dec", 70, + ThresholdUnit.Absolute, + EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, + opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); + ep2.setStartDate(LocalDate.now().format(formatter)); + ep2.setExpiryDate(LocalDate.now().minusDays(2L).format(formatter)); + ep2.setVendorLicenseModelId(vlm1_id); + vendorLicenseManagerImpl.createEntitlementPool(ep2).getId(); + Assert.fail(); - @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = "Vendor " + - "license model with id vlm1_id has invalid date range.") - public void createWithoutStartDateTest() { + } - Set opScopeChoices; - opScopeChoices = new HashSet<>(); - opScopeChoices.add(OperationalScope.Core); - opScopeChoices.add(OperationalScope.CPU); - opScopeChoices.add(OperationalScope.Network_Wide); - EntitlementPoolEntity ep2 = - createEntitlementPool("vlm3Id", null, ep1_id,EP1_NAME, "EP2 dec", 70, - ThresholdUnit.Absolute, - EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, - opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); - ep2.setExpiryDate(LocalDate.now().plusDays(2L).format(formatter)); - ep2.setVendorLicenseModelId(vlm1_id); - vendorLicenseManagerImpl.createEntitlementPool(ep2, USER1).getId(); - Assert.fail(); + @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = "Vendor " + + "license model with id vlm1_id has invalid date range.") + public void createWithoutStartDateTest() { - } + Set opScopeChoices; + opScopeChoices = new HashSet<>(); + opScopeChoices.add(OperationalScope.Core); + opScopeChoices.add(OperationalScope.CPU); + opScopeChoices.add(OperationalScope.Network_Wide); + EntitlementPoolEntity ep2 = + createEntitlementPool("vlm3Id", null, ep1_id, EP1_NAME, "EP2 dec", 70, + ThresholdUnit.Absolute, + EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, + opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); + ep2.setExpiryDate(LocalDate.now().plusDays(2L).format(formatter)); + ep2.setVendorLicenseModelId(vlm1_id); + vendorLicenseManagerImpl.createEntitlementPool(ep2).getId(); + Assert.fail(); - @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = "Vendor " + - "license model with id vlm1_id has invalid date range.") - public void createWithSameStartExpiryDateTest() { + } - Set opScopeChoices; - opScopeChoices = new HashSet<>(); - opScopeChoices.add(OperationalScope.Core); - opScopeChoices.add(OperationalScope.CPU); - opScopeChoices.add(OperationalScope.Network_Wide); - EntitlementPoolEntity ep2 = - createEntitlementPool("vlm4Id", null, ep1_id,EP1_NAME, "EP2 dec", 70, - ThresholdUnit.Absolute, - EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, - opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); - ep2.setStartDate(LocalDate.now().format(formatter)); - ep2.setExpiryDate(LocalDate.now().format(formatter)); - ep2.setVendorLicenseModelId(vlm1_id); - vendorLicenseManagerImpl.createEntitlementPool(ep2, USER1).getId(); - Assert.fail(); - } + @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = "Vendor " + + "license model with id vlm1_id has invalid date range.") + public void createWithSameStartExpiryDateTest() { - @Test - public void testUpdate() { - Set opScopeChoices; - opScopeChoices = new HashSet<>(); - opScopeChoices.add(OperationalScope.Core); - opScopeChoices.add(OperationalScope.CPU); - opScopeChoices.add(OperationalScope.Network_Wide); - EntitlementPoolEntity ep2 = - createEntitlementPool(vlm1_id, VERSION01, ep1_id,EP1_NAME, "EP2 dec", 70, - ThresholdUnit - .Absolute, - EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, - opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); - ep2.setStartDate(LocalDate.now().minusDays(3L).format(formatter)); - ep2.setExpiryDate(LocalDate.now().minusDays(2L).format(formatter)); + Set opScopeChoices; + opScopeChoices = new HashSet<>(); + opScopeChoices.add(OperationalScope.Core); + opScopeChoices.add(OperationalScope.CPU); + opScopeChoices.add(OperationalScope.Network_Wide); + EntitlementPoolEntity ep2 = + createEntitlementPool("vlm4Id", null, ep1_id, EP1_NAME, "EP2 dec", 70, + ThresholdUnit.Absolute, + EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, + opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); + ep2.setStartDate(LocalDate.now().format(formatter)); + ep2.setExpiryDate(LocalDate.now().format(formatter)); + ep2.setVendorLicenseModelId(vlm1_id); + vendorLicenseManagerImpl.createEntitlementPool(ep2).getId(); + Assert.fail(); + } - VersionInfo info = new VersionInfo(); - info.getViewableVersions().add(VERSION01); - info.setActiveVersion(VERSION01); - doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(),anyObject(),anyObject()); + @Test + public void testUpdate() { + Set opScopeChoices; + opScopeChoices = new HashSet<>(); + opScopeChoices.add(OperationalScope.Core); + opScopeChoices.add(OperationalScope.CPU); + opScopeChoices.add(OperationalScope.Network_Wide); + EntitlementPoolEntity ep2 = + createEntitlementPool(vlm1_id, VERSION01, ep1_id, EP1_NAME, "EP2 dec", 70, + ThresholdUnit + .Absolute, + EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, + opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); + ep2.setStartDate(LocalDate.now().minusDays(3L).format(formatter)); + ep2.setExpiryDate(LocalDate.now().minusDays(2L).format(formatter)); - vendorLicenseManagerImpl.updateEntitlementPool(ep2, USER1); - verify(vendorLicenseFacade).updateEntitlementPool(ep2,USER1); - verify(vendorLicenseFacade).updateVlmLastModificationTime(vlm1_id,VERSION01); - } + vendorLicenseManagerImpl.updateEntitlementPool(ep2); + } - @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = "Vendor " + - "license model with id vlm1_id has invalid date range.") - public void updateWithInvalidStartExpiryDateTest() { + @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = "Vendor " + + "license model with id vlm1_id has invalid date range.") + public void updateWithInvalidStartExpiryDateTest() { - Set opScopeChoices; - opScopeChoices = new HashSet<>(); - opScopeChoices.add(OperationalScope.Core); - opScopeChoices.add(OperationalScope.CPU); - opScopeChoices.add(OperationalScope.Network_Wide); - EntitlementPoolEntity ep2 = - createEntitlementPool("vlm2Id", null, ep1_id,EP1_NAME, "EP2 dec", 70, - ThresholdUnit.Absolute, - EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, - opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); - ep2.setStartDate(LocalDate.now().format(formatter)); - ep2.setExpiryDate(LocalDate.now().minusDays(2L).format(formatter)); - ep2.setVendorLicenseModelId(vlm1_id); - vendorLicenseManagerImpl.updateEntitlementPool(ep2, USER1); - Assert.fail(); + Set opScopeChoices; + opScopeChoices = new HashSet<>(); + opScopeChoices.add(OperationalScope.Core); + opScopeChoices.add(OperationalScope.CPU); + opScopeChoices.add(OperationalScope.Network_Wide); + EntitlementPoolEntity ep2 = + createEntitlementPool("vlm2Id", null, ep1_id, EP1_NAME, "EP2 dec", 70, + ThresholdUnit.Absolute, + EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, + opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); + ep2.setStartDate(LocalDate.now().format(formatter)); + ep2.setExpiryDate(LocalDate.now().minusDays(2L).format(formatter)); + ep2.setVendorLicenseModelId(vlm1_id); + vendorLicenseManagerImpl.updateEntitlementPool(ep2); + Assert.fail(); - } + } - @Test - public void updateWithoutStartDateTest() { - try { + @Test + public void updateWithoutStartDateTest() { + try { - Set opScopeChoices; - opScopeChoices = new HashSet<>(); - opScopeChoices.add(OperationalScope.Core); - opScopeChoices.add(OperationalScope.CPU); - opScopeChoices.add(OperationalScope.Network_Wide); - EntitlementPoolEntity ep2 = - createEntitlementPool("vlm3Id", null, ep1_id,EP1_NAME, "EP2 dec", 70, - ThresholdUnit.Absolute, - EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, - opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); - ep2.setExpiryDate(LocalDate.now().plusDays(2L).format(formatter)); - vendorLicenseManagerImpl.updateEntitlementPool(ep2, USER1); - Assert.fail(); - } catch (CoreException exception) { - Assert.assertEquals(exception.code().id(), VendorLicenseErrorCodes.DATE_RANGE_INVALID); - } + Set opScopeChoices; + opScopeChoices = new HashSet<>(); + opScopeChoices.add(OperationalScope.Core); + opScopeChoices.add(OperationalScope.CPU); + opScopeChoices.add(OperationalScope.Network_Wide); + EntitlementPoolEntity ep2 = + createEntitlementPool("vlm3Id", null, ep1_id, EP1_NAME, "EP2 dec", 70, + ThresholdUnit.Absolute, + EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, + null, + opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); + ep2.setExpiryDate(LocalDate.now().plusDays(2L).format(formatter)); + vendorLicenseManagerImpl.updateEntitlementPool(ep2); + Assert.fail(); + } catch (CoreException exception) { + Assert.assertEquals(exception.code().id(), VendorLicenseErrorCodes.DATE_RANGE_INVALID); } + } - @Test - public void updateWithSameStartExpiryDateTest() { - try { + @Test + public void updateWithSameStartExpiryDateTest() { + try { - Set opScopeChoices; - opScopeChoices = new HashSet<>(); - opScopeChoices.add(OperationalScope.Core); - opScopeChoices.add(OperationalScope.CPU); - opScopeChoices.add(OperationalScope.Network_Wide); - EntitlementPoolEntity ep2 = - createEntitlementPool("vlm4Id", null, ep1_id,EP1_NAME, "EP2 dec", 70, - ThresholdUnit.Absolute, - EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, null, - opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); - ep2.setStartDate(LocalDate.now().format(formatter)); - ep2.setExpiryDate(LocalDate.now().format(formatter)); - vendorLicenseManagerImpl.updateEntitlementPool(ep2, USER1); - Assert.fail(); - } catch (CoreException exception) { - Assert.assertEquals(exception.code().id(), VendorLicenseErrorCodes.DATE_RANGE_INVALID); - } + Set opScopeChoices; + opScopeChoices = new HashSet<>(); + opScopeChoices.add(OperationalScope.Core); + opScopeChoices.add(OperationalScope.CPU); + opScopeChoices.add(OperationalScope.Network_Wide); + EntitlementPoolEntity ep2 = + createEntitlementPool("vlm4Id", null, ep1_id, EP1_NAME, "EP2 dec", 70, + ThresholdUnit.Absolute, + EntitlementMetric.Other, "exception metric2", "inc2", AggregationFunction.Average, + null, + opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); + ep2.setStartDate(LocalDate.now().format(formatter)); + ep2.setExpiryDate(LocalDate.now().format(formatter)); + vendorLicenseManagerImpl.updateEntitlementPool(ep2); + Assert.fail(); + } catch (CoreException exception) { + Assert.assertEquals(exception.code().id(), VendorLicenseErrorCodes.DATE_RANGE_INVALID); } + } - @Test - public void deleteEntitlementPoolTest() { - - VersionInfo versionInfo = new VersionInfo(); - versionInfo.setActiveVersion(VERSION01); - versionInfo.setLockingUser(USER1); - ArrayList viewable = new ArrayList(); - viewable.add(VERSION01); - versionInfo.setViewableVersions(viewable); - - doReturn(versionInfo).when(vendorLicenseManagerImpl).getVersionInfo(vlm1_id, - VersionableEntityAction.Write, USER1); - - Set opScopeChoices; - opScopeChoices = new HashSet<>(); - opScopeChoices.add(OperationalScope.Core); - opScopeChoices.add(OperationalScope.CPU); - opScopeChoices.add(OperationalScope.Network_Wide); - - EntitlementPoolEntity entitlementPool = - createEntitlementPool(vlm1_id,VERSION01, ep1_id,EP1_NAME, "EP2 dec", 70, - ThresholdUnit.Absolute,EntitlementMetric.Other, "exception metric2", "inc2", - AggregationFunction.Average, null, - opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); - entitlementPool.setStartDate(LocalDate.now().format(formatter)); - entitlementPool.setExpiryDate(LocalDate.now().plusDays(1L).format(formatter)); - - doReturn(entitlementPool).when(entitlementPoolDao).get(anyObject()); - - doNothing().when(vendorLicenseManagerImpl).deleteChildLimits(vlm1_id,VERSION01,ep1_id,USER1); - - doNothing().when(vendorLicenseManagerImpl).deleteUniqueName(anyObject(),anyObject(), - anyObject(),anyObject()); + @Test + public void deleteEntitlementPoolTest() { + Set opScopeChoices; + opScopeChoices = new HashSet<>(); + opScopeChoices.add(OperationalScope.Core); + opScopeChoices.add(OperationalScope.CPU); + opScopeChoices.add(OperationalScope.Network_Wide); - vendorLicenseManagerImpl.deleteEntitlementPool(entitlementPool, USER1); + EntitlementPoolEntity entitlementPool = + createEntitlementPool(vlm1_id, VERSION01, ep1_id, EP1_NAME, "EP2 dec", 70, + ThresholdUnit.Absolute, EntitlementMetric.Other, "exception metric2", "inc2", + AggregationFunction.Average, null, + opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); + entitlementPool.setStartDate(LocalDate.now().format(formatter)); + entitlementPool.setExpiryDate(LocalDate.now().plusDays(1L).format(formatter)); - verify(entitlementPoolDao).delete(entitlementPool); - verify(vendorLicenseFacade).updateVlmLastModificationTime(vlm1_id,VERSION01); + doReturn(entitlementPool).when(entitlementPoolDao).get(anyObject()); - } + doNothing().when(vendorLicenseManagerImpl).deleteChildLimits(vlm1_id, VERSION01, ep1_id); - @Test - public void testGetEntitlementPool(){ + doNothing().when(vendorLicenseManagerImpl).deleteUniqueName(anyObject(), anyObject(), + anyObject(), anyObject()); - VersionInfo versionInfo = new VersionInfo(); - versionInfo.setActiveVersion(VERSION01); - versionInfo.setLockingUser(USER1); - ArrayList viewable = new ArrayList(); - viewable.add(VERSION01); - versionInfo.setViewableVersions(viewable); - versionInfo.setActiveVersion(VERSION01); + vendorLicenseManagerImpl.deleteEntitlementPool(entitlementPool); - doReturn(versionInfo).when(vendorLicenseManagerImpl).getVersionInfo(vlm1_id, - VersionableEntityAction.Read, USER1); + verify(entitlementPoolDao).delete(entitlementPool); + } - Set opScopeChoices; - opScopeChoices = new HashSet<>(); - opScopeChoices.add(OperationalScope.Core); - opScopeChoices.add(OperationalScope.CPU); - opScopeChoices.add(OperationalScope.Network_Wide); + @Test + public void testGetEntitlementPool() { + Set opScopeChoices; + opScopeChoices = new HashSet<>(); + opScopeChoices.add(OperationalScope.Core); + opScopeChoices.add(OperationalScope.CPU); + opScopeChoices.add(OperationalScope.Network_Wide); - EntitlementPoolEntity entitlementPool = - createEntitlementPool(vlm1_id,VERSION01, ep1_id,EP1_NAME, "EP2 dec", 70, - ThresholdUnit.Absolute,EntitlementMetric.Other, "exception metric2", "inc2", - AggregationFunction.Average, null, - opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy'T'HH:mm:ss'Z'"); + EntitlementPoolEntity entitlementPool = + createEntitlementPool(vlm1_id, VERSION01, ep1_id, EP1_NAME, "EP2 dec", 70, + ThresholdUnit.Absolute, EntitlementMetric.Other, "exception metric2", "inc2", + AggregationFunction.Average, null, + opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy'T'HH:mm:ss'Z'"); - entitlementPool.setStartDate(LocalDateTime.now().format(formatter)); - entitlementPool.setExpiryDate(LocalDateTime.now().plusDays(1L).format(formatter)); + entitlementPool.setStartDate(LocalDateTime.now().format(formatter)); + entitlementPool.setExpiryDate(LocalDateTime.now().plusDays(1L).format(formatter)); - doReturn(entitlementPool).when(entitlementPoolDao).get(anyObject()); + doReturn(entitlementPool).when(entitlementPoolDao).get(anyObject()); - EntitlementPoolEntity retrived = vendorLicenseManagerImpl.getEntitlementPool - (entitlementPool,USER1); + EntitlementPoolEntity retrived = vendorLicenseManagerImpl.getEntitlementPool(entitlementPool); - Assert.assertEquals(retrived.getId(),entitlementPool.getId()); - Assert.assertEquals(retrived.getVendorLicenseModelId(),entitlementPool.getVendorLicenseModelId()); - Assert.assertEquals(retrived.getVersion(),entitlementPool.getVersion()); - } + Assert.assertEquals(retrived.getId(), entitlementPool.getId()); + Assert.assertEquals(retrived.getVendorLicenseModelId(), + entitlementPool.getVendorLicenseModelId()); + Assert.assertEquals(retrived.getVersion(), entitlementPool.getVersion()); + } - @Test - public void testListEntitlmentPool(){ + @Test + public void testListEntitlmentPool() { - Set opScopeChoices; - opScopeChoices = new HashSet<>(); - opScopeChoices.add(OperationalScope.Core); - opScopeChoices.add(OperationalScope.CPU); - opScopeChoices.add(OperationalScope.Network_Wide); + Set opScopeChoices; + opScopeChoices = new HashSet<>(); + opScopeChoices.add(OperationalScope.Core); + opScopeChoices.add(OperationalScope.CPU); + opScopeChoices.add(OperationalScope.Network_Wide); - doReturn(Arrays.asList( - createEntitlementPool(vlm1_id,VERSION01, ep1_id, EP1_NAME,"EP1 dec", 70, - ThresholdUnit.Absolute,EntitlementMetric.Other, "exception metric1", - "inc1", AggregationFunction.Average, null, - opScopeChoices, null, EntitlementTime.Other, "time1", "sku1"), - createEntitlementPool(vlm1_id,VERSION01, ep2_id, EP2_NAME,"EP2 dec", 70, - ThresholdUnit.Absolute,EntitlementMetric.Other, "exception metric2", - "inc2", AggregationFunction.Average, null, - opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"))) - .when(vendorLicenseFacade).listEntitlementPools(vlm1_id, VERSION01, USER1); - - Collection EPs = - vendorLicenseManagerImpl.listEntitlementPools(vlm1_id, VERSION01, USER1); - - verify(vendorLicenseFacade).listEntitlementPools(vlm1_id, VERSION01, USER1); - Assert.assertEquals(EPs.size(), 2); - EPs.forEach(ep -> Assert.assertTrue(ep.getId().matches(ep1_id + "|" + ep2_id))); - } + doReturn(Arrays.asList( + createEntitlementPool(vlm1_id, VERSION01, ep1_id, EP1_NAME, "EP1 dec", 70, + ThresholdUnit.Absolute, EntitlementMetric.Other, "exception metric1", + "inc1", AggregationFunction.Average, null, + opScopeChoices, null, EntitlementTime.Other, "time1", "sku1"), + createEntitlementPool(vlm1_id, VERSION01, ep2_id, EP2_NAME, "EP2 dec", 70, + ThresholdUnit.Absolute, EntitlementMetric.Other, "exception metric2", + "inc2", AggregationFunction.Average, null, + opScopeChoices, null, EntitlementTime.Other, "time2", "sku2"))) + .when(vendorLicenseFacade).listEntitlementPools(vlm1_id, VERSION01); + + Collection EPs = + vendorLicenseManagerImpl.listEntitlementPools(vlm1_id, VERSION01); + + verify(vendorLicenseFacade).listEntitlementPools(vlm1_id, VERSION01); + Assert.assertEquals(EPs.size(), 2); + EPs.forEach(ep -> Assert.assertTrue(ep.getId().matches(ep1_id + "|" + ep2_id))); + } /* @Test diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/FeatureGroupTest.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/FeatureGroupTest.java index dd3560615e..b9eacc3e6f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/FeatureGroupTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/FeatureGroupTest.java @@ -21,35 +21,27 @@ package org.openecomp.sdc.vendorlicense.impl; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; - import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; -import org.openecomp.sdc.activityLog.ActivityLogManager; import org.openecomp.sdc.vendorlicense.VendorLicenseConstants; -import org.openecomp.sdc.vendorlicense.dao.*; -import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; +import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDao; +import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDao; +import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDao; +import org.openecomp.sdc.vendorlicense.dao.LicenseKeyGroupDao; +import org.openecomp.sdc.vendorlicense.dao.LimitDao; +import org.openecomp.sdc.vendorlicense.dao.VendorLicenseModelDao; import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseTerm; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; -import org.openecomp.sdc.vendorlicense.facade.impl.VendorLicenseFacadeImpl; -import org.openecomp.sdc.vendorlicense.impl.VendorLicenseManagerImpl; import org.openecomp.sdc.versioning.VersioningManager; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; import org.testng.Assert; -import org.testng.AssertJUnit.*; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; @@ -58,7 +50,6 @@ import java.util.Set; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; /** @@ -66,272 +57,254 @@ import static org.mockito.Mockito.verify; */ public class FeatureGroupTest { - //JUnit Test Cases using Mockito - private static final Version VERSION01 = new Version(0, 1); - private static final Version VERSION10 = new Version(1, 0); - private final String FG1_NAME = "FG1 name"; - private static final String USER1 = "TestUser1"; - private static final String USER2 = "TestUser2"; - - private static String vlm1_id = "vlm1_id"; - private static String vlm2_id = "vlm2_id"; - private static String lkg1_id = "lkg1_id"; - private static String lkg2_id = "lkg2_id"; - private static String fg1_id = "fg1_id"; - private static String fg2_id = "fg2_id"; - private static String ep1_id = "ep1_id"; - private static String ep2_id = "ep2_id"; - - @Mock - private VendorLicenseFacade vendorLicenseFacadeMcok; - - @Mock - private LimitDao limitDaoMcok; - @Mock - private ActivityLogManager activityLogManagerMcok; - - @Mock - private VendorLicenseModelDao vendorLicenseModelDao; - - @Mock - private LicenseAgreementDao licenseAgreementDao; - - @Mock - private FeatureGroupDao featureGroupDao; - - @Mock - private EntitlementPoolDao entitlementPoolDao; - - @Mock - private LicenseKeyGroupDao licenseKeyGroupDao; - - @Mock - private VersioningManager versioningManager; - - @InjectMocks - @Spy - private VendorLicenseManagerImpl vendorLicenseManagerImpl; - - public FeatureGroupEntity updateFeatureGroup(String vlmId, Version version, String id, String name, String desc, - String partNumber, String manufacturerReferenceNumber, Set - licenseKeyGroupIds, Set entitlementPoolIds, Set - referencingLicenseAgreements){ - FeatureGroupEntity featureGroup = new FeatureGroupEntity(vlmId, version, id); - featureGroup.setVendorLicenseModelId(vlmId); - featureGroup.setVersion(version); - featureGroup.setId(id); - featureGroup.setName(name); - featureGroup.setDescription(desc); - featureGroup.setPartNumber(partNumber); - //featureGroup.setManufacturerReferenceNumber(manufacturerReferenceNumber); - featureGroup.setLicenseKeyGroupIds(licenseKeyGroupIds); - featureGroup.setEntitlementPoolIds(entitlementPoolIds); - featureGroup.setReferencingLicenseAgreements(referencingLicenseAgreements); - - return featureGroup; - } - - @BeforeMethod - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testUpdate(){ - Set licenseKeyGroupIds; - licenseKeyGroupIds = new HashSet<>(); - licenseKeyGroupIds.add("lkg1"); - - Set entitlementPoolIds; - entitlementPoolIds = new HashSet<>(); - entitlementPoolIds.add("ep1"); - - Set referencingLicenseAgreements; - referencingLicenseAgreements = new HashSet<>(); - referencingLicenseAgreements.add("la1"); - - FeatureGroupEntity featureGroupEntity = updateFeatureGroup("vlmId", VERSION01, "fgId", FG1_NAME, "fg1 desc", + //JUnit Test Cases using Mockito + private static final Version VERSION01 = new Version(0, 1); + private static final Version VERSION10 = new Version(1, 0); + private final String FG1_NAME = "FG1 name"; + private static final String USER1 = "TestUser1"; + private static final String USER2 = "TestUser2"; + + private static String vlm1_id = "vlm1_id"; + private static String vlm2_id = "vlm2_id"; + private static String lkg1_id = "lkg1_id"; + private static String lkg2_id = "lkg2_id"; + private static String fg1_id = "fg1_id"; + private static String fg2_id = "fg2_id"; + private static String ep1_id = "ep1_id"; + private static String ep2_id = "ep2_id"; + + @Mock + private VendorLicenseFacade vendorLicenseFacadeMcok; + + @Mock + private LimitDao limitDaoMcok; + + @Mock + private VendorLicenseModelDao vendorLicenseModelDao; + + @Mock + private LicenseAgreementDao licenseAgreementDao; + + @Mock + private FeatureGroupDao featureGroupDao; + + @Mock + private EntitlementPoolDao entitlementPoolDao; + + @Mock + private LicenseKeyGroupDao licenseKeyGroupDao; + + @Mock + private VersioningManager versioningManager; + + @InjectMocks + @Spy + private VendorLicenseManagerImpl vendorLicenseManagerImpl; + + public FeatureGroupEntity updateFeatureGroup(String vlmId, Version version, String id, + String name, String desc, + String partNumber, + String manufacturerReferenceNumber, Set + licenseKeyGroupIds, + Set entitlementPoolIds, Set + referencingLicenseAgreements) { + FeatureGroupEntity featureGroup = new FeatureGroupEntity(vlmId, version, id); + featureGroup.setVendorLicenseModelId(vlmId); + featureGroup.setVersion(version); + featureGroup.setId(id); + featureGroup.setName(name); + featureGroup.setDescription(desc); + featureGroup.setPartNumber(partNumber); + //featureGroup.setManufacturerReferenceNumber(manufacturerReferenceNumber); + featureGroup.setLicenseKeyGroupIds(licenseKeyGroupIds); + featureGroup.setEntitlementPoolIds(entitlementPoolIds); + featureGroup.setReferencingLicenseAgreements(referencingLicenseAgreements); + + return featureGroup; + } + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testUpdate() { + Set licenseKeyGroupIds; + licenseKeyGroupIds = new HashSet<>(); + licenseKeyGroupIds.add("lkg1"); + + Set entitlementPoolIds; + entitlementPoolIds = new HashSet<>(); + entitlementPoolIds.add("ep1"); + + Set referencingLicenseAgreements; + referencingLicenseAgreements = new HashSet<>(); + referencingLicenseAgreements.add("la1"); + + FeatureGroupEntity featureGroupEntity = + updateFeatureGroup("vlmId", VERSION01, "fgId", FG1_NAME, "fg1 desc", "partNumber", "MRN", licenseKeyGroupIds, entitlementPoolIds, referencingLicenseAgreements); - doReturn(featureGroupEntity).when(featureGroupDao).get(anyObject()); + doReturn(featureGroupEntity).when(featureGroupDao).get(anyObject()); /*if(featureGroupEntity.getManufacturerReferenceNumber() != null) featureGroupDao.update(featureGroupEntity); verify(featureGroupDao).update(anyObject());*/ - } + } - @Test - public void testUpdateWithoutManufacturingReferenceNumber(){ - Set licenseKeyGroupIds; - licenseKeyGroupIds = new HashSet<>(); - licenseKeyGroupIds.add("lkg1"); + @Test + public void testUpdateWithoutManufacturingReferenceNumber() { + Set licenseKeyGroupIds; + licenseKeyGroupIds = new HashSet<>(); + licenseKeyGroupIds.add("lkg1"); - Set entitlementPoolIds; - entitlementPoolIds = new HashSet<>(); - entitlementPoolIds.add("ep1"); + Set entitlementPoolIds; + entitlementPoolIds = new HashSet<>(); + entitlementPoolIds.add("ep1"); - Set referencingLicenseAgreements; - referencingLicenseAgreements = new HashSet<>(); - referencingLicenseAgreements.add("la1"); + Set referencingLicenseAgreements; + referencingLicenseAgreements = new HashSet<>(); + referencingLicenseAgreements.add("la1"); - FeatureGroupEntity featureGroupEntity = updateFeatureGroup("vlmId", VERSION01, "fgId", FG1_NAME, "fg1 desc", + FeatureGroupEntity featureGroupEntity = + updateFeatureGroup("vlmId", VERSION01, "fgId", FG1_NAME, "fg1 desc", "partNumber", null, licenseKeyGroupIds, entitlementPoolIds, referencingLicenseAgreements); - doReturn(featureGroupEntity).when(featureGroupDao).get(anyObject()); + doReturn(featureGroupEntity).when(featureGroupDao).get(anyObject()); /*if(featureGroupEntity.getManufacturerReferenceNumber() != null) featureGroupDao.update(featureGroupEntity); verify(featureGroupDao, never()).update(anyObject());*/ - } - - @Test - public void testListFeatureGroups() { - doReturn(Arrays.asList( - createFeatureGroup(vlm1_id, VERSION01, fg1_id, "FG1", "FG1 desc", new HashSet(), - new HashSet()), - createFeatureGroup(vlm1_id, VERSION01, fg2_id, "FG2", "FG2 desc", new HashSet(), - new HashSet()))) - .when(vendorLicenseFacadeMcok).listFeatureGroups(vlm1_id, VERSION01, USER1); - - Collection FGs = - vendorLicenseManagerImpl.listFeatureGroups(vlm1_id, VERSION01, USER1); - - verify(vendorLicenseFacadeMcok).listFeatureGroups(vlm1_id, VERSION01, USER1); - Assert.assertEquals(FGs.size(), 2); - FGs.forEach(fg -> Assert.assertTrue(fg.getId().matches(fg1_id + "|" + fg2_id))); - } - - @Test - public void testCreateFeatureGroup() { - FeatureGroupEntity featureGroupEntity = new FeatureGroupEntity(vlm1_id,VERSION01, - fg1_id); - - doReturn(featureGroupEntity).when(vendorLicenseFacadeMcok).createFeatureGroup - (featureGroupEntity,USER1); + } + + @Test + public void testListFeatureGroups() { + doReturn(Arrays.asList( + createFeatureGroup(vlm1_id, VERSION01, fg1_id, "FG1", "FG1 desc", new HashSet(), + new HashSet()), + createFeatureGroup(vlm1_id, VERSION01, fg2_id, "FG2", "FG2 desc", new HashSet(), + new HashSet()))) + .when(vendorLicenseFacadeMcok).listFeatureGroups(vlm1_id, VERSION01); + + Collection FGs = + vendorLicenseManagerImpl.listFeatureGroups(vlm1_id, VERSION01); + + verify(vendorLicenseFacadeMcok).listFeatureGroups(vlm1_id, VERSION01); + Assert.assertEquals(FGs.size(), 2); + FGs.forEach(fg -> Assert.assertTrue(fg.getId().matches(fg1_id + "|" + fg2_id))); + } - vendorLicenseManagerImpl.createFeatureGroup(featureGroupEntity,USER1); - - verify(vendorLicenseFacadeMcok).createFeatureGroup(featureGroupEntity,USER1); - } - - - @Test - public void testUpdateFeatureGroup(){ - VersionInfo versionInfo = new VersionInfo(); - versionInfo.setActiveVersion(VERSION01); - versionInfo.setLockingUser(USER1); - ArrayList viewable = new ArrayList(); - viewable.add(VERSION01); - versionInfo.setViewableVersions(viewable); - - doReturn(versionInfo).when(vendorLicenseManagerImpl).getVersionInfo(vlm1_id, - VersionableEntityAction.Write, USER1); - FeatureGroupEntity existingFG = new FeatureGroupEntity(vlm1_id, VERSION01, fg1_id); - - existingFG.setEntitlementPoolIds(new HashSet()); - existingFG.setLicenseKeyGroupIds(new HashSet()); - - doReturn(existingFG).when(featureGroupDao).get(existingFG); - - Set removedEPs = new HashSet<>(); - Set addedEPs = new HashSet<>(); - - addedEPs.add(ep1_id); - addedEPs.add(ep2_id); - EntitlementPoolEntity ep1 = new EntitlementPoolEntity(vlm1_id, VERSION01, ep1_id); - EntitlementPoolEntity ep2 = new EntitlementPoolEntity(vlm1_id, VERSION01, ep2_id); - doReturn(ep1).when(entitlementPoolDao).get(ep1); - doReturn(ep2).when(entitlementPoolDao).get(ep2); - - Set removedLKGs = new HashSet<>(); - Set addedLKGs = new HashSet<>(); - - addedLKGs.add(lkg1_id); - addedLKGs.add(lkg2_id); - LicenseKeyGroupEntity lkg1 = new LicenseKeyGroupEntity(vlm1_id, VERSION01, lkg1_id); - LicenseKeyGroupEntity lkg2 = new LicenseKeyGroupEntity(vlm1_id, VERSION01, lkg2_id); - doReturn(lkg1).when(licenseKeyGroupDao).get(lkg1); - doReturn(lkg2).when(licenseKeyGroupDao).get(lkg2); - - doNothing().when(vendorLicenseManagerImpl).updateUniqueName(anyObject(), anyObject(), - anyObject(),anyObject(), anyObject()); - - vendorLicenseManagerImpl.updateFeatureGroup(existingFG,addedLKGs,removedLKGs, addedEPs, - removedEPs, USER1); - - verify(vendorLicenseManagerImpl).addLicenseKeyGroupsToFeatureGroupsRef(addedLKGs, - existingFG); - verify(vendorLicenseManagerImpl).removeLicenseKeyGroupsToFeatureGroupsRef(removedLKGs, - existingFG); - verify(vendorLicenseManagerImpl).addEntitlementPoolsToFeatureGroupsRef(addedEPs,existingFG); - verify(vendorLicenseManagerImpl).removeEntitlementPoolsToFeatureGroupsRef(removedEPs, - existingFG); - - verify(featureGroupDao) - .updateFeatureGroup(existingFG,addedEPs,removedEPs, addedLKGs, removedLKGs); - verify(vendorLicenseFacadeMcok).updateVlmLastModificationTime(vlm1_id,VERSION01); - } - - - @Test - public void testGetFeatureGroup(){ - FeatureGroupEntity featureGroupEntity = new FeatureGroupEntity(vlm1_id,VERSION01,fg1_id); - vendorLicenseManagerImpl.getFeatureGroupModel(featureGroupEntity,USER1); - verify(vendorLicenseFacadeMcok).getFeatureGroupModel(featureGroupEntity,USER1); - } - - @Test - public void deleteFeatureGroupTest() { - - VersionInfo versionInfo = new VersionInfo(); - versionInfo.setActiveVersion(VERSION01); - versionInfo.setLockingUser(USER1); - ArrayList viewable = new ArrayList(); - viewable.add(VERSION01); - versionInfo.setViewableVersions(viewable); - - doReturn(versionInfo).when(vendorLicenseManagerImpl).getVersionInfo(vlm1_id, - VersionableEntityAction.Write, USER1); - - FeatureGroupEntity existingFG = new FeatureGroupEntity(vlm1_id, VERSION01, fg1_id); - existingFG.setName("FG_name"); - existingFG.setLicenseKeyGroupIds(new HashSet()); - existingFG.setEntitlementPoolIds(new HashSet()); - existingFG.setLicenseKeyGroupIds(new HashSet()); - - doReturn(existingFG).when(featureGroupDao).get(anyObject()); - - doNothing().when(vendorLicenseManagerImpl).deleteUniqueName(VendorLicenseConstants - .UniqueValues.FEATURE_GROUP_NAME,vlm1_id,VERSION01.toString(),existingFG.getName()); - - vendorLicenseManagerImpl.deleteFeatureGroup(existingFG, USER1); - - verify(featureGroupDao).delete(existingFG); - verify(vendorLicenseFacadeMcok).updateVlmLastModificationTime(vlm1_id,VERSION01); - - verify(vendorLicenseManagerImpl).removeLicenseKeyGroupsToFeatureGroupsRef(existingFG - .getLicenseKeyGroupIds(),existingFG); - verify(vendorLicenseManagerImpl).removeEntitlementPoolsToFeatureGroupsRef(existingFG - .getEntitlementPoolIds(),existingFG); - verify(vendorLicenseManagerImpl).deleteUniqueName(VendorLicenseConstants - .UniqueValues.FEATURE_GROUP_NAME,vlm1_id,VERSION01.toString(),existingFG.getName()); - } - - private FeatureGroupEntity createFeatureGroup(String vendorId, Version version, String id, - String name, String description, - Set entitlementPoolIds, - Set licenseKeyGroupIds) { - FeatureGroupEntity featureGroup = new FeatureGroupEntity(); - featureGroup.setVendorLicenseModelId(vendorId); - featureGroup.setVersion(version); - featureGroup.setId(id); - featureGroup.setName(name); - featureGroup.setDescription(description); - featureGroup.setEntitlementPoolIds(entitlementPoolIds); - featureGroup.setLicenseKeyGroupIds(licenseKeyGroupIds); - return featureGroup; - } + @Test + public void testCreateFeatureGroup() { + FeatureGroupEntity featureGroupEntity = new FeatureGroupEntity(vlm1_id, VERSION01, + fg1_id); + + doReturn(featureGroupEntity).when(vendorLicenseFacadeMcok).createFeatureGroup + (featureGroupEntity); + + vendorLicenseManagerImpl.createFeatureGroup(featureGroupEntity); + + verify(vendorLicenseFacadeMcok).createFeatureGroup(featureGroupEntity); + } + + + @Test + public void testUpdateFeatureGroup() { + FeatureGroupEntity existingFG = new FeatureGroupEntity(vlm1_id, VERSION01, fg1_id); + + existingFG.setEntitlementPoolIds(new HashSet()); + existingFG.setLicenseKeyGroupIds(new HashSet()); + + doReturn(existingFG).when(featureGroupDao).get(existingFG); + + Set removedEPs = new HashSet<>(); + Set addedEPs = new HashSet<>(); + + addedEPs.add(ep1_id); + addedEPs.add(ep2_id); + EntitlementPoolEntity ep1 = new EntitlementPoolEntity(vlm1_id, VERSION01, ep1_id); + EntitlementPoolEntity ep2 = new EntitlementPoolEntity(vlm1_id, VERSION01, ep2_id); + doReturn(ep1).when(entitlementPoolDao).get(ep1); + doReturn(ep2).when(entitlementPoolDao).get(ep2); + + Set removedLKGs = new HashSet<>(); + Set addedLKGs = new HashSet<>(); + + addedLKGs.add(lkg1_id); + addedLKGs.add(lkg2_id); + LicenseKeyGroupEntity lkg1 = new LicenseKeyGroupEntity(vlm1_id, VERSION01, lkg1_id); + LicenseKeyGroupEntity lkg2 = new LicenseKeyGroupEntity(vlm1_id, VERSION01, lkg2_id); + doReturn(lkg1).when(licenseKeyGroupDao).get(lkg1); + doReturn(lkg2).when(licenseKeyGroupDao).get(lkg2); + + doNothing().when(vendorLicenseManagerImpl).updateUniqueName(anyObject(), anyObject(), + anyObject(), anyObject(), anyObject()); + + vendorLicenseManagerImpl.updateFeatureGroup(existingFG, addedLKGs, removedLKGs, addedEPs, + removedEPs); + + verify(vendorLicenseManagerImpl).addLicenseKeyGroupsToFeatureGroupsRef(addedLKGs, + existingFG); + verify(vendorLicenseManagerImpl).removeLicenseKeyGroupsToFeatureGroupsRef(removedLKGs, + existingFG); + verify(vendorLicenseManagerImpl).addEntitlementPoolsToFeatureGroupsRef(addedEPs, existingFG); + verify(vendorLicenseManagerImpl).removeEntitlementPoolsToFeatureGroupsRef(removedEPs, + existingFG); + + verify(featureGroupDao) + .updateFeatureGroup(existingFG, addedEPs, removedEPs, addedLKGs, removedLKGs); + } + + + @Test + public void testGetFeatureGroup() { + FeatureGroupEntity featureGroupEntity = new FeatureGroupEntity(vlm1_id, VERSION01, fg1_id); + vendorLicenseManagerImpl.getFeatureGroupModel(featureGroupEntity); + verify(vendorLicenseFacadeMcok).getFeatureGroupModel(featureGroupEntity); + } + + @Test + public void deleteFeatureGroupTest() { + + FeatureGroupEntity existingFG = new FeatureGroupEntity(vlm1_id, VERSION01, fg1_id); + existingFG.setName("FG_name"); + existingFG.setLicenseKeyGroupIds(new HashSet()); + existingFG.setEntitlementPoolIds(new HashSet()); + existingFG.setLicenseKeyGroupIds(new HashSet()); + + doReturn(existingFG).when(featureGroupDao).get(anyObject()); + + doNothing().when(vendorLicenseManagerImpl).deleteUniqueName(VendorLicenseConstants + .UniqueValues.FEATURE_GROUP_NAME, vlm1_id, VERSION01.toString(), existingFG.getName()); + + vendorLicenseManagerImpl.deleteFeatureGroup(existingFG); + + verify(featureGroupDao).delete(existingFG); + + verify(vendorLicenseManagerImpl).removeLicenseKeyGroupsToFeatureGroupsRef(existingFG + .getLicenseKeyGroupIds(), existingFG); + verify(vendorLicenseManagerImpl).removeEntitlementPoolsToFeatureGroupsRef(existingFG + .getEntitlementPoolIds(), existingFG); + verify(vendorLicenseManagerImpl).deleteUniqueName(VendorLicenseConstants + .UniqueValues.FEATURE_GROUP_NAME, vlm1_id, VERSION01.toString(), existingFG.getName()); + } + + private FeatureGroupEntity createFeatureGroup(String vendorId, Version version, String id, + String name, String description, + Set entitlementPoolIds, + Set licenseKeyGroupIds) { + FeatureGroupEntity featureGroup = new FeatureGroupEntity(); + featureGroup.setVendorLicenseModelId(vendorId); + featureGroup.setVersion(version); + featureGroup.setId(id); + featureGroup.setName(name); + featureGroup.setDescription(description); + featureGroup.setEntitlementPoolIds(entitlementPoolIds); + featureGroup.setLicenseKeyGroupIds(licenseKeyGroupIds); + return featureGroup; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/LicenseAgreementTest.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/LicenseAgreementTest.java index b0b5953a53..91435e85fd 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/LicenseAgreementTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/LicenseAgreementTest.java @@ -26,17 +26,11 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; -import org.openecomp.core.util.UniqueValueUtil; -import org.openecomp.core.utilities.CommonMethods; -import org.openecomp.sdc.activityLog.ActivityLogManager; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; -import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.vendorlicense.VendorLicenseConstants; import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDao; import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDao; -import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDaoFactory; import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDao; -import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDaoFactory; import org.openecomp.sdc.vendorlicense.dao.LicenseKeyGroupDao; import org.openecomp.sdc.vendorlicense.dao.LimitDao; import org.openecomp.sdc.vendorlicense.dao.VendorLicenseModelDao; @@ -44,36 +38,24 @@ import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; import org.openecomp.sdc.vendorlicense.dao.types.LicenseTerm; -import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; -import org.openecomp.sdc.vendorlicense.impl.VendorLicenseManagerImpl; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; import org.openecomp.sdc.versioning.VersioningManager; -import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; import org.testng.Assert; -import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.verify; -import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE; -import static org.testng.AssertJUnit.assertEquals; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; + public class LicenseAgreementTest { private static final String USER1 = "TestUser1"; @@ -104,8 +86,6 @@ public class LicenseAgreementTest { private LicenseKeyGroupDao licenseKeyGroupDaoMcok; @Mock private LimitDao limitDaoMcok; - @Mock - private ActivityLogManager activityLogManagerMcok; @Spy @@ -160,12 +140,12 @@ public class LicenseAgreementTest { @Test public void listLicenseAgreementsTest() { - LicenseAgreementEntity la = new LicenseAgreementEntity(vlm1_id,VERSION01,USER1); - doReturn(la).when(vendorLicenseManager).createLicenseAgreementForList(vlm1_id,VERSION01, USER1); + LicenseAgreementEntity la = + new LicenseAgreementEntity(vlm1_id, VERSION01, null); // TODO: 8/13/2017 doReturn(Arrays.asList( createLicenseAgreement(vlm1_id, VERSION01, la1_id, "LA1", "LA1 " + - "desc","RequirementsAndConstrains2", new ChoiceOrOther<>(LicenseTerm.Unlimited, null), + "desc", "RequirementsAndConstrains2", new ChoiceOrOther<>(LicenseTerm.Unlimited, null), "fg1"), createLicenseAgreement(vlm1_id, VERSION01, la2_id, "LA2", "LA2 desc", "RequirementsAndConstrains2", new ChoiceOrOther<>(LicenseTerm.Unlimited, null), @@ -173,23 +153,23 @@ public class LicenseAgreementTest { .when(licenseAgreementDaoMcok).list(la); Collection LAs = - vendorLicenseManager.listLicenseAgreements(vlm1_id, VERSION01, USER1); + vendorLicenseManager.listLicenseAgreements(vlm1_id, VERSION01); Assert.assertEquals(LAs.size(), 2); - LAs.forEach(licseAgreement-> Assert.assertTrue(licseAgreement.getId().matches(la1_id + "|" + la2_id))); + LAs.forEach( + licseAgreement -> Assert.assertTrue(licseAgreement.getId().matches(la1_id + "|" + la2_id))); } @Test public void testListLicenseAgreementsWhenNone() { - LicenseAgreementEntity la = new LicenseAgreementEntity(vlm1_id,VERSION01,USER1); - doReturn(la).when(vendorLicenseManager).createLicenseAgreementForList(vlm1_id,VERSION01, - USER1); + LicenseAgreementEntity la = + new LicenseAgreementEntity(vlm1_id, VERSION01, null); // TODO: 8/13/2017 doReturn(new ArrayList()) .when(licenseAgreementDaoMcok).list(la); Collection LAs = - vendorLicenseManager.listLicenseAgreements(vlm1_id, VERSION01, USER1); + vendorLicenseManager.listLicenseAgreements(vlm1_id, VERSION01); verify(licenseAgreementDaoMcok).list(la); Assert.assertEquals(LAs.size(), 0); @@ -199,29 +179,19 @@ public class LicenseAgreementTest { @Test public void testCreateLicenseAgreement() { - LicenseAgreementEntity licenseAgreementEntity = new LicenseAgreementEntity(vlm1_id,VERSION01, + LicenseAgreementEntity licenseAgreementEntity = new LicenseAgreementEntity(vlm1_id, VERSION01, la2_id); doReturn(licenseAgreementEntity).when(vendorLicenseFacadeMcok).createLicenseAgreement - (licenseAgreementEntity,USER1); + (licenseAgreementEntity); - vendorLicenseManager.createLicenseAgreement(licenseAgreementEntity,USER1); + vendorLicenseManager.createLicenseAgreement(licenseAgreementEntity); - verify(vendorLicenseFacadeMcok).createLicenseAgreement(licenseAgreementEntity,USER1); + verify(vendorLicenseFacadeMcok).createLicenseAgreement(licenseAgreementEntity); } @Test public void testUpdateLicenseAgreement() { - - VersionInfo versionInfo = new VersionInfo(); - versionInfo.setActiveVersion(VERSION01); - versionInfo.setLockingUser(USER1); - ArrayList viewable = new ArrayList(); - viewable.add(VERSION01); - versionInfo.setViewableVersions(viewable); - - doReturn(versionInfo).when(vendorLicenseManager).getVersionInfo(vlm1_id, - VersionableEntityAction.Write, USER1); LicenseAgreementEntity existingLA = new LicenseAgreementEntity(vlm1_id, VERSION01, la1_id); existingLA.setFeatureGroupIds(new HashSet()); @@ -236,34 +206,20 @@ public class LicenseAgreementTest { FeatureGroupEntity fg2 = new FeatureGroupEntity(vlm1_id, VERSION01, fg2_id); doReturn(fg1).when(featureGroupDaoMcok).get(fg1); doReturn(fg2).when(featureGroupDaoMcok).get(fg2); - doReturn(existingLA).when(vendorLicenseManager).createLicenseAgreementForList(vlm1_id,VERSION01, - USER1); doNothing().when(vendorLicenseManager).updateUniqueName(anyObject(), anyObject(), anyObject(), anyObject(), anyObject()); - vendorLicenseManager.updateLicenseAgreement(existingLA, addedFGs, removedFGs, USER1); + vendorLicenseManager.updateLicenseAgreement(existingLA, addedFGs, removedFGs); verify(licenseAgreementDaoMcok) .updateColumnsAndDeltaFeatureGroupIds(existingLA, addedFGs, removedFGs); - verify(vendorLicenseManager).addFeatureGroupsToLicenseAgreementRef(addedFGs,existingLA); - verify(vendorLicenseManager).removeFeatureGroupsToLicenseAgreementRef(removedFGs,existingLA); - verify(vendorLicenseFacadeMcok).updateVlmLastModificationTime(vlm1_id,VERSION01); + verify(vendorLicenseManager).addFeatureGroupsToLicenseAgreementRef(addedFGs, existingLA); + verify(vendorLicenseManager).removeFeatureGroupsToLicenseAgreementRef(removedFGs, existingLA); } @Test public void deleteLicenseAgreementsTest() { - - VersionInfo versionInfo = new VersionInfo(); - versionInfo.setActiveVersion(VERSION01); - versionInfo.setLockingUser(USER1); - ArrayList viewable = new ArrayList(); - viewable.add(VERSION01); - versionInfo.setViewableVersions(viewable); - - doReturn(versionInfo).when(vendorLicenseManager).getVersionInfo(vlm1_id, - VersionableEntityAction.Write, USER1); - LicenseAgreementEntity existingLA = new LicenseAgreementEntity(vlm1_id, VERSION01, la1_id); existingLA.setName("LA"); existingLA.setFeatureGroupIds(new HashSet<>()); @@ -271,20 +227,19 @@ public class LicenseAgreementTest { doReturn(existingLA).when(licenseAgreementDaoMcok).get(anyObject()); doNothing().when(vendorLicenseManager).deleteUniqueName(VendorLicenseConstants.UniqueValues - .LICENSE_AGREEMENT_NAME,vlm1_id,VERSION01.toString(),existingLA.getName()); + .LICENSE_AGREEMENT_NAME, vlm1_id, VERSION01.toString(), existingLA.getName()); - vendorLicenseManager.deleteLicenseAgreement(vlm1_id, VERSION01, la1_id, USER1); + vendorLicenseManager.deleteLicenseAgreement(vlm1_id, VERSION01, la1_id); verify(licenseAgreementDaoMcok).delete(existingLA); - verify(vendorLicenseFacadeMcok).updateVlmLastModificationTime(vlm1_id,VERSION01); verify(vendorLicenseManager).removeFeatureGroupsToLicenseAgreementRef(existingLA - .getFeatureGroupIds(),existingLA); + .getFeatureGroupIds(), existingLA); } @Test - public void testGetLicenseAgreement(){ - vendorLicenseManager.getLicenseAgreementModel(vlm1_id,VERSION01,la1_id,USER1); - verify(vendorLicenseFacadeMcok).getLicenseAgreementModel(vlm1_id,VERSION01,la1_id,USER1); + public void testGetLicenseAgreement() { + vendorLicenseManager.getLicenseAgreementModel(vlm1_id, VERSION01, la1_id); + verify(vendorLicenseFacadeMcok).getLicenseAgreementModel(vlm1_id, VERSION01, la1_id); } /* @@ -300,7 +255,7 @@ public class LicenseAgreementTest { featureGroupDao.create(created); featureGroupDao.addReferencingLicenseAgreement(created, licenseAgreement.getId()); - vendorLicenseManager.deleteFeatureGroup(created, USER1); + vendorLicenseManager.deleteFeatureGroup(created); LicenseAgreementEntity afterDeletingFG = licenseAgreementDao.get(licenseAgreement); Assert.assertEquals(afterDeletingFG.getFeatureGroupIds().size(), 1); Assert.assertTrue(afterDeletingFG.getFeatureGroupIds().contains("fg2")); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/LicenseKeyGroupTest.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/LicenseKeyGroupTest.java index f0dd383a1f..dc376ee5b6 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/LicenseKeyGroupTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/LicenseKeyGroupTest.java @@ -26,21 +26,19 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; 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.vendorlicense.dao.LicenseKeyGroupDao; import org.openecomp.sdc.vendorlicense.dao.LimitDao; -import org.openecomp.sdc.vendorlicense.dao.types.*; +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.errors.VendorLicenseErrorCodes; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.util.ArrayList; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Arrays; @@ -56,10 +54,10 @@ import static org.mockito.Mockito.verify; public class LicenseKeyGroupTest { //JUnit Test Cases using Mockito - private final String USER = "lkgTestUser"; - private final String LKG_NAME = "LKG name"; - private final String LKG2_NAME = "LKG2 name"; - private final String LT_NAME = "LT name"; + private final String USER = "lkgTestUser"; + private final String LKG_NAME = "LKG name"; + private final String LKG2_NAME = "LKG2 name"; + private final String LT_NAME = "LT name"; private final String LKG1_NAME = "LKG1 name"; private final String USER1 = "user1"; private static String lkg1_id = "lkg1_id"; @@ -85,15 +83,16 @@ public class LicenseKeyGroupTest { MockitoAnnotations.initMocks(this); } - private LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyType type, Set operationalScopeChoices, - String operationalScopeOther) - { + private LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyType type, + Set operationalScopeChoices, + String operationalScopeOther) { LicenseKeyGroupEntity licenseKeyGroupEntity = new LicenseKeyGroupEntity(); licenseKeyGroupEntity.setType(type); licenseKeyGroupEntity.setOperationalScope( new MultiChoiceOrOther<>(operationalScopeChoices, operationalScopeOther)); return licenseKeyGroupEntity; } + /* @Test public void deleteLicenseKeyGroupTest() { @@ -207,14 +206,14 @@ public class LicenseKeyGroupTest { opScopeChoices.add(OperationalScope.CPU); opScopeChoices.add(OperationalScope.Network_Wide); LicenseKeyGroupEntity lkg = - createLicenseKeyGroup("vlm1Id", null,lkg1_id, LKG1_NAME, "LKG1 dec",LicenseKeyType.Unique, + createLicenseKeyGroup("vlm1Id", null, lkg1_id, LKG1_NAME, "LKG1 dec", LicenseKeyType.Unique, new MultiChoiceOrOther<>(opScopeChoices, null)); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); lkg.setStartDate(LocalDate.now().format(formatter)); lkg.setExpiryDate(LocalDate.now().plusDays(1L).format(formatter)); - vendorLicenseManagerImpl.createLicenseKeyGroup(lkg, USER1); - verify(vendorLicenseFacade).createLicenseKeyGroup(lkg,USER1); + vendorLicenseManagerImpl.createLicenseKeyGroup(lkg); + verify(vendorLicenseFacade).createLicenseKeyGroup(lkg); } @Test @@ -227,12 +226,13 @@ public class LicenseKeyGroupTest { opScopeChoices.add(OperationalScope.CPU); opScopeChoices.add(OperationalScope.Network_Wide); LicenseKeyGroupEntity lkg = - createLicenseKeyGroup("vlm1Id", null, lkg1_id,LKG1_NAME, "LKG1 dec",LicenseKeyType.Unique, + createLicenseKeyGroup("vlm1Id", null, lkg1_id, LKG1_NAME, "LKG1 dec", + LicenseKeyType.Unique, new MultiChoiceOrOther<>(opScopeChoices, null)); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); lkg.setStartDate(LocalDate.now().format(formatter)); lkg.setExpiryDate(LocalDate.now().minusDays(2L).format(formatter)); - vendorLicenseManagerImpl.createLicenseKeyGroup(lkg, USER1); + vendorLicenseManagerImpl.createLicenseKeyGroup(lkg); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), VendorLicenseErrorCodes.DATE_RANGE_INVALID); @@ -249,11 +249,12 @@ public class LicenseKeyGroupTest { opScopeChoices.add(OperationalScope.CPU); opScopeChoices.add(OperationalScope.Network_Wide); LicenseKeyGroupEntity lkg = - createLicenseKeyGroup("vlm1Id", null, lkg1_id,LKG1_NAME, "LKG1 dec",LicenseKeyType.Unique, + createLicenseKeyGroup("vlm1Id", null, lkg1_id, LKG1_NAME, "LKG1 dec", + LicenseKeyType.Unique, new MultiChoiceOrOther<>(opScopeChoices, null)); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); lkg.setExpiryDate(LocalDate.now().plusDays(2L).format(formatter)); - vendorLicenseManagerImpl.createLicenseKeyGroup(lkg, USER1).getId(); + vendorLicenseManagerImpl.createLicenseKeyGroup(lkg).getId(); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), VendorLicenseErrorCodes.DATE_RANGE_INVALID); @@ -270,12 +271,13 @@ public class LicenseKeyGroupTest { opScopeChoices.add(OperationalScope.CPU); opScopeChoices.add(OperationalScope.Network_Wide); LicenseKeyGroupEntity lkg = - createLicenseKeyGroup("vlm1Id", null, lkg1_id,LKG1_NAME, "LKG1 dec",LicenseKeyType.Unique, + createLicenseKeyGroup("vlm1Id", null, lkg1_id, LKG1_NAME, "LKG1 dec", + LicenseKeyType.Unique, new MultiChoiceOrOther<>(opScopeChoices, null)); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); lkg.setStartDate(LocalDate.now().plusDays(2L).format(formatter)); lkg.setExpiryDate(LocalDate.now().plusDays(2L).format(formatter)); - vendorLicenseManagerImpl.createLicenseKeyGroup(lkg, USER1).getId(); + vendorLicenseManagerImpl.createLicenseKeyGroup(lkg).getId(); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), VendorLicenseErrorCodes.DATE_RANGE_INVALID); @@ -290,19 +292,14 @@ public class LicenseKeyGroupTest { opScopeChoices.add(OperationalScope.CPU); opScopeChoices.add(OperationalScope.Network_Wide); LicenseKeyGroupEntity lkg = - createLicenseKeyGroup(vlm1_id, null,lkg1_id, LKG1_NAME, "LKG1 dec",LicenseKeyType.Unique, + createLicenseKeyGroup(vlm1_id, null, lkg1_id, LKG1_NAME, "LKG1 dec", LicenseKeyType.Unique, new MultiChoiceOrOther<>(opScopeChoices, null)); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); lkg.setStartDate(LocalDate.now().minusDays(3L).format(formatter)); lkg.setExpiryDate(LocalDate.now().minusDays(2L).format(formatter)); - VersionInfo info = new VersionInfo(); - info.getViewableVersions().add(VERSION01); - info.setActiveVersion(VERSION01); - doReturn(info).when(vendorLicenseFacade).getVersionInfo(anyObject(),anyObject(),anyObject()); - - vendorLicenseManagerImpl.updateLicenseKeyGroup(lkg, USER1); - verify(vendorLicenseFacade).updateLicenseKeyGroup(lkg,USER1); - verify(vendorLicenseFacade).updateVlmLastModificationTime(vlm1_id,VERSION01); + + vendorLicenseManagerImpl.updateLicenseKeyGroup(lkg); + verify(vendorLicenseFacade).updateLicenseKeyGroup(lkg); } @Test @@ -315,12 +312,13 @@ public class LicenseKeyGroupTest { opScopeChoices.add(OperationalScope.CPU); opScopeChoices.add(OperationalScope.Network_Wide); LicenseKeyGroupEntity lkg = - createLicenseKeyGroup("vlm1Id", null, lkg1_id,LKG1_NAME, "LKG1 dec",LicenseKeyType.Unique, + createLicenseKeyGroup("vlm1Id", null, lkg1_id, LKG1_NAME, "LKG1 dec", + LicenseKeyType.Unique, new MultiChoiceOrOther<>(opScopeChoices, null)); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); lkg.setStartDate(LocalDate.now().format(formatter)); lkg.setExpiryDate(LocalDate.now().minusDays(2L).format(formatter)); - vendorLicenseManagerImpl.updateLicenseKeyGroup(lkg, USER1); + vendorLicenseManagerImpl.updateLicenseKeyGroup(lkg); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), VendorLicenseErrorCodes.DATE_RANGE_INVALID); @@ -337,11 +335,12 @@ public class LicenseKeyGroupTest { opScopeChoices.add(OperationalScope.CPU); opScopeChoices.add(OperationalScope.Network_Wide); LicenseKeyGroupEntity lkg = - createLicenseKeyGroup("vlm1Id", null, lkg1_id,LKG1_NAME, "LKG1 dec",LicenseKeyType.Unique, + createLicenseKeyGroup("vlm1Id", null, lkg1_id, LKG1_NAME, "LKG1 dec", + LicenseKeyType.Unique, new MultiChoiceOrOther<>(opScopeChoices, null)); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); lkg.setExpiryDate(LocalDate.now().plusDays(2L).format(formatter)); - vendorLicenseManagerImpl.updateLicenseKeyGroup(lkg, USER1); + vendorLicenseManagerImpl.updateLicenseKeyGroup(lkg); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), VendorLicenseErrorCodes.DATE_RANGE_INVALID); @@ -358,12 +357,13 @@ public class LicenseKeyGroupTest { opScopeChoices.add(OperationalScope.CPU); opScopeChoices.add(OperationalScope.Network_Wide); LicenseKeyGroupEntity lkg = - createLicenseKeyGroup("vlm1Id", null,lkg1_id, LKG1_NAME, "LKG1 dec",LicenseKeyType.Unique, + createLicenseKeyGroup("vlm1Id", null, lkg1_id, LKG1_NAME, "LKG1 dec", + LicenseKeyType.Unique, new MultiChoiceOrOther<>(opScopeChoices, null)); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); lkg.setStartDate(LocalDate.now().format(formatter)); lkg.setExpiryDate(LocalDate.now().format(formatter)); - vendorLicenseManagerImpl.updateLicenseKeyGroup(lkg, USER1); + vendorLicenseManagerImpl.updateLicenseKeyGroup(lkg); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), VendorLicenseErrorCodes.DATE_RANGE_INVALID); @@ -371,9 +371,10 @@ public class LicenseKeyGroupTest { } @Test - public void testListlistLicenseKeyGroups(){ + public void testListlistLicenseKeyGroups() { - MultiChoiceOrOther multiChoiceOrOther = new MultiChoiceOrOther(); + MultiChoiceOrOther multiChoiceOrOther = + new MultiChoiceOrOther(); Set opScopeChoices = new HashSet<>(); opScopeChoices.add(OperationalScope.Core); opScopeChoices.add(OperationalScope.CPU); @@ -382,34 +383,25 @@ public class LicenseKeyGroupTest { multiChoiceOrOther.setOther("Other"); doReturn(Arrays.asList( - createLicenseKeyGroup(vlm1_id,VERSION01, lkg1_id, LKG1_NAME,"LKG1 dec", LicenseKeyType.Universal, + createLicenseKeyGroup(vlm1_id, VERSION01, lkg1_id, LKG1_NAME, "LKG1 dec", + LicenseKeyType.Universal, multiChoiceOrOther), - createLicenseKeyGroup(vlm1_id,VERSION01, lkg2_id, LKG2_NAME,"LKG2 dec", LicenseKeyType + createLicenseKeyGroup(vlm1_id, VERSION01, lkg2_id, LKG2_NAME, "LKG2 dec", LicenseKeyType .Universal, multiChoiceOrOther))) - .when(vendorLicenseFacade).listLicenseKeyGroups(vlm1_id, VERSION01, USER1); + .when(vendorLicenseFacade).listLicenseKeyGroups(vlm1_id, VERSION01); Collection LKGs = - vendorLicenseManagerImpl.listLicenseKeyGroups(vlm1_id, VERSION01, USER1); + vendorLicenseManagerImpl.listLicenseKeyGroups(vlm1_id, VERSION01); - verify(vendorLicenseFacade).listLicenseKeyGroups(vlm1_id, VERSION01, USER1); + verify(vendorLicenseFacade).listLicenseKeyGroups(vlm1_id, VERSION01); Assert.assertEquals(LKGs.size(), 2); LKGs.forEach(lkg -> Assert.assertTrue(lkg.getId().matches(lkg1_id + "|" + lkg2_id))); } @Test - public void testGetLicenseKeyGroup(){ - VersionInfo versionInfo = new VersionInfo(); - versionInfo.setActiveVersion(VERSION01); - versionInfo.setLockingUser(USER1); - ArrayList viewable = new ArrayList(); - viewable.add(VERSION01); - versionInfo.setViewableVersions(viewable); - versionInfo.setActiveVersion(VERSION01); - - doReturn(versionInfo).when(vendorLicenseManagerImpl).getVersionInfo(vlm1_id, - VersionableEntityAction.Read, USER1); - - MultiChoiceOrOther multiChoiceOrOther = new MultiChoiceOrOther(); + public void testGetLicenseKeyGroup() { + MultiChoiceOrOther multiChoiceOrOther = + new MultiChoiceOrOther(); Set opScopeChoices = new HashSet<>(); opScopeChoices.add(OperationalScope.Core); opScopeChoices.add(OperationalScope.CPU); @@ -417,35 +409,24 @@ public class LicenseKeyGroupTest { multiChoiceOrOther.setChoices(opScopeChoices); multiChoiceOrOther.setOther("Other"); - LicenseKeyGroupEntity lkg = createLicenseKeyGroup(vlm1_id,VERSION01, lkg1_id, LKG1_NAME, + LicenseKeyGroupEntity lkg = createLicenseKeyGroup(vlm1_id, VERSION01, lkg1_id, LKG1_NAME, "LKG1 dec", LicenseKeyType.Universal, multiChoiceOrOther); doReturn(lkg).when(licenseKeyGroupDao).get(anyObject()); - LicenseKeyGroupEntity lkgRetrived = vendorLicenseManagerImpl.getLicenseKeyGroup(lkg,USER1); + LicenseKeyGroupEntity lkgRetrived = vendorLicenseManagerImpl.getLicenseKeyGroup(lkg); verify(licenseKeyGroupDao).get(lkg); - Assert.assertEquals(lkgRetrived.getId(),lkg.getId()); - Assert.assertEquals(lkgRetrived.getVendorLicenseModelId(),lkg.getVendorLicenseModelId()); - Assert.assertEquals(lkgRetrived.getVersion(),lkg.getVersion()); + Assert.assertEquals(lkgRetrived.getId(), lkg.getId()); + Assert.assertEquals(lkgRetrived.getVendorLicenseModelId(), lkg.getVendorLicenseModelId()); + Assert.assertEquals(lkgRetrived.getVersion(), lkg.getVersion()); } @Test public void testDeleteLicenseKeyGroup() { - - VersionInfo versionInfo = new VersionInfo(); - versionInfo.setActiveVersion(VERSION01); - versionInfo.setLockingUser(USER1); - ArrayList viewable = new ArrayList(); - viewable.add(VERSION01); - versionInfo.setViewableVersions(viewable); - - doReturn(versionInfo).when(vendorLicenseManagerImpl).getVersionInfo(vlm1_id, - VersionableEntityAction.Write, USER1); - - - MultiChoiceOrOther multiChoiceOrOther = new MultiChoiceOrOther(); + MultiChoiceOrOther multiChoiceOrOther = + new MultiChoiceOrOther(); Set opScopeChoices = new HashSet<>(); opScopeChoices.add(OperationalScope.Core); opScopeChoices.add(OperationalScope.CPU); @@ -453,26 +434,26 @@ public class LicenseKeyGroupTest { multiChoiceOrOther.setChoices(opScopeChoices); multiChoiceOrOther.setOther("Other"); - LicenseKeyGroupEntity lkg = createLicenseKeyGroup(vlm1_id,VERSION01, lkg1_id, LKG1_NAME, + LicenseKeyGroupEntity lkg = createLicenseKeyGroup(vlm1_id, VERSION01, lkg1_id, LKG1_NAME, "LKG1 dec", LicenseKeyType.Universal, multiChoiceOrOther); lkg.setReferencingFeatureGroups(new HashSet<>()); doReturn(lkg).when(licenseKeyGroupDao).get(anyObject()); - doNothing().when(vendorLicenseManagerImpl).deleteChildLimits(vlm1_id,VERSION01,lkg1_id,USER1); + doNothing().when(vendorLicenseManagerImpl).deleteChildLimits(vlm1_id, VERSION01, lkg1_id); - doNothing().when(vendorLicenseManagerImpl).deleteUniqueName(anyObject(),anyObject(), - anyObject(),anyObject()); + doNothing().when(vendorLicenseManagerImpl).deleteUniqueName(anyObject(), anyObject(), + anyObject(), anyObject()); - vendorLicenseManagerImpl.deleteLicenseKeyGroup(lkg, USER1); + vendorLicenseManagerImpl.deleteLicenseKeyGroup(lkg); verify(licenseKeyGroupDao).delete(lkg); - verify(vendorLicenseFacade).updateVlmLastModificationTime(vlm1_id,VERSION01); } - public static LicenseKeyGroupEntity createLicenseKeyGroup(String vlmId, Version version,String id, + public static LicenseKeyGroupEntity createLicenseKeyGroup(String vlmId, Version version, + String id, String name, String desc, LicenseKeyType type, MultiChoiceOrOther operationalScope) { @@ -525,7 +506,7 @@ public class LicenseKeyGroupTest { vlm1Id = vendorLicenseManager.createVendorLicenseModel(VendorLicenseModelTest .createVendorLicenseModel("vendor1 name " + CommonMethods.nextUuId(), "vlm1Id dec", - "icon1"), USER1).getId(); + "icon1")1).getId(); vlm2Id = vendorLicenseManager.createVendorLicenseModel(VendorLicenseModelTest .createVendorLicenseModel("vendor2 name " + CommonMethods.nextUuId(), "vlm2 dec", "icon2"), USER1).getId(); @@ -545,7 +526,7 @@ public class LicenseKeyGroupTest { LicenseKeyGroupEntity lkg1 = createLicenseKeyGroup(vlmId, VERSION01, name, "LKG1 dec", LicenseKeyType.One_Time, new MultiChoiceOrOther<>(opScopeChoices, null)); - String lkg1Id = vendorLicenseManager.createLicenseKeyGroup(lkg1, USER1).getId(); + String lkg1Id = vendorLicenseManager.createLicenseKeyGroup(lkg11).getId(); lkg1.setId(lkg1Id); LicenseKeyGroupEntity loadedLkg1 = licenseKeyGroupDao.get(lkg1); @@ -560,7 +541,7 @@ public class LicenseKeyGroupTest { createLicenseKeyGroup(vlm1Id, VERSION01, LKG1_NAME, "LKG1 dec", LicenseKeyType.One_Time, new MultiChoiceOrOther<>(Collections.singleton(OperationalScope.Other), "other op scope")); - vendorLicenseManager.createLicenseKeyGroup(lkg1, USER1).getId(); + vendorLicenseManager.createLicenseKeyGroup(lkg11).getId(); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), UniqueValueUtil.UNIQUE_VALUE_VIOLATION); @@ -581,9 +562,9 @@ public class LicenseKeyGroupTest { lkg1.setOperationalScope(new MultiChoiceOrOther<>(opScopeChoices, "op scope1 updated")); lkg1.setDescription("LKG1 dec updated"); - vendorLicenseManager.updateLicenseKeyGroup(lkg1, USER1); + vendorLicenseManager.updateLicenseKeyGroup(lkg11); - LicenseKeyGroupEntity loadedLkg1 = vendorLicenseManager.getLicenseKeyGroup(lkg1, USER1); + LicenseKeyGroupEntity loadedLkg1 = vendorLicenseManager.getLicenseKeyGroup(lkg11); Assert.assertTrue(loadedLkg1.equals(lkg1)); } @@ -595,11 +576,11 @@ public class LicenseKeyGroupTest { LicenseKeyGroupEntity lkg2 = createLicenseKeyGroup(vlm1Id, VERSION01, "LKG2", "LKG2 dec", LicenseKeyType.Universal, new MultiChoiceOrOther<>(opScopeChoices, null)); - lkg2Id = vendorLicenseManager.createLicenseKeyGroup(lkg2, USER1).getId(); + lkg2Id = vendorLicenseManager.createLicenseKeyGroup(lkg21).getId(); lkg2.setId(lkg2Id); Collection loadedLkgs = - vendorLicenseManager.listLicenseKeyGroups(vlm1Id, null, USER1); + vendorLicenseManager.listLicenseKeyGroups(vlm1Id, null1); Assert.assertEquals(loadedLkgs.size(), 2); for (LicenseKeyGroupEntity loadedLkg : loadedLkgs) { if (lkg2Id.equals(loadedLkg.getId())) { @@ -611,7 +592,7 @@ public class LicenseKeyGroupTest { @Test(dependsOnMethods = {"listTest"}) public void deleteTest() { vendorLicenseManager - .deleteLicenseKeyGroup(new LicenseKeyGroupEntity(vlm1Id, VERSION01, lkg1Id), USER1); + .deleteLicenseKeyGroup(new LicenseKeyGroupEntity(vlm1Id, VERSION01, lkg1Id)1); LicenseKeyGroupEntity loadedLkg1 = licenseKeyGroupDao.get(new LicenseKeyGroupEntity(vlm1Id, VERSION01, lkg1Id)); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseModelTest.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseModelTest.java index 195fa5d4da..d1df147a60 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseModelTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseModelTest.java @@ -1,12 +1,12 @@ package org.openecomp.sdc.vendorlicense.impl; -import org.junit.rules.ExpectedException; -import org.openecomp.core.util.UniqueValueUtil; -import org.openecomp.sdc.activityLog.ActivityLogManager; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.common.errors.ErrorCategory; -import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.vendorlicense.VendorLicenseConstants; import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDao; import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDao; @@ -14,50 +14,17 @@ import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDao; import org.openecomp.sdc.vendorlicense.dao.LicenseKeyGroupDao; import org.openecomp.sdc.vendorlicense.dao.LimitDao; import org.openecomp.sdc.vendorlicense.dao.VendorLicenseModelDao; -import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; -import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseTerm; import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; -import org.openecomp.sdc.vendorlicense.types.VersionedVendorLicenseModel; -import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; -import org.openecomp.sdc.vendorsoftwareproduct.types.VersionedVendorSoftwareProductInfo; import org.openecomp.sdc.versioning.VersioningManager; -import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionStatus; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; -import org.testng.annotations.BeforeMethod; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; -import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.util.ArrayList; -import java.util.Arrays; -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 static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; -import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE; /** @@ -93,9 +60,6 @@ public class VendorLicenseModelTest { private LicenseKeyGroupDao licenseKeyGroupDaoMcok; @Mock private LimitDao limitDaoMcok; - @Mock - private ActivityLogManager activityLogManagerMcok; - @Spy @InjectMocks @@ -112,159 +76,19 @@ public class VendorLicenseModelTest { } @Test - public void testCheckout() { - - doReturn(VERSION01).when(versioningManagerMcok) - .checkout(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vlm1_id, USER1); - - vendorLicenseManager.checkout(vlm1_id, USER1); - - Assert.assertEquals(VERSION01.getStatus(), VersionStatus.Locked); - verify(vendorLicenseFacadeMcok).updateVlmLastModificationTime(vlm1_id, VERSION01); - - verify(versioningManagerMcok) - .checkout(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vlm1_id, USER1); - - verify(activityLogManagerMcok).addActionLog(activityLogEntityArg.capture(), eq(USER1)); - ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue(); - Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION01.getMajor() + 1)); - Assert.assertTrue(activityLogEntity.isSuccess()); - } - - @Test - public void testUndoCheckout() { - Version existingVersion = new Version(0, 2); - doReturn(existingVersion).when(versioningManagerMcok).undoCheckout( - VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vlm1_id, USER1); - - vendorLicenseManager.undoCheckout(vlm1_id, USER1); - - verify(vendorLicenseFacadeMcok).updateVlmLastModificationTime(vlm1_id, existingVersion); - } - - @Test - public void testCheckin() { - - doReturn(VERSION10).when(vendorLicenseFacadeMcok).checkin(vlm1_id, USER1); - - vendorLicenseManager.checkin(vlm1_id, USER1); - verify(activityLogManagerMcok).addActionLog(activityLogEntityArg.capture(), eq(USER1)); - ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue(); - Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION10.getMajor() + 1)); - verify(vendorLicenseFacadeMcok).checkin(vlm1_id, USER1); - - } - - @Test - public void testSubmit() { - - doReturn(VERSION10).when(vendorLicenseFacadeMcok).submit(vlm1_id, USER1); - - vendorLicenseManager.submit(vlm1_id, USER1); - verify(activityLogManagerMcok).addActionLog(activityLogEntityArg.capture(), eq(USER1)); - ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue(); - Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION10.getMajor())); - verify(vendorLicenseFacadeMcok).submit(vlm1_id, USER1); - - } - - @Test - public void testListWhenNone() { - doReturn(new HashMap<>()).when(versioningManagerMcok).listEntitiesVersionInfo - (VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, USER1, VersionableEntityAction.Read); - Collection vlms = vendorLicenseManager.listVendorLicenseModels - (null, USER1); - Assert.assertEquals(vlms.size(), 0); - } - - @Test - public void testList() { - - Map vlmsTobeReturned = new HashMap<>(); - - VersionInfo versionInfo1 = new VersionInfo(); - versionInfo1.setActiveVersion(VERSION01); - vlmsTobeReturned.put(vlm1_id, versionInfo1); - - VersionInfo versionInfo2 = new VersionInfo(); - versionInfo2.setActiveVersion(VERSION10); - vlmsTobeReturned.put(vlm2_id, versionInfo2); - - doReturn(vlmsTobeReturned).when(versioningManagerMcok).listEntitiesVersionInfo - (VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, USER1, VersionableEntityAction.Read); - - VendorLicenseModelEntity vlm1 = new VendorLicenseModelEntity(vlm1_id, VERSION01); - vlm1.setWritetimeMicroSeconds(8L); - doReturn(vlm1).when(vendorLicenseModelDaoMcok).get(any(VendorLicenseModelEntity.class)); - - Collection vlms = vendorLicenseManager.listVendorLicenseModels - (null, USER1); - Assert.assertEquals(vlms.size(), 2); - } - - @Test - public void testListFinalsWhenNone() { - - Map vspsTobeReturned = new HashMap<>(); - - VersionInfo versionInfo1 = new VersionInfo(); - versionInfo1.setActiveVersion(VERSION01); - vspsTobeReturned.put(vlm1_id, versionInfo1); - - VersionInfo versionInfo2 = new VersionInfo(); - versionInfo2.setActiveVersion(VERSION10); - vspsTobeReturned.put(vlm2_id, versionInfo2); - - doReturn(vspsTobeReturned).when(versioningManagerMcok).listEntitiesVersionInfo - (VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, USER1, VersionableEntityAction.Read); - - Collection vlms = vendorLicenseManager.listVendorLicenseModels - (VersionStatus.Final.name(), USER1); - Assert.assertEquals(vlms.size(), 0); - } - - @Test - public void testListFinals() { - Map vlmsTobeReturned = new HashMap<>(); - - VersionInfo versionInfo1 = new VersionInfo(); - versionInfo1.setActiveVersion(VERSION01); - vlmsTobeReturned.put(vlm1_id, versionInfo1); - - VersionInfo versionInfo2 = new VersionInfo(); - - versionInfo2.setActiveVersion(new Version(1, 3)); - versionInfo2.setLatestFinalVersion(VERSION10); - vlmsTobeReturned.put(vlm2_id, versionInfo2); - - doReturn(vlmsTobeReturned).when(versioningManagerMcok).listEntitiesVersionInfo - (VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, USER1, VersionableEntityAction.Read); - - VendorLicenseModelEntity vlm1 = new VendorLicenseModelEntity(vlm1_id, VERSION01); - vlm1.setWritetimeMicroSeconds(8L); - doReturn(vlm1).when(vendorLicenseModelDaoMcok).get(any(VendorLicenseModelEntity.class)); - - Collection vlms = vendorLicenseManager.listVendorLicenseModels - (VersionStatus.Final.name(), USER1); - - Assert.assertEquals(vlms.size(), 1); + public void testValidate() { + // TODO: 8/13/2017 + vendorLicenseManager.validate(vlm1_id, null); + verify(vendorLicenseFacadeMcok).validate(vlm1_id, null); } @Test public void testCreate() { - VendorLicenseModelEntity vlmEntity = new VendorLicenseModelEntity(vlm1_id, VERSION01); - doReturn(vlmEntity).when(vendorLicenseFacadeMcok).createVendorLicenseModel(vlmEntity, USER1); - - vendorLicenseManager.createVendorLicenseModel(vlmEntity, USER1); - - verify(vendorLicenseFacadeMcok).createVendorLicenseModel(vlmEntity, USER1); - verify(activityLogManagerMcok).addActionLog(activityLogEntityArg.capture(), eq(USER1)); - ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue(); - Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION01.getMajor() + 1)); - Assert.assertTrue(activityLogEntity.isSuccess()); + vendorLicenseManager.createVendorLicenseModel(vlmEntity); + verify(vendorLicenseModelDaoMcok).create(vlmEntity); } @Test @@ -277,14 +101,6 @@ public class VendorLicenseModelTest { existingVlm.setVendorName("VLM1"); existingVlm.setDescription("decription"); - VersionInfo versionInfo = new VersionInfo(); - versionInfo.setActiveVersion(VERSION01); - - doReturn(versionInfo).when(vendorLicenseManager).getVersionInfo(existingVlm.getId(), - VersionableEntityAction.Write, USER1); - - doReturn(VERSION01).when(vendorLicenseManager).resloveVersion(vlm1_id,null, versionInfo, USER1); - doReturn("VLM1").when(vendorLicenseModelDaoMcok).get(existingVlm); VendorLicenseModelEntity updatedVlm = new VendorLicenseModelEntity(); @@ -302,21 +118,20 @@ public class VendorLicenseModelTest { doReturn(existingVlm).when(vendorLicenseModelDaoMcok).get(any(VendorLicenseModelEntity.class)); - vendorLicenseManager.updateVendorLicenseModel(updatedVlm, USER1); + vendorLicenseManager.updateVendorLicenseModel(updatedVlm); verify(vendorLicenseModelDaoMcok).update(updatedVlm); - verify(vendorLicenseFacadeMcok).updateVlmLastModificationTime(vlm1_id, VERSION01); } @Test - public void testGetVendorLicenseModel(){ - vendorLicenseManager.getVendorLicenseModel(vlm1_id,VERSION01,USER1); - verify(vendorLicenseFacadeMcok).getVendorLicenseModel(vlm1_id,VERSION01,USER1); + public void testGetVendorLicenseModel() { + vendorLicenseManager.getVendorLicenseModel(vlm1_id, VERSION01); + verify(vendorLicenseFacadeMcok).getVendorLicenseModel(vlm1_id, VERSION01); } @Test(expectedExceptions = UnsupportedOperationException.class) public void testDeleteVLMUnsupportedOperation() { - vendorLicenseManager.deleteVendorLicenseModel(vlm1_id, USER1); + vendorLicenseManager.deleteVendorLicenseModel(vlm1_id, null); // TODO: 8/13/2017 } @@ -324,7 +139,7 @@ public class VendorLicenseModelTest { // public void testGetNonExistingVersion_negative() { // Version notExistversion = new Version(43, 8); // doReturn(null).when(vspInfoDaoMock).get(any(VspDetails.class)); -// vendorSoftwareProductManager.getVsp(VSP_ID, notExistversion, USER1); +// vendorSoftwareProductManager.getVsp(VSP_ID, notExistversion); // } } \ No newline at end of file diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/VendorLicenseArtifactsServiceTest.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/VendorLicenseArtifactsServiceTest.java index ec50c96f74..c20d96ac36 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/VendorLicenseArtifactsServiceTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/test/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/VendorLicenseArtifactsServiceTest.java @@ -20,22 +20,8 @@ package org.openecomp.sdc.vendorlicense.licenseartifacts.impl; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.sdc.vendorlicense.ArtifactTestUtils; -import org.openecomp.sdc.vendorlicense.VendorLicenseConstants; -import org.openecomp.sdc.vendorlicense.dao.types.EntitlementMetric; -import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; -import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; public class VendorLicenseArtifactsServiceTest extends ArtifactTestUtils { 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 a651b0bb12..869628e6f5 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 @@ -4,12 +4,17 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModel import org.openecomp.sdc.versioning.dao.types.Version; import java.util.Collection; -import java.util.List; public interface ComponentDependencyModelManager { - void createComponentDependencyModel(List entities, String - vspId, Version version, String user); + Collection list(String vspId, Version version); - Collection list(String vspId, Version version, String user); + ComponentDependencyModelEntity createComponentDependency(ComponentDependencyModelEntity entity, + String vspId, Version version); + + void delete(String vspId, Version version, String dependencyId); + + void update(ComponentDependencyModelEntity entity); + + 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/ComponentManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentManager.java index b895f5595f..413529882d 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 @@ -31,24 +31,23 @@ import java.util.Collection; public interface ComponentManager { - Collection listComponents(String vspId, Version version, String user); + Collection listComponents(String vspId, Version version); - void deleteComponents(String vspId, Version version, String user); + void deleteComponents(String vspId, Version version); - ComponentEntity createComponent(ComponentEntity componentEntity, String user); + ComponentEntity createComponent(ComponentEntity componentEntity); - CompositionEntityValidationData updateComponent(ComponentEntity componentEntity, String user); + CompositionEntityValidationData updateComponent(ComponentEntity componentEntity); CompositionEntityResponse getComponent(String vspId, Version version, - String componentId, String user); + String componentId); - void deleteComponent(String vspId, Version version, String componentId, String user); + void deleteComponent(String vspId, Version version, String componentId); - QuestionnaireResponse getQuestionnaire(String vspId, Version version, String componentId, - String user); + QuestionnaireResponse getQuestionnaire(String vspId, Version version, String componentId); void updateQuestionnaire(String vspId, Version version, String componentId, - String questionnaireData, String user); + String questionnaireData); - void validateComponentExistence(String vspId, Version version, String componentId, String user); + 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/ComputeManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComputeManager.java index 65bceb9864..7ddd4e20c8 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 @@ -12,23 +12,20 @@ import java.util.Collection; public interface ComputeManager { - Collection listCompute(String vspId, Version version, String - componentId, String user); + Collection listComputes(String vspId, Version version, String componentId); - ComputeEntity createCompute(ComputeEntity compute, String user); + ComputeEntity createCompute(ComputeEntity compute); - CompositionEntityResponse getCompute(String vspId, Version version, String - componentId, String computeFlavorId, String user); + CompositionEntityResponse getCompute(String vspId, Version version, + String componentId, String computeFlavorId); - QuestionnaireResponse getComputeQuestionnaire(String vspId, Version version, String - componentId, String computeFlavorId, String user); + QuestionnaireResponse getComputeQuestionnaire(String vspId, Version version, String componentId, + String computeFlavorId); - void updateComputeQuestionnaire(String vspId, Version version, String componentId, String - computeId, String - questionnaireData, String user); + void updateComputeQuestionnaire(String vspId, Version version, String componentId, + String computeId, String questionnaireData); - CompositionEntityValidationData updateCompute(ComputeEntity compute, String user); + CompositionEntityValidationData updateCompute(ComputeEntity compute); - void deleteCompute(String vspId, Version version,String componentId, String computeFlavorId, - String user); + 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/DeploymentFlavorManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/DeploymentFlavorManager.java index 51ba2f4d40..88d399aa5c 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 @@ -12,23 +12,19 @@ import java.util.Collection; public interface DeploymentFlavorManager { - DeploymentFlavorEntity createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity, - String user); + DeploymentFlavorEntity createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity); - Collection listDeploymentFlavors(String vspId, Version version, - String user); + Collection listDeploymentFlavors(String vspId, Version version); CompositionEntityResponse getDeploymentFlavor(String vspId, Version version, - String deploymentFlavorId, - String user); + String deploymentFlavorId); - CompositionEntityResponse getDeploymentFlavorSchema(String vspId, Version - version, String user); + CompositionEntityResponse getDeploymentFlavorSchema(String vspId, + Version version); - void deleteDeploymentFlavor(String vspId, Version version, String deploymentFlavorId, String - user); + void deleteDeploymentFlavor(String vspId, Version version, String deploymentFlavorId); - CompositionEntityValidationData updateDeploymentFlavor(DeploymentFlavorEntity - deploymentFlavorEntity, String user); + CompositionEntityValidationData updateDeploymentFlavor( + DeploymentFlavorEntity deploymentFlavorEntity); } 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 6bbfc0b69a..1a53221951 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 @@ -10,24 +10,22 @@ import org.openecomp.sdc.versioning.dao.types.Version; import java.util.Collection; public interface ImageManager { - ImageEntity createImage(ImageEntity imageEntity, String user); + ImageEntity createImage(ImageEntity imageEntity); - CompositionEntityResponse getImageSchema(String vspId, String user); + CompositionEntityResponse getImageSchema(String vspId); - Collection listImages(String vspId, Version version, String componentId, - String user); + Collection listImages(String vspId, Version version, String componentId); CompositionEntityResponse getImage(String vspId, Version version, String componentId, - String imageId, String user); + String imageId); - QuestionnaireResponse getImageQuestionnaire(String vspId, Version version, String - componentId, String imageId, String user); + QuestionnaireResponse getImageQuestionnaire(String vspId, Version version, String componentId, + String imageId); - void deleteImage(String vspId, Version version, String componentId, String imageId, String user); + void deleteImage(String vspId, Version version, String componentId, String imageId); - CompositionEntityValidationData updateImage(ImageEntity imageEntity, String user); + CompositionEntityValidationData updateImage(ImageEntity imageEntity); void updateImageQuestionnaire(String vspId, Version version, String componentId, String imageId, - String - questionnaireData, String user); + String questionnaireData); } 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 c9a5206383..621374ad3c 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 @@ -6,7 +6,7 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface ManualVspToscaManager { - public VspModelInfo gatherVspInformation(String vspId, Version version, String user); + VspModelInfo gatherVspInformation(String vspId, Version version); - public 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 f5e34a01be..36f06507dc 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 @@ -28,11 +28,10 @@ import java.io.InputStream; public interface MonitoringUploadsManager { void delete(String vspId, Version version, String componentId, - MonitoringUploadType monitoringUploadType, String user); + MonitoringUploadType monitoringUploadType); void upload(InputStream object, String filename, String vspId, Version version, - String componentId, MonitoringUploadType monitoringUploadType, String user); + String componentId, MonitoringUploadType monitoringUploadType); - MonitoringUploadStatus listFilenames(String vspId, Version version, String componentId, - String user); + 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/NetworkManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NetworkManager.java index b647735188..fa740690b7 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 @@ -29,14 +29,13 @@ import org.openecomp.sdc.versioning.dao.types.Version; import java.util.Collection; public interface NetworkManager { - Collection listNetworks(String vspId, Version version, String user); + Collection listNetworks(String vspId, Version version); - NetworkEntity createNetwork(NetworkEntity network, String user); + NetworkEntity createNetwork(NetworkEntity network); - CompositionEntityValidationData updateNetwork(NetworkEntity networkEntity, String user); + CompositionEntityValidationData updateNetwork(NetworkEntity networkEntity); - CompositionEntityResponse getNetwork(String vspId, Version version, String networkId, - String user); + CompositionEntityResponse getNetwork(String vspId, Version version, String networkId); - void deleteNetwork(String vspId, Version version, String networkId, String user); + 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/NicManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NicManager.java index 466583edfd..b055d97ef3 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 @@ -31,20 +31,20 @@ import java.util.Collection; public interface NicManager { - Collection listNics(String vspId, Version version, String componentId, String user); + Collection listNics(String vspId, Version version, String componentId); - NicEntity createNic(NicEntity nic, String user); + NicEntity createNic(NicEntity nic); - CompositionEntityValidationData updateNic(NicEntity nicEntity, String user); + CompositionEntityValidationData updateNic(NicEntity nicEntity); CompositionEntityResponse getNic(String vspId, Version version, String componentId, - String nicId, String user); + String nicId); - void deleteNic(String vspId, Version version, String componentId, String nicId, String user); + void deleteNic(String vspId, Version version, String componentId, String nicId); QuestionnaireResponse getNicQuestionnaire(String vspId, Version version, String componentId, - String nicId, String user); + String nicId); void updateNicQuestionnaire(String vspId, Version version, String componentId, String nicId, - String questionnaireData, String user); + String questionnaireData); } 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 e2ef86149b..84318dbdd8 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 @@ -21,6 +21,7 @@ package org.openecomp.sdc.vendorsoftwareproduct; import org.apache.commons.lang3.tuple.Pair; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse; @@ -33,14 +34,16 @@ import java.util.Optional; public interface OrchestrationTemplateCandidateManager { UploadFileResponse upload(String vspId, Version version, InputStream heatFileToUpload, - String user, String filePrefix, String networkPackageName); + String fileSuffix, String networkPackageName); - OrchestrationTemplateActionResponse process(String vspId, Version version, String user); + OrchestrationTemplateActionResponse process(String vspId, Version version); - Optional getFilesDataStructure(String vspId, Version version, String user); + Optional getFilesDataStructure(String vspId, Version version); - ValidationResponse updateFilesDataStructure(String vspId, Version version, String user, + ValidationResponse updateFilesDataStructure(String vspId, Version version, FilesDataStructure fileDataStructure); - Optional> get(String vspId, Version version, String user) throws IOException; + Optional> get(String vspId, Version version) throws IOException; + + OrchestrationTemplateCandidateData getInfo(String vspId, Version version); } 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 afe88d2053..979eea0fb8 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 @@ -28,27 +28,22 @@ import java.io.InputStream; import java.util.Collection; public interface ProcessManager { - Collection listProcesses(String vspId, Version version, String componentId, - String user); + Collection listProcesses(String vspId, Version version, String componentId); - void deleteProcesses(String vspId, Version version, String componentId, String user); + void deleteProcesses(String vspId, Version version, String componentId); - ProcessEntity createProcess(ProcessEntity processEntity, String user); + ProcessEntity createProcess(ProcessEntity processEntity); - ProcessEntity getProcess(String vspId, Version version, String componentId, String processId, - String user); + ProcessEntity getProcess(String vspId, Version version, String componentId, String processId); - void updateProcess(ProcessEntity processEntity, String user); + void updateProcess(ProcessEntity processEntity); - void deleteProcess(String vspId, Version version, String componentId, String processId, - String user); + void deleteProcess(String vspId, Version version, String componentId, String processId); - File getProcessArtifact(String vspId, Version version, String componentId, String processId, - String user); + File getProcessArtifact(String vspId, Version version, String componentId, String processId); - void deleteProcessArtifact(String vspId, Version version, String componentId, String processId, - String user); + void deleteProcessArtifact(String vspId, Version version, String componentId, String processId); void uploadProcessArtifact(InputStream uploadFile, String fileName, String vspId, - Version version, String componentId, String processId, String user); + 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/VendorSoftwareProductManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VendorSoftwareProductManager.java index 0adca1c695..2e38122856 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 @@ -20,65 +20,55 @@ package org.openecomp.sdc.vendorsoftwareproduct; +import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; +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.types.QuestionnaireResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse; -import org.openecomp.sdc.vendorsoftwareproduct.types.VersionedVendorSoftwareProductInfo; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.types.VersionInfo; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.List; +import java.util.Map; public interface VendorSoftwareProductManager { - Version checkout(String vendorSoftwareProductId, String user); + VspDetails createVsp(VspDetails vspDetails); - Version undoCheckout(String vendorSoftwareProductId, String user); + void updateVsp(VspDetails vspDetails); - Version checkin(String vendorSoftwareProductId, String user); + VspDetails getVsp(String vspId, Version version); - ValidationResponse submit(String vendorSoftwareProductId, String user) throws IOException; + void deleteVsp(String vspIdToDelete); + ValidationResponse validate(String vspId, Version version) throws IOException; - List listVsps(String versionFilter, String user); + Map> compile(String vspId, Version version); - VspDetails createVsp(VspDetails vspDetails, String user); - void updateVsp(VspDetails vspDetails, String user); + QuestionnaireResponse getVspQuestionnaire(String vspId, Version version); - VspDetails getVsp(String vspId, Version version, String user); + void updateVspQuestionnaire(String vspId, Version version, String questionnaireData); - Version callAutoHeal(String vspId, VersionInfo versionInfo, - VspDetails vendorSoftwareProductInfo, String user) throws Exception; - void deleteVsp(String vspIdToDelete, String user); + byte[] getOrchestrationTemplateFile(String vspId, Version version); - QuestionnaireResponse getVspQuestionnaire(String vspId, Version version, String user); + OrchestrationTemplateEntity getOrchestrationTemplateInfo(String vspId, Version version); - void updateVspQuestionnaire(String vspId, Version version, String questionnaireData, String user); - - byte[] getOrchestrationTemplateFile(String vspId, Version version, String user); - - PackageInfo createPackage(String vspId, Version version, String user) throws IOException; + PackageInfo createPackage(String vspId, Version version) throws IOException; List listPackages(String category, String subCategory); - File getTranslatedFile(String vspId, Version version, String user); - - void heal(String vspId, Version version, String user); - File getInformationArtifact(String vspId, Version version, String user); + File getTranslatedFile(String vspId, Version version); - String fetchValidationVsp(String user); + File getInformationArtifact(String vspId, Version version); - Collection getComputeByVsp(String vspId, Version version, String user); - Version healAndAdvanceFinalVersion(String vspId, VspDetails vendorSoftwareProductInfo, - String user) throws IOException; + Collection getComputeByVsp(String vspId, Version version); } 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 78605c86fc..53ad74b772 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 @@ -1,18 +1,14 @@ 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.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; + public class ComponentDependencyModelErrorBuilder { private static final String CYCLIC_DEPENDENCY_COMPONENT_MSG = "Cyclic dependency exists between" 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 b242b7169c..5d58f5c35b 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 @@ -2,41 +2,16 @@ 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; public class DuplicateComputeInComponentErrorBuilder { - - private static final String DUPLICATE_COMPUTE_NAME_NOT_ALLOWED_MSG = - "Invalid request, Compute with name %s already exists for component with ID %s."; - private static final String COMPUTE_HEAT_READONLY_ATTR_MSG = "Update of attribute %s not allowed " - + "for VSP onboarded via HEAT."; - private static final String COMPUTE_MANUAL_READONLY_ATTR_MSG = "Update of attribute %s not allowed " - + "for VSP onboarded manually."; - + 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 DuplicateComputeInComponentErrorBuilder(String computeName, String componentId ){ - builder.withId(VendorSoftwareProductErrorCodes.DUPLICATE_COMPUTE_NAME_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(DUPLICATE_COMPUTE_NAME_NOT_ALLOWED_MSG,computeName, - componentId)); - } - - /** - * Gets duplicate compute name error builder. - * - * @return the duplicate compute name error builder - */ - public static ErrorCode getDuplicateComputeNameErrorBuilder(String computeName, String componenetId) { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(VendorSoftwareProductErrorCodes.DUPLICATE_COMPUTE_NAME_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(DUPLICATE_COMPUTE_NAME_NOT_ALLOWED_MSG, computeName, componenetId )); - return builder.build(); - } - public static ErrorCode getComputeHeatReadOnlyErrorBuilder(String name) { ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); builder.withId(UPDATE_COMPUTE_NOT_ALLOWED); 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 9ac6e1b1bb..2d22d01774 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 @@ -3,7 +3,11 @@ 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.*; +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; /** * The Image error builder. 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 5fc29d5a4f..eed56e1a1a 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 @@ -28,8 +28,7 @@ import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProdu 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"; + "Monitoring file uploaded for vendor software product with Id %s and version %s is invalid: %s"; /** @@ -44,7 +43,7 @@ public class MonitoringUploadErrorBuilder extends BaseErrorBuilder { getErrorCodeBuilder().withId(MONITORING_UPLOAD_INVALID); getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); getErrorCodeBuilder().withMessage(String.format(UPLOAD_INVALID_DETAILED_MSG, - vendorSoftwareProductId, version == null ? null : version.toString(), error)); + vendorSoftwareProductId, version == null ? null : version.getId(), error)); } /** 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 0850d2e704..2acfde48ff 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 @@ -1,11 +1,11 @@ package org.openecomp.sdc.vendorsoftwareproduct.errors; -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; - 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."; 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 7801df8fd7..1b6896211b 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 @@ -1,5 +1,8 @@ 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.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; @@ -7,9 +10,6 @@ import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProdu 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; - public class NotSupportedHeatOnboardMethodErrorBuilder { private static final String ADD_NIC_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG = "NIC cannot be added for VSPs onboarded with HEAT."; 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 8aad900102..49785a38f8 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 @@ -1,36 +1,18 @@ package org.openecomp.sdc.vendorsoftwareproduct.errors; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes - .VSP_INVALID_ONBOARDING_METHOD; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes - .VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED; - 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_ONBOARD_METHOD_UPDATE_NOT_ALLOWED_MSG = - "onboardingMethod update is not allowed."; private static final String VSP_INVALID_ONBOARDING_METHOD_MSG = "The onboardingMethod value doesn't meet the expected attribute value."; - /** - * Gets onboarding update error. - * - * @return the onboarding update error - */ - public static ErrorCode getOnboardingUpdateError() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED_MSG)); - return builder.build(); - } - /** * Get invalid onboarding method error builder error code. * @@ -40,7 +22,7 @@ public class OnboardingMethodErrorBuilder { ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); builder.withId(VSP_INVALID_ONBOARDING_METHOD); builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(VSP_INVALID_ONBOARDING_METHOD_MSG)); + 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/TranslationFileCreationErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/TranslationFileCreationErrorBuilder.java index 1ec3af397f..fd8acd1497 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 @@ -20,12 +20,12 @@ 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 " 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 4a84c83338..4fc0b6e6f7 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 @@ -28,7 +28,7 @@ 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 " + + 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 final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); @@ -39,13 +39,13 @@ public class VendorSoftwareProductInvalidErrorBuilder { * @param version the version */ public static ErrorCode VendorSoftwareProductMissingServiceModelErrorBuilder(String - vendorSoftwareProductId, - Version version) { + 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.toString())); + .withMessage(String.format(VSP_INVALID_MSG, vendorSoftwareProductId, version.getId())); return builder.build(); } 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 b4513dec79..1f9a35cb2c 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 @@ -3,13 +3,16 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.sdc.vendorsoftwareproduct.ComponentDependencyModelManager; import org.openecomp.sdc.vendorsoftwareproduct.ComponentDependencyModelManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.ComponentManagerFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDaoFactory; public class ComponentDependencyModelManagerFactoryImpl extends ComponentDependencyModelManagerFactory { + private static final ComponentDependencyModelManager INSTANCE = - new ComponentDependencyModelManagerImpl(VendorSoftwareProductDaoFactory.getInstance() - .createInterface(), ComponentManagerFactory.getInstance().createInterface()); + new ComponentDependencyModelManagerImpl( + ComponentManagerFactory.getInstance().createInterface(), + ComponentDependencyModelDaoFactory.getInstance().createInterface() + ); @Override public ComponentDependencyModelManager createInterface() { 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 5dc1446601..17d1833af6 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 @@ -1,6 +1,7 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.apache.commons.lang3.StringUtils; +import org.openecomp.core.utilities.CommonMethods; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.datatypes.error.ErrorLevel; @@ -12,72 +13,114 @@ import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; import org.openecomp.sdc.vendorsoftwareproduct.ComponentDependencyModelManager; import org.openecomp.sdc.vendorsoftwareproduct.ComponentManager; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.errors.ComponentDependencyModelErrorBuilder; +import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; import java.util.Collection; -import java.util.List; public class ComponentDependencyModelManagerImpl implements ComponentDependencyModelManager { - private VendorSoftwareProductDao vendorSoftwareProductDao; private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); protected static final Logger logger = LoggerFactory.getLogger(ComponentDependencyModelManagerImpl.class); private ComponentManager componentManager; + private ComponentDependencyModelDao componentDependencyModelDao; - public ComponentDependencyModelManagerImpl(VendorSoftwareProductDao vendorSoftwareProductDao, ComponentManager componentManager) { - this.vendorSoftwareProductDao = vendorSoftwareProductDao; + public ComponentDependencyModelManagerImpl( + ComponentManager componentManager, ComponentDependencyModelDao componentDependencyModelDao) { this.componentManager = componentManager; + this.componentDependencyModelDao = componentDependencyModelDao; + } + + private void raiseException(ErrorCode errorCode) { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, + LoggerTragetServiceName.CREATE_COMPONENT_DEPENDENCY_MODEL, ErrorLevel.ERROR.name(), + errorCode.id(), errorCode.message()); + throw new CoreException(errorCode); } @Override - public void createComponentDependencyModel(List entities, - String vspId, Version version, String user) { - - mdcDataDebugMessage.debugEntryMessage("createComponentDependencyModel"); - for(ComponentDependencyModelEntity entity : entities) { - if (!StringUtils.isEmpty(entity.getSourceComponentId())) { - componentManager.validateComponentExistence(entity.getVspId(), entity.getVersion(), - entity.getSourceComponentId(), user); - if (entity.getSourceComponentId().equals(entity.getTargetComponentId())) { - ErrorCode errorCode = - ComponentDependencyModelErrorBuilder.getSourceTargetComponentEqualErrorBuilder(); - raiseException(errorCode); - } - } else { - ErrorCode errorCode = ComponentDependencyModelErrorBuilder - .getNoSourceComponentErrorBuilder(); - raiseException(errorCode); - } + public Collection list(String vspId, Version version) { + + mdcDataDebugMessage.debugExitMessage("VSP id, version", vspId, version.toString()); + + return componentDependencyModelDao + .list(new ComponentDependencyModelEntity(vspId, version, null)); + } + + @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(), user); + 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(); + raiseException(errorCode); } + } else { + ErrorCode errorCode = ComponentDependencyModelErrorBuilder + .getNoSourceComponentErrorBuilder(); + raiseException(errorCode); } - vendorSoftwareProductDao.createComponentDependencyModel(entities, vspId, version ); - - mdcDataDebugMessage.debugExitMessage("createComponentDependencyModel"); + if (!StringUtils.isEmpty(entity.getTargetComponentId())) { + componentManager.validateComponentExistence(entity.getVspId(), entity.getVersion(), + entity.getTargetComponentId()); + } } - private void raiseException(ErrorCode errorCode) { - MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, - LoggerTragetServiceName.CREATE_COMPONENT_DEPENDENCY_MODEL, ErrorLevel.ERROR.name(), - errorCode.id(), errorCode.message()); - throw new CoreException(errorCode); + @Override + public void delete(String vspId, Version version, String dependencyId) { + mdcDataDebugMessage.debugEntryMessage("VSP id, dependencyId", vspId, dependencyId); + ComponentDependencyModelEntity componentDependencyEntity = getComponentDependency(vspId, + version, dependencyId); + if (componentDependencyEntity != null) { + componentDependencyModelDao.delete(componentDependencyEntity); + } + + mdcDataDebugMessage.debugExitMessage("VSP id, dependencyId", vspId, dependencyId); } @Override - public Collection list(String vspId, Version version, String - user) { + public void update(ComponentDependencyModelEntity entity) { + mdcDataDebugMessage.debugEntryMessage("VSP id, dependencyId", entity.getVspId(), + entity.getId()); + ComponentDependencyModelEntity componentDependencyEntity = getComponentDependency( + entity.getVspId(), entity.getVersion(), entity.getId()); + validateComponentDependency(entity); + componentDependencyModelDao.update(entity); + } - mdcDataDebugMessage.debugExitMessage("VSP id, version", vspId, version.toString()); + @Override + public ComponentDependencyModelEntity get(String vspId, Version version, String dependencyId) { + mdcDataDebugMessage.debugEntryMessage("VSP id, dependencyId", vspId, dependencyId); + ComponentDependencyModelEntity componentDependency = + getComponentDependency(vspId, version, dependencyId); + return componentDependency; + } - return vendorSoftwareProductDao.listComponentDependencies(vspId, version); + 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/ComponentManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentManagerImpl.java index 72a38bbb5d..1834bf05d6 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 @@ -67,10 +67,10 @@ public class ComponentManagerImpl implements ComponentManager { private NicManager nicManager; private VendorSoftwareProductInfoDao vspInfoDao; - public ComponentManagerImpl( - ComponentDao componentDao, - CompositionEntityDataManager compositionEntityDataManager, - NicManager nicManager, VendorSoftwareProductInfoDao vspInfoDao) { + public ComponentManagerImpl(ComponentDao componentDao, + CompositionEntityDataManager compositionEntityDataManager, + NicManager nicManager, + VendorSoftwareProductInfoDao vspInfoDao) { this.componentDao = componentDao; this.compositionEntityDataManager = compositionEntityDataManager; this.nicManager = nicManager; @@ -78,14 +78,14 @@ public class ComponentManagerImpl implements ComponentManager { } @Override - public Collection listComponents(String vspId, Version version, String user) { + public Collection listComponents(String vspId, Version version) { mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); mdcDataDebugMessage.debugExitMessage("VSP id", vspId); return componentDao.list(new ComponentEntity(vspId, version, null)); } @Override - public void deleteComponents(String vspId, Version version, String user) { + public void deleteComponents(String vspId, Version version) { mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); if (!vspInfoDao.isManual(vspId, version)) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, @@ -95,12 +95,11 @@ public class ComponentManagerImpl implements ComponentManager { new CompositionEditNotAllowedErrorBuilder(vspId, version).build()); } - //componentDao.updateVspLatestModificationTime(vspId, version); mdcDataDebugMessage.debugExitMessage("VSP id", vspId); } /*@Override - public ComponentEntity createComponent(ComponentEntity component, String user) { + public ComponentEntity createComponent(ComponentEntity component) { mdcDataDebugMessage.debugEntryMessage("VSP id", component.getId()); if (!isManual(component.getVspId(), component.getVersion())) { @@ -112,24 +111,18 @@ public class ComponentManagerImpl implements ComponentManager { .build()); } - //componentDao.updateVspLatestModificationTime(component.getVspId(), component.getVersion()); mdcDataDebugMessage.debugExitMessage("VSP id", component.getId()); return null; }*/ @Override - public ComponentEntity createComponent(ComponentEntity component, String user) { + public ComponentEntity createComponent(ComponentEntity component) { mdcDataDebugMessage.debugEntryMessage("VSP id", component.getId()); - /*Version activeVersion = - getVersionInfo(component.getVspId(), VersionableEntityAction.Write, user) - .getActiveVersion(); - component.setVersion(activeVersion);*/ final String VFC_ADD_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG = "VFCs cannot be added for VSPs onboarded with HEAT."; - ComponentEntity createdComponent = null; - + ComponentEntity createdComponent; if (!vspInfoDao.isManual(component.getVspId(), component.getVersion())) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.CREATE_COMPONENT, ErrorLevel.ERROR.name(), @@ -141,7 +134,7 @@ public class ComponentManagerImpl implements ComponentManager { } else { validateComponentManual(component); updateComponentName(component); - createdComponent = createComponent(component); + createdComponent = compositionEntityDataManager.createComponent(component); } mdcDataDebugMessage.debugExitMessage("VSP id", component.getId()); @@ -149,10 +142,6 @@ public class ComponentManagerImpl implements ComponentManager { return createdComponent; } - private ComponentEntity createComponent(ComponentEntity component) { - return compositionEntityDataManager.createComponent(component); - } - private void updateComponentName(ComponentEntity component) { ComponentData data = component.getComponentCompositionData(); data.setName(COMPUTE_TYPE_PREFIX + data.getDisplayName()); @@ -166,8 +155,8 @@ public class ComponentManagerImpl implements ComponentManager { final String VSP_VFC_DUPLICATE_NAME_MSG = "VFC with specified name " + "already present in given VSP."; - Collection vspComponentList = listComponents(component.getVspId() - , component.getVersion(), null); + Collection vspComponentList = + listComponents(component.getVspId(), component.getVersion()); if (vspComponentList.size() >= 1) //1707 release only supports 1 VFC in VSP (manual creation) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, @@ -202,18 +191,17 @@ public class ComponentManagerImpl implements ComponentManager { } @Override - public CompositionEntityValidationData updateComponent(ComponentEntity component, String user) { + public CompositionEntityValidationData updateComponent(ComponentEntity component) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id", component .getVspId(), component.getId()); ComponentEntity retrieved = - getComponent(component.getVspId(), component.getVersion(), component.getId()); + getValidatedComponent(component.getVspId(), component.getVersion(), component.getId()); boolean isManual = vspInfoDao.isManual(component.getVspId(), component.getVersion()); if (isManual) { - validateComponentUpdateManual(component, retrieved, user); + validateComponentUpdateManual(retrieved); } - ComponentCompositionSchemaInput schemaInput = new ComponentCompositionSchemaInput(); schemaInput.setManual(isManual); schemaInput.setComponent(retrieved.getComponentCompositionData()); @@ -232,19 +220,18 @@ public class ComponentManagerImpl implements ComponentManager { return validationData; } - private void validateComponentUpdateManual(ComponentEntity component, ComponentEntity - retrieved, String user) { + private void validateComponentUpdateManual(ComponentEntity component) { Collection vspComponentList = - listComponents(component.getVspId(), component.getVersion(), user); + 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) { + for (ComponentEntity ce : vspComponentList) { if (ce.getId().equals(component.getId())) { vspComponentList.remove(ce); break; } } - if (!isVfcNameUnique(vspComponentList, component.getComponentCompositionData() + if (!isVfcNameUnique(vspComponentList, component.getComponentCompositionData() .getDisplayName())) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.UPDATE_COMPONENT, ErrorLevel.ERROR.name(), @@ -259,9 +246,9 @@ public class ComponentManagerImpl implements ComponentManager { } public CompositionEntityResponse getComponent(String vspId, Version version, - String componentId, String user) { + String componentId) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); - ComponentEntity componentEntity = getComponent(vspId, version, componentId); + ComponentEntity componentEntity = getValidatedComponent(vspId, version, componentId); ComponentData component = componentEntity.getComponentCompositionData(); ComponentCompositionSchemaInput schemaInput = new ComponentCompositionSchemaInput(); @@ -278,7 +265,7 @@ public class ComponentManagerImpl implements ComponentManager { } @Override - public void deleteComponent(String vspId, Version version, String componentId, String user) { + public void deleteComponent(String vspId, Version version, String componentId) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); if (!vspInfoDao.isManual(vspId, version)) { @@ -289,14 +276,12 @@ public class ComponentManagerImpl implements ComponentManager { new CompositionEditNotAllowedErrorBuilder(vspId, version).build()); } - //componentDao.updateVspLatestModificationTime(vspId, version); - mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); } @Override public QuestionnaireResponse getQuestionnaire(String vspId, Version version, - String componentId, String user) { + String componentId) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse(); @@ -306,7 +291,7 @@ public class ComponentManagerImpl implements ComponentManager { VspDetails.ENTITY_TYPE); questionnaireResponse.setData(component.getQuestionnaireData()); - List nicNames = nicManager.listNics(vspId, version, componentId, user).stream() + 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 @@ -319,23 +304,21 @@ public class ComponentManagerImpl implements ComponentManager { @Override public void updateQuestionnaire(String vspId, Version version, String componentId, - String questionnaireData, String user) { + String questionnaireData) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); - validateComponentExistence(vspId, version, componentId, user); + validateComponentExistence(vspId, version, componentId); componentDao.updateQuestionnaireData(vspId, version, componentId, questionnaireData); - //componentDao.updateVspLatestModificationTime(vspId, version); mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); } @Override - public void validateComponentExistence(String vspId, Version version, String componentId, - String user) { - getComponent(vspId, version, componentId); + public void validateComponentExistence(String vspId, Version version, String componentId) { + getValidatedComponent(vspId, version, componentId); } - private ComponentEntity getComponent(String vspId, Version version, String 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), @@ -353,8 +336,4 @@ public class ComponentManagerImpl implements ComponentManager { .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.component, schemaInput); } - - /*private boolean isManual(String vspId, Version version) { - return false; - }*/ } 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 71985fa83e..598c45f323 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 @@ -2,7 +2,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.sdc.vendorsoftwareproduct.ComputeManager; import org.openecomp.sdc.vendorsoftwareproduct.ComputeManagerFactory; -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.VendorSoftwareProductInfoDaoFactory; @@ -15,10 +14,7 @@ public class ComputeManagerFactoryImpl extends ComputeManagerFactory { VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), ComputeDaoFactory.getInstance().createInterface(), CompositionEntityDataManagerFactory.getInstance().createInterface(), - DeploymentFlavorDaoFactory.getInstance().createInterface(), - ComponentDaoFactory.getInstance().createInterface() - - ); + DeploymentFlavorDaoFactory.getInstance().createInterface()); @Override public ComputeManager createInterface() { 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 be90b08af9..0fc0aaffb1 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 @@ -2,6 +2,8 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.core.util.UniqueValueUtil; +import org.openecomp.core.utilities.json.JsonSchemaDataGenerator; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; @@ -12,7 +14,7 @@ import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; import org.openecomp.sdc.vendorsoftwareproduct.ComputeManager; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; +import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; @@ -51,33 +53,22 @@ public class ComputeManagerImpl implements ComputeManager { private CompositionEntityDataManager compositionEntityDataManager; private VendorSoftwareProductInfoDao vspInfoDao; private DeploymentFlavorDao deploymentFlavorDao; - private ComponentDao componentDao; - private static final String MANUAL = "Manual"; - - public ComputeManagerImpl( - VendorSoftwareProductInfoDao vspInfoDao, - ComputeDao computeDao, - CompositionEntityDataManager compositionEntityDataManager, - DeploymentFlavorDao deploymentFlavorDao, - ComponentDao componentDao - ) { + + public ComputeManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, + ComputeDao computeDao, + CompositionEntityDataManager compositionEntityDataManager, + DeploymentFlavorDao deploymentFlavorDao) { this.computeDao = computeDao; this.compositionEntityDataManager = compositionEntityDataManager; this.vspInfoDao = vspInfoDao; this.deploymentFlavorDao = deploymentFlavorDao; - this.componentDao = componentDao; } @Override - public ComputeEntity createCompute(ComputeEntity compute, String user) { - ComputeEntity createdCompute = null; - mdcDataDebugMessage.debugEntryMessage("VSP id, component id", compute.getVspId(), - compute.getComponentId()); - - /*Version activeVersion = - getVersionInfo(compute.getVspId(), VersionableEntityAction.Write, user).getActiveVersion(); - compute.setVersion(activeVersion);*/ - //if (!isManual(compute.getVspId(), activeVersion)) { + public ComputeEntity createCompute(ComputeEntity compute) { + mdcDataDebugMessage + .debugEntryMessage("VSP id, component id", compute.getVspId(), compute.getComponentId()); + if (!vspInfoDao.isManual(compute.getVspId(), compute.getVersion())) { ErrorCode onboardingMethodUpdateErrorCode = NotSupportedHeatOnboardMethodErrorBuilder .getAddComputeNotSupportedHeatOnboardMethodErrorBuilder(); @@ -87,92 +78,45 @@ public class ComputeManagerImpl implements ComputeManager { onboardingMethodUpdateErrorCode.message()); throw new CoreException(onboardingMethodUpdateErrorCode); } else { - - //validateComponentId(compute.getVspId(),compute.getVersion(),compute.getComponentId()); - Collection vfcComputeList = listCompute(compute.getVspId(),compute.getVersion - (),compute.getComponentId()); - - validateVfcCompute(compute, vfcComputeList, LoggerTragetServiceName.CREATE_COMPUTE); - createdCompute = createCompute(compute); + 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()); } mdcDataDebugMessage .debugExitMessage("VSP id, component id", compute.getVspId(), compute.getComponentId()); - return createdCompute; + return compute; } - private ComputeEntity createCompute(ComputeEntity compute) { - - return compositionEntityDataManager.createCompute(compute); - } - - /*private void validateCompute(ComputeEntity compute) { - Collection vfcComputeList = listCompute(compute.getVspId(),compute.getVersion - (),compute.getComponentId()); - - if (!isComputeNameUnique(vfcComputeList,compute.getComputeCompositionData().getName())) { - final ErrorCode duplicateComputeInComponentErrorBuilder = - new DuplicateComputeInComponentErrorBuilder(compute.getComputeCompositionData().getName(), - compute.getComponentId()).build(); - MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.CREATE_COMPUTE, ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), - duplicateComputeInComponentErrorBuilder.message()); - throw new CoreException(duplicateComputeInComponentErrorBuilder); - } - - }*/ - - private void validateComputeUpdate(ComputeEntity compute) { - Collection vfcComputeList = listCompute(compute.getVspId(),compute.getVersion - (),compute.getComponentId()); - - for (ComputeEntity ce : vfcComputeList) { - if (ce.getId().equals(compute.getId())) { - vfcComputeList.remove(ce); - break; - } - } - - if (!isComputeNameUnique(vfcComputeList,compute.getComputeCompositionData().getName())) { - final ErrorCode duplicateComputeInComponentErrorBuilder = - new DuplicateComputeInComponentErrorBuilder(compute.getComputeCompositionData().getName(), - compute.getComponentId()).build(); - MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.UPDATE_COMPUTE, ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), - duplicateComputeInComponentErrorBuilder.message()); - throw new CoreException(duplicateComputeInComponentErrorBuilder); - } - - } @Override - public Collection listCompute(String vspId, Version version, - String componentId, String user) { - + public Collection listComputes(String vspId, Version version, + String componentId) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); - //validateComponentId(vspId, version, componentId); - ComputeEntity entity = new ComputeEntity(vspId, version, componentId, null); - Collection computes = computeDao.list(entity); + Collection computes = + computeDao.list(new ComputeEntity(vspId, version, componentId, null)); Collection computeResponse = - getListComputeResponse(vspId, version, user, computes); + getListComputeResponse(vspId, version, computes); mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); return computeResponse; } private Collection getListComputeResponse(String vspId, Version version, - String user, Collection computes) { - Set vspComputes = getComputeAssociatedWithDepFlavors(vspId, version, user); - Collection computeResponse = new ArrayList(); - for(ComputeEntity computeEntity : 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())) { + if (vspComputes.contains(computeEntity.getId())) { response.setAssociatedWithDeploymentFlavor(true); } else { response.setAssociatedWithDeploymentFlavor(false); @@ -182,16 +126,15 @@ public class ComputeManagerImpl implements ComputeManager { return computeResponse; } - private Set getComputeAssociatedWithDepFlavors(String vspId, Version version, - String user) { + 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) { + Set vspComputes = new HashSet<>(); + for (DeploymentFlavorEntity entity : deploymentFlavorEntities) { final List componentComputeAssociations = entity.getDeploymentFlavorCompositionData().getComponentComputeAssociations(); - if(componentComputeAssociations != null && !componentComputeAssociations.isEmpty()) { - for(ComponentComputeAssociation association : componentComputeAssociations) { + if (componentComputeAssociations != null && !componentComputeAssociations.isEmpty()) { + for (ComponentComputeAssociation association : componentComputeAssociations) { vspComputes.add(association.getComputeFlavorId()); } } @@ -199,32 +142,14 @@ public class ComputeManagerImpl implements ComputeManager { return vspComputes; } - private boolean isComputeNameUnique(Collection vfcComputeList, String name) { - for (ComputeEntity compute : vfcComputeList) { - if (compute.getComputeCompositionData().getName().equalsIgnoreCase(name)) { - return false; - } - } - return true; - } - - private Collection listCompute(String vspId, Version version,String componentId) { - Collection computeEntities = - computeDao.list(new ComputeEntity(vspId, version, componentId, null)); - - return computeEntities; - } - @Override public CompositionEntityResponse getCompute(String vspId, Version version, String componentId, - String computeFlavorId, String user) { + String computeFlavorId) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id, compute id", vspId, componentId, computeFlavorId); - /*version = VersioningUtil - .resolveVersion(version, getVersionInfo(vspId, VersionableEntityAction.Read, user));*/ - ComputeEntity computeEntity = getCompute(vspId, version, componentId, computeFlavorId); + ComputeEntity computeEntity = getValidatedCompute(vspId, version, componentId, computeFlavorId); ComputeData compute = computeEntity.getComputeCompositionData(); ComputeCompositionSchemaInput schemaInput = new ComputeCompositionSchemaInput(); @@ -242,9 +167,8 @@ public class ComputeManagerImpl implements ComputeManager { return response; } - private ComputeEntity getCompute(String vspId, Version version, String componentId, String - computeFlavorId) { - //validateComponentId(vspId,version,componentId); + private ComputeEntity getValidatedCompute(String vspId, Version version, String componentId, + String computeFlavorId) { ComputeEntity retrieved = computeDao.get(new ComputeEntity(vspId, version, componentId, computeFlavorId)); VersioningUtil @@ -253,186 +177,113 @@ public class ComputeManagerImpl implements ComputeManager { return retrieved; } - /*private void validateComponentId(String vspId, Version version, String componentId) { - ComponentEntity retrivedComponent = componentDao.get(new ComponentEntity(vspId, version, - componentId)); - VersioningUtil - .validateEntityExistence(retrivedComponent, new ComponentEntity(vspId, version, - componentId),VspDetails.ENTITY_TYPE); - }*/ - @Override public QuestionnaireResponse getComputeQuestionnaire(String vspId, Version version, String - componentId, String computeId, String user) { + componentId, String computeId) { mdcDataDebugMessage.debugEntryMessage("VSP id, componentId", vspId, componentId, computeId); - /*version = VersioningUtil - .resolveVersion(version, getVersionInfo(vspId, VersionableEntityAction.Read, user));*/ - //validateComponentId(vspId,version,componentId); QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse(); - //validateComponentId(vspId,version,componentId); - ComputeEntity computeQuestionnaire = computeDao.getQuestionnaireData(vspId, version, componentId, computeId); + ComputeEntity computeQuestionnaire = + computeDao.getQuestionnaireData(vspId, version, componentId, computeId); VersioningUtil - .validateEntityExistence(computeQuestionnaire, new ComputeEntity(vspId, version, componentId, - computeId), VspDetails.ENTITY_TYPE); + .validateEntityExistence(computeQuestionnaire, + new ComputeEntity(vspId, version, componentId, computeId), VspDetails.ENTITY_TYPE); questionnaireResponse.setData(computeQuestionnaire.getQuestionnaireData()); questionnaireResponse.setSchema(getComputeQuestionnaireSchema(null)); - mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, - componentId, computeId); + mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId, computeId); return questionnaireResponse; } - protected String getComputeQuestionnaireSchema(SchemaTemplateInput schemaInput) { - mdcDataDebugMessage.debugEntryMessage(null, null); - - mdcDataDebugMessage.debugExitMessage(null, null); - return SchemaGenerator - .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.compute, - schemaInput); - } - - @Override - public void updateComputeQuestionnaire(String vspId, Version version, String componentId, String - computeId, - String questionnaireData, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id, compute id", vspId, - componentId, computeId); + public void updateComputeQuestionnaire(String vspId, Version version, String componentId, + String computeId, String questionnaireData) { + mdcDataDebugMessage + .debugEntryMessage("VSP id, component id, compute id", vspId, componentId, computeId); - /*Version activeVersion = - getVersionInfo(vspId, VersionableEntityAction.Write, user).getActiveVersion(); - getComponent(vspId, activeVersion, componentId);*/ - ComputeEntity retrieved = computeDao.get(new ComputeEntity(vspId,version,componentId, + 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); - mdcDataDebugMessage.debugExitMessage("VSP id, component id, compute id", vspId, - componentId, computeId); + mdcDataDebugMessage + .debugExitMessage("VSP id, component id, compute id", vspId, componentId, computeId); } @Override - public CompositionEntityValidationData updateCompute(ComputeEntity compute, String user) { + public CompositionEntityValidationData updateCompute(ComputeEntity compute) { mdcDataDebugMessage - .debugEntryMessage("VSP id, component id", compute.getVspId(), compute.getComponentId(), - compute.getId()); - - /*Version activeVersion = - getVersionInfo(image.getVspId(), VersionableEntityAction.Write, user).getActiveVersion(); - image.setVersion(activeVersion);*/ + .debugEntryMessage("VSP id, component id", compute.getVspId(), compute.getComponentId(), + compute.getId()); - ComputeEntity retrieved = getComputeEntity(compute.getVspId(), compute.getVersion(), compute.getComponentId(), + ComputeEntity retrieved = + getComputeEntity(compute.getVspId(), compute.getVersion(), compute.getComponentId(), compute.getId()); - if(!vspInfoDao.isManual(compute.getVspId(), compute.getVersion())) { - final ComputeData computeCompositionData = compute.getComputeCompositionData(); - final String name = computeCompositionData.getName(); - //final String format = computeCompositionData.getFormat(); - validateHeatVspComputeUpdate("Name", name, retrieved.getComputeCompositionData() - .getName()); - /*validateHeatVspComputeUpdate("format", format, retrieved.getComputeCompositionData() - .getFormat());*/ + boolean manual = vspInfoDao.isManual(compute.getVspId(), compute.getVersion()); + if (!manual) { + validateHeatVspComputeUpdate("Name", + compute.getComputeCompositionData().getName(), + retrieved.getComputeCompositionData().getName()); } - Collection vfcComputeList = listComputes(compute.getVspId() , - compute.getVersion(), compute.getComponentId()); - - //Set to null so that retrieved object is equal to one in list and gets removed. - retrieved.setQuestionnaireData(null); - vfcComputeList.remove(retrieved); - if(vspInfoDao.isManual(compute.getVspId(), compute.getVersion())) - validateVfcCompute(compute, vfcComputeList, LoggerTragetServiceName.UPDATE_COMPUTE); - - //Set format to default value in order to handle FTL validation when compute format is null - /*if(compute.getComputeCompositionData().getFormat() == null) - compute.getComputeCompositionData().setFormat(ComputeFormat.qcow2.name());*/ - ComputeCompositionSchemaInput schemaInput = new ComputeCompositionSchemaInput(); schemaInput.setCompute(compute.getComputeCompositionData()); CompositionEntityValidationData validationData = compositionEntityDataManager - .validateEntity(compute, SchemaTemplateContext.composition, schemaInput); + .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); } mdcDataDebugMessage - .debugExitMessage("VSP id, component id", compute.getVspId(), compute.getComponentId(), - compute.getId()); + .debugExitMessage("VSP id, component id", compute.getVspId(), compute.getComponentId(), + compute.getId()); return validationData; } private void validateHeatVspComputeUpdate(String name, String value, String retrivedValue) { - if(value != null && !value.equals(retrivedValue)) { + if (value != null && !value.equals(retrivedValue)) { final ErrorCode updateHeatComputeErrorBuilder = - DuplicateComputeInComponentErrorBuilder.getComputeHeatReadOnlyErrorBuilder(name); + DuplicateComputeInComponentErrorBuilder.getComputeHeatReadOnlyErrorBuilder(name); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.UPDATE_COMPUTE, ErrorLevel.ERROR.name(), - LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), - updateHeatComputeErrorBuilder.message()); + LoggerTragetServiceName.UPDATE_COMPUTE, ErrorLevel.ERROR.name(), + LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), + updateHeatComputeErrorBuilder.message()); throw new CoreException(updateHeatComputeErrorBuilder); } } - private void validateVfcCompute(ComputeEntity compute, Collection vfcComputeList, - String event) { - if (isComputeNameDuplicate(vfcComputeList,compute.getComputeCompositionData().getName(), - compute.getId())) { - ErrorCode errorCode = DuplicateComputeInComponentErrorBuilder - .getDuplicateComputeNameErrorBuilder(compute.getComputeCompositionData().getName(), - compute.getComponentId()); - - MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - event, ErrorLevel.ERROR.name(), - errorCode.id(),errorCode.message()); - - throw new CoreException(errorCode); - } - } - - private boolean isComputeNameDuplicate(Collection computes, String name, String computeId) { - for (ComputeEntity compute : computes) { - if (compute.getComputeCompositionData().getName().equalsIgnoreCase(name) && !compute.getId().equals(computeId)) { - return true; - } - } - return false; - } - - private ComputeEntity getComputeEntity(String vspId, Version version, String componentId, - String computeId) { - //validateComponentId(vspId,version,componentId); - ComputeEntity computeEntity = computeDao.get(new ComputeEntity(vspId, version, componentId, computeId)); - VersioningUtil.validateEntityExistence(computeEntity, new ComputeEntity(vspId, version, componentId, - computeId), VspDetails.ENTITY_TYPE); - return computeEntity; - } - - private Collection listComputes(String vspId, Version version, String componentId) { - return computeDao.list(new ComputeEntity(vspId, version, componentId, null)); + 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 void deleteCompute(String vspId, Version version, String componentId, String - computeFlavorId, String user) { + public void deleteCompute(String vspId, Version version, String componentId, + String computeFlavorId) { final String VSP_COMPOSITION_EDIT_NOT_ALLOWED_MSG = "Composition entities may not be created / deleted for Vendor Software Product " + "whose entities were uploaded"; mdcDataDebugMessage.debugEntryMessage("VSP id, component id, compute id", vspId, componentId, computeFlavorId); - /*Version activeVersion = - getVersionInfo(vspId, VersionableEntityAction.Write, user).getActiveVersion();*/ if (!vspInfoDao.isManual(vspId, version)) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.DELETE_COMPUTE, ErrorLevel.ERROR.name(), @@ -442,30 +293,32 @@ public class ComputeManagerImpl implements ComputeManager { .withId(VendorSoftwareProductErrorCodes.VSP_COMPOSITION_EDIT_NOT_ALLOWED) .withMessage(VSP_COMPOSITION_EDIT_NOT_ALLOWED_MSG).build()); } - ComputeEntity retrived = getCompute(vspId,version,componentId,computeFlavorId); - if (retrived != null){ - deleteComputeFromDeploymentFlavors(vspId,version,computeFlavorId); + 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()); } mdcDataDebugMessage.debugExitMessage("VSP id, component id, compute id", vspId, componentId, computeFlavorId); } - private void deleteComputeFromDeploymentFlavors(String vspId, Version activeVersion, + private void deleteComputeFromDeploymentFlavors(String vspId, Version version, String computeFlavorId) { - //Collection listDF = listDeploymentFlavors(vspId, activeVersion); - Collection listDF = deploymentFlavorDao.list(new DeploymentFlavorEntity - (vspId, activeVersion, null)); - for(DeploymentFlavorEntity df : listDF) { - DeploymentFlavorEntity deploymentFlavorEntity=removeComputeFromDF(df, computeFlavorId); - if(deploymentFlavorEntity!=null) + 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) { + private DeploymentFlavorEntity removeComputeFromDF(DeploymentFlavorEntity df, + String computeFlavorId) { DeploymentFlavor flavor = df.getDeploymentFlavorCompositionData(); List associations = flavor.getComponentComputeAssociations(); if (associations != null) { @@ -486,20 +339,47 @@ public class ComputeManagerImpl implements ComputeManager { return null; } - protected String getComputeCompositionSchema(SchemaTemplateInput schemaInput){ - mdcDataDebugMessage.debugEntryMessage(null, null); - mdcDataDebugMessage.debugExitMessage(null, null); - return SchemaGenerator.generate(SchemaTemplateContext.composition, CompositionEntityType.compute, schemaInput); + protected String getComputeCompositionSchema(SchemaTemplateInput schemaInput) { + mdcDataDebugMessage.debugEntryMessage(null); + mdcDataDebugMessage.debugExitMessage(null); + return SchemaGenerator + .generate(SchemaTemplateContext.composition, CompositionEntityType.compute, schemaInput); + } + + protected String getComputeQuestionnaireSchema(SchemaTemplateInput schemaInput) { + mdcDataDebugMessage.debugEntryMessage(null); + mdcDataDebugMessage.debugExitMessage(null); + return SchemaGenerator + .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.compute, schemaInput); } - /*boolean isManual(String vspId, Version version) { + protected void validateUniqueName(String vspId, Version version, String componentId, + String name) { + UniqueValueUtil.validateUniqueValue(VendorSoftwareProductConstants.UniqueValues.COMPUTE_NAME, + vspId, version.getId(), componentId, name); + } - VspDetails vsp = vspInfoDao.get(new VspDetails(vspId, version)); - String onboardingMethod = vsp.getOnboardingMethod(); - if (MANUAL.equals(onboardingMethod)) { - return true; - } - return false; - }*/ + protected void createUniqueName(String vspId, Version version, String componentId, String name) { + 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 + .updateUniqueValue(VendorSoftwareProductConstants.UniqueValues.COMPUTE_NAME, oldName, + newName, vspId, version.getId(), componentId); + } + protected void deleteUniqueValue(String vspId, Version version, String componentId, String name) { + if (componentId == null) { + UniqueValueUtil + .deleteUniqueValue(VendorSoftwareProductConstants.UniqueValues.COMPUTE_NAME, vspId, + version.getId(), 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/DeploymentFlavorManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeploymentFlavorManagerImpl.java index 0873eaf921..f1acaae178 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 @@ -44,18 +44,14 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { private VendorSoftwareProductInfoDao vspInfoDao; private DeploymentFlavorDao deploymentFlavorDao; private CompositionEntityDataManager compositionEntityDataManager; - private ComponentDao componentDao; + private ComponentDao componentDao; private ComputeDao computeDao; - public DeploymentFlavorManagerImpl( - VendorSoftwareProductInfoDao vspInfoDao, - DeploymentFlavorDao deploymentFlavorDao, - CompositionEntityDataManager compositionEntityDataManager, - ComponentDao componentDao, - ComputeDao computeDao - - ) { - + public DeploymentFlavorManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, + DeploymentFlavorDao deploymentFlavorDao, + CompositionEntityDataManager compositionEntityDataManager, + ComponentDao componentDao, + ComputeDao computeDao) { this.vspInfoDao = vspInfoDao; this.deploymentFlavorDao = deploymentFlavorDao; this.compositionEntityDataManager = compositionEntityDataManager; @@ -65,31 +61,17 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { } @Override - public Collection listDeploymentFlavors(String vspId, Version version, - String user) { + public Collection listDeploymentFlavors(String vspId, Version version) { mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); - /*version = VersioningUtil - .resolveVersion(version, getVersionInfo(vspId, VersionableEntityAction.Read, user));*/ - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); - return listDeploymentFlavors(vspId, version); - } - - private Collection listDeploymentFlavors(String vspId, Version version) { - Collection deploymentFlavorEntities = - deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); - return deploymentFlavorEntities; + return deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); } @Override public DeploymentFlavorEntity createDeploymentFlavor( - DeploymentFlavorEntity deploymentFlavorEntity, String user) { - DeploymentFlavorEntity createDeploymentFlavor = null; + DeploymentFlavorEntity deploymentFlavorEntity) { + DeploymentFlavorEntity createDeploymentFlavor; mdcDataDebugMessage.debugEntryMessage("VSP id ", deploymentFlavorEntity.getVspId()); - /*Version activeVersion = - getVersionInfo(deploymentFlavorEntity.getVspId(), VersionableEntityAction.Write, user) - .getActiveVersion(); - deploymentFlavorEntity.setVersion(activeVersion);*/ if (!vspInfoDao.isManual(deploymentFlavorEntity.getVspId(), deploymentFlavorEntity.getVersion())) { @@ -100,31 +82,30 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), deploymentFlavorErrorBuilder.message()); throw new CoreException(deploymentFlavorErrorBuilder); } else { - validateDeploymentFlavor(deploymentFlavorEntity, user, deploymentFlavorEntity.getVersion()); + validateDeploymentFlavor(deploymentFlavorEntity, deploymentFlavorEntity.getVersion()); createDeploymentFlavor = compositionEntityDataManager.createDeploymentFlavor(deploymentFlavorEntity); } return createDeploymentFlavor; } - private void validateDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity, String - user, Version activeVersion) { - + private void validateDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity, + Version version) { //Validation for unique model. Collection listDeploymentFlavors = listDeploymentFlavors(deploymentFlavorEntity.getVspId(), - activeVersion); + version); isDeploymentFlavorModelDuplicate(deploymentFlavorEntity, listDeploymentFlavors); List featureGroups = - getFeatureGroupListForVsp(deploymentFlavorEntity.getVspId(), user, activeVersion); + getFeatureGroupListForVsp(deploymentFlavorEntity.getVspId(), version); String featureGroup = deploymentFlavorEntity.getDeploymentFlavorCompositionData() .getFeatureGroupId(); - if (featureGroup != null && featureGroup.trim().length()>0) { + if (featureGroup != null && featureGroup.trim().length() > 0) { if (isEmpty(featureGroups) || (!(validFeatureGroup(featureGroups, featureGroup)))) { ErrorCode deploymentFlavorErrorBuilder = DeploymentFlavorErrorBuilder .getFeatureGroupNotexistErrorBuilder(featureGroup, deploymentFlavorEntity.getVspId(), - activeVersion); + version); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.CREATE_DEPLOYMENT_FLAVOR, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), deploymentFlavorErrorBuilder.message()); @@ -132,7 +113,7 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { } } - validateComponentComputeAssociation(deploymentFlavorEntity, activeVersion); + validateComponentComputeAssociation(deploymentFlavorEntity, version); } private void isDeploymentFlavorModelDuplicate(DeploymentFlavorEntity deploymentFlavorEntity, @@ -152,14 +133,8 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { }); } - private List getFeatureGroupListForVsp(String vspId, - String user, Version activeVersion) { - /*VersionedVendorSoftwareProductInfo versionedVendorSoftwareProductInfo = getVspDetails( - vspId,activeVersion, user); - return versionedVendorSoftwareProductInfo.getVspDetails() - .getFeatureGroups();*/ - - final VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, activeVersion)); + private List getFeatureGroupListForVsp(String vspId, Version version) { + final VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); return vspDetails.getFeatureGroups(); } @@ -183,7 +158,7 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { } private void validateComponentComputeAssociation(DeploymentFlavorEntity deploymentFlavorEntity, - Version activeVersion) { + Version version) { List componentComputeAssociationList = deploymentFlavorEntity .getDeploymentFlavorCompositionData().getComponentComputeAssociations(); List vfcList = new ArrayList<>(); @@ -201,14 +176,14 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { LoggerErrorCode.DATA_ERROR.getErrorCode(), invalidAssociationErrorBuilder.message()); throw new CoreException(invalidAssociationErrorBuilder); } else if (componentComputeAssociation.getComponentId() != null && - componentComputeAssociation.getComponentId().trim().length() > 0 ) { - ComponentEntity component = getComponent(deploymentFlavorEntity.getVspId(), activeVersion, + componentComputeAssociation.getComponentId().trim().length() > 0) { + ComponentEntity component = getComponent(deploymentFlavorEntity.getVspId(), version, componentComputeAssociation.getComponentId()); if (componentComputeAssociation .getComputeFlavorId() != null && componentComputeAssociation - .getComputeFlavorId().trim().length() > 0 ) { + .getComputeFlavorId().trim().length() > 0) { ComputeEntity computeFlavor = computeDao.get(new ComputeEntity(deploymentFlavorEntity - .getVspId(), activeVersion, componentComputeAssociation.getComponentId(), + .getVspId(), version, componentComputeAssociation.getComponentId(), componentComputeAssociation.getComputeFlavorId())); if (computeFlavor == null) { ErrorCode invalidComputeIdErrorBuilder = DeploymentFlavorErrorBuilder @@ -251,22 +226,19 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { @Override public CompositionEntityResponse getDeploymentFlavor(String vspId, Version version, - String deploymentFlavorId, - String user) { + String deploymentFlavorId) { mdcDataDebugMessage .debugEntryMessage("VSP id, deployment flavor id", vspId, deploymentFlavorId); - /*version = VersioningUtil - .resolveVersion(version, getVersionInfo(vspId, VersionableEntityAction.Read, user));*/ - DeploymentFlavorEntity deploymentFlavorEntity = getDeploymentFlavor(vspId,version, - 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, user, version); + getFeatureGroupListForVsp(vspId, version); schemaInput.setFeatureGroupIds(featureGroups); CompositionEntityResponse response = new CompositionEntityResponse<>(); response.setId(deploymentFlavorId); @@ -280,27 +252,24 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { return response; } - private DeploymentFlavorEntity getDeploymentFlavor(String vspId, Version version, String + 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); + deploymentFlavorId), VspDetails.ENTITY_TYPE); return retrieved; } @Override public CompositionEntityResponse getDeploymentFlavorSchema(String vspId, - Version version, - String user) { - /*version = VersioningUtil - .resolveVersion(version, getVersionInfo(vspId, VersionableEntityAction.Read, user));*/ - DeploymentFlavorCompositionSchemaInput schemaInput= new - DeploymentFlavorCompositionSchemaInput(); + Version version) { + DeploymentFlavorCompositionSchemaInput schemaInput = + new DeploymentFlavorCompositionSchemaInput(); schemaInput.setManual(vspInfoDao.isManual(vspId, version)); List featureGroups = - getFeatureGroupListForVsp(vspId, user, version); + getFeatureGroupListForVsp(vspId, version); schemaInput.setFeatureGroupIds(featureGroups); CompositionEntityResponse response = new CompositionEntityResponse<>(); response.setSchema((SchemaGenerator @@ -310,14 +279,13 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { } @Override - public void deleteDeploymentFlavor(String vspId, Version version, String deploymentFlavorId, - String user) { + public void deleteDeploymentFlavor(String vspId, Version version, String deploymentFlavorId) { mdcDataDebugMessage .debugEntryMessage("VSP id, deployment flavor id", vspId, deploymentFlavorId); /*Version activeVersion = getVersionInfo(vspId, VersionableEntityAction.Write, user).getActiveVersion();*/ - DeploymentFlavorEntity deploymentFlavorEntity = getDeploymentFlavor(vspId,version, - deploymentFlavorId); + DeploymentFlavorEntity deploymentFlavorEntity = + getValidatedDeploymentFlavor(vspId, version, deploymentFlavorId); if (!vspInfoDao.isManual(vspId, version)) { final ErrorCode deleteDeploymentFlavorErrorBuilder = NotSupportedHeatOnboardMethodErrorBuilder @@ -328,7 +296,7 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { deleteDeploymentFlavorErrorBuilder.message()); throw new CoreException(deleteDeploymentFlavorErrorBuilder); } - if(deploymentFlavorEntity != null) { + if (deploymentFlavorEntity != null) { deploymentFlavorDao.delete(new DeploymentFlavorEntity(vspId, version, deploymentFlavorId)); } @@ -336,8 +304,8 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { .debugExitMessage("VSP id, deployment flavor id", vspId, deploymentFlavorId); } - public CompositionEntityValidationData updateDeploymentFlavor(DeploymentFlavorEntity - deploymentFlavorEntity, String user) { + public CompositionEntityValidationData updateDeploymentFlavor( + DeploymentFlavorEntity deploymentFlavorEntity) { mdcDataDebugMessage.debugEntryMessage("VSP id, deploymentFlavor id", deploymentFlavorEntity .getVspId(), deploymentFlavorEntity.getId()); /*Version activeVersion = @@ -355,9 +323,9 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { updateDeploymentFlavorErrorBuilder.message()); throw new CoreException(updateDeploymentFlavorErrorBuilder); } - //deploymentFlavorEntity.setVersion(activeVersion); DeploymentFlavorEntity retrieved = - getDeploymentFlavor(deploymentFlavorEntity.getVspId(), deploymentFlavorEntity.getVersion(), + getValidatedDeploymentFlavor(deploymentFlavorEntity.getVspId(), + deploymentFlavorEntity.getVersion(), deploymentFlavorEntity.getId()); @@ -367,7 +335,8 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { isDeploymentFlavorModelDuplicate(deploymentFlavorEntity, listDeploymentFlavors); //validateComponentComputeAssociation(deploymentFlavorEntity, activeVersion); - validateComponentComputeAssociation(deploymentFlavorEntity, deploymentFlavorEntity.getVersion()); + validateComponentComputeAssociation(deploymentFlavorEntity, + deploymentFlavorEntity.getVersion()); DeploymentFlavorCompositionSchemaInput schemaInput = new DeploymentFlavorCompositionSchemaInput(); @@ -376,7 +345,7 @@ public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { schemaInput.setDeploymentFlavor(retrieved.getDeploymentFlavorCompositionData()); List featureGroups = - getFeatureGroupListForVsp(deploymentFlavorEntity.getVspId(), user, + getFeatureGroupListForVsp(deploymentFlavorEntity.getVspId(), deploymentFlavorEntity.getVersion()); schemaInput.setFeatureGroupIds(featureGroups); 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 82b71399aa..0429ba4de8 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 @@ -37,72 +37,49 @@ import org.openecomp.sdc.versioning.dao.types.Version; import java.util.Collection; import java.util.stream.Collectors; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - public class ImageManagerImpl implements ImageManager { private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private VendorSoftwareProductInfoDao vspInfoDao; private ImageDao imageDao; private CompositionEntityDataManager compositionEntityDataManager; - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); - - public ImageManagerImpl( - VendorSoftwareProductInfoDao vspInfoDao, - ImageDao imageDao, - CompositionEntityDataManager compositionEntityDataManager - - ) { - + public ImageManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, + ImageDao imageDao, + CompositionEntityDataManager compositionEntityDataManager) { this.vspInfoDao = vspInfoDao; this.imageDao = imageDao; this.compositionEntityDataManager = compositionEntityDataManager; - } @Override - public ImageEntity createImage(ImageEntity imageEntity, String user) { - /*Version activeVersion = getVersionInfo(imageEntity.getVspId(), - VersionableEntityAction.Write, user).getActiveVersion(); - - imageEntity.setVersion(activeVersion);*/ + public ImageEntity createImage(ImageEntity imageEntity) { boolean isManual = vspInfoDao.isManual(imageEntity.getVspId(), imageEntity.getVersion()); if (!isManual) { - ErrorCode errorCode = NotSupportedHeatOnboardMethodErrorBuilder - .getAddImageNotSupportedHeatOnboardMethodErrorBuilder(); + .getAddImageNotSupportedHeatOnboardMethodErrorBuilder(); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.CREATE_IMAGE, ErrorLevel.ERROR.name(), - errorCode.id(), errorCode.message()); + LoggerTragetServiceName.CREATE_IMAGE, ErrorLevel.ERROR.name(), + errorCode.id(), errorCode.message()); throw new CoreException(errorCode); } - - /*Collection vfcImageList = listImages(imageEntity.getVspId() , - imageEntity.getVersion(), imageEntity.getComponentId());*/ compositionEntityDataManager.createImage(imageEntity); return imageEntity; } @Override - public Collection listImages(String vspId, Version version, String componentId, - String user) { + public Collection listImages(String vspId, Version version, String componentId) { mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); - Collection imageEntities = listImages(vspId, version, componentId); + Collection imageEntities = + imageDao.list(new ImageEntity(vspId, version, componentId, null)); mdcDataDebugMessage.debugExitMessage("VSP id", vspId); - return imageEntities; } - private Collection listImages(String vspId, Version version, String componentId) { - return imageDao.list(new ImageEntity(vspId, version, componentId, null)); - } - @Override - public CompositionEntityResponse getImageSchema(String vspId, String user) { + public CompositionEntityResponse getImageSchema(String vspId) { mdcDataDebugMessage.debugEntryMessage("VSP id, image id", vspId); CompositionEntityResponse response = new CompositionEntityResponse<>(); @@ -118,14 +95,10 @@ public class ImageManagerImpl implements ImageManager { @Override public CompositionEntityResponse getImage(String vspId, Version version, String - componentId, String imageId, String user) { + componentId, String imageId) { mdcDataDebugMessage.debugEntryMessage("VSP id, componentId, image id", vspId, componentId, - imageId); - - /*version = VersioningUtil - .resolveVersion(version, getVersionInfo(vspId, VersionableEntityAction.Read, user));*/ - + imageId); ImageEntity imageEntity = getImageEntity(vspId, version, componentId, imageId); Image image = imageEntity.getImageCompositionData(); @@ -142,25 +115,21 @@ public class ImageManagerImpl implements ImageManager { response.setSchema(getImageCompositionSchema(schemaInput)); mdcDataDebugMessage.debugExitMessage("VSP id, componentId, image id", vspId, componentId, - imageId); + imageId); return response; } @Override public QuestionnaireResponse getImageQuestionnaire(String vspId, Version version, String - componentId, String imageId, String user) { + componentId, String imageId) { mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); - - /*version = VersioningUtil - .resolveVersion(version, getVersionInfo(vspId, VersionableEntityAction.Read, user)); - validateComponentId(vspId,version,componentId);*/ QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse(); //validateComponentId(vspId,version,componentId); ImageEntity retrieved = imageDao.getQuestionnaireData(vspId, version, componentId, imageId); VersioningUtil.validateEntityExistence(retrieved, new ImageEntity(vspId, version, componentId, - imageId), ComponentEntity.ENTITY_TYPE); + imageId), ComponentEntity.ENTITY_TYPE); questionnaireResponse.setData(retrieved.getQuestionnaireData()); questionnaireResponse.setSchema(getImageQuestionnaireSchema(null)); @@ -170,72 +139,63 @@ public class ImageManagerImpl implements ImageManager { } @Override - public void deleteImage(String vspId, Version version, String componentId, String imageId, String - user) { + public void deleteImage(String vspId, Version version, String componentId, String imageId) { mdcDataDebugMessage - .debugEntryMessage("VSP id, component id", vspId, componentId, imageId); - - /*Version activeVersion = - getVersionInfo(vspId, VersionableEntityAction.Write, user).getActiveVersion(); - ComponentEntity component = getComponent(vspId, activeVersion, componentId);*/ + .debugEntryMessage("VSP id, component id", vspId, componentId, imageId); ImageEntity imageEntity = getImageEntity(vspId, version, componentId, imageId); if (!vspInfoDao.isManual(vspId, version)) { final ErrorCode deleteImageErrorBuilder = - NotSupportedHeatOnboardMethodErrorBuilder - .getDelImageNotSupportedHeatOnboardMethodErrorBuilder(); + NotSupportedHeatOnboardMethodErrorBuilder + .getDelImageNotSupportedHeatOnboardMethodErrorBuilder(); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.DELETE_IMAGE, ErrorLevel.ERROR.name(), - LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), - deleteImageErrorBuilder.message()); + LoggerTragetServiceName.DELETE_IMAGE, ErrorLevel.ERROR.name(), + LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), + deleteImageErrorBuilder.message()); throw new CoreException(deleteImageErrorBuilder); } if (imageEntity != null) { imageDao.delete(new ImageEntity(vspId, version, componentId, imageId)); } mdcDataDebugMessage - .debugExitMessage("VSP id, component id", vspId, componentId, imageId); + .debugExitMessage("VSP id, component id", vspId, componentId, imageId); } private void validateHeatVspImageUpdate(String name, String value, String retrivedValue) { - - if(value != null && !value.equals(retrivedValue)) { - + if (value != null && !value.equals(retrivedValue)) { final ErrorCode updateHeatImageErrorBuilder = - ImageErrorBuilder.getImageHeatReadOnlyErrorBuilder(name); + ImageErrorBuilder.getImageHeatReadOnlyErrorBuilder(name); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.UPDATE_IMAGE, ErrorLevel.ERROR.name(), - LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), - updateHeatImageErrorBuilder.message()); + LoggerTragetServiceName.UPDATE_IMAGE, ErrorLevel.ERROR.name(), + LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), + updateHeatImageErrorBuilder.message()); throw new CoreException(updateHeatImageErrorBuilder); } } @Override - public CompositionEntityValidationData updateImage(ImageEntity image, String user) { + public CompositionEntityValidationData updateImage(ImageEntity image) { mdcDataDebugMessage - .debugEntryMessage("VSP id, component id", image.getVspId(), image.getComponentId(), - image.getId()); + .debugEntryMessage("VSP id, component id", image.getVspId(), image.getComponentId(), + image.getId()); - /*Version activeVersion = - getVersionInfo(image.getVspId(), VersionableEntityAction.Write, user).getActiveVersion(); - image.setVersion(activeVersion);*/ boolean isManual = vspInfoDao.isManual(image.getVspId(), image.getVersion()); - ImageEntity retrieved = getImageEntity(image.getVspId(), image.getVersion(), image.getComponentId(), + ImageEntity retrieved = + getImageEntity(image.getVspId(), image.getVersion(), image.getComponentId(), image.getId()); - if(!isManual) { + if (!isManual) { final Image imageCompositionData = image.getImageCompositionData(); final String fileName = imageCompositionData.getFileName(); //final String format = imageCompositionData.getFormat(); validateHeatVspImageUpdate("fileName", fileName, retrieved.getImageCompositionData() - .getFileName()); + .getFileName()); /*validateHeatVspImageUpdate("format", format, retrieved.getImageCompositionData() .getFormat());*/ } - Collection vfcImageList = listImages(image.getVspId() , - image.getVersion(), image.getComponentId()); + 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); @@ -249,50 +209,45 @@ public class ImageManagerImpl implements ImageManager { schemaInput.setImage(image.getImageCompositionData()); CompositionEntityValidationData validationData = compositionEntityDataManager - .validateEntity(image, SchemaTemplateContext.composition, schemaInput); + .validateEntity(image, SchemaTemplateContext.composition, schemaInput); if (CollectionUtils.isEmpty(validationData.getErrors())) { imageDao.update(image); } mdcDataDebugMessage - .debugExitMessage("VSP id, component id", image.getVspId(), image.getComponentId(), - image.getId()); + .debugExitMessage("VSP id, component id", image.getVspId(), image.getComponentId(), + image.getId()); return validationData; } @Override public void updateImageQuestionnaire(String vspId, Version version, String componentId, String - imageId, String questionnaireData, String user) { + imageId, String questionnaireData) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id, imageId", vspId, componentId, - imageId); + imageId); getImageEntity(vspId, version, componentId, imageId); - /*Version activeVersion = - getVersionInfo(vspId, VersionableEntityAction.Write, user).getActiveVersion(); - - getComponent(vspId, activeVersion, componentId);*/ final ImageDetails image = JsonUtil.json2Object(questionnaireData, ImageDetails.class); final String format = image.getFormat(); try { if (format != null) { - final ImageFormat imageFormat = ImageFormat.valueOf(format); + ImageFormat.valueOf(format); } } catch (IllegalArgumentException exception) { - log.debug("", exception); ErrorCode errorCode = ImageErrorBuilder.getInvalidImageFormatErrorBuilder(); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.UPDATE_IMAGE, ErrorLevel.ERROR.name(), - errorCode.id(), errorCode.message() ); + LoggerTragetServiceName.UPDATE_IMAGE, ErrorLevel.ERROR.name(), + errorCode.id(), errorCode.message()); throw new CoreException(errorCode); } //Validate Format is read only for HEAT Onboarding if (!vspInfoDao.isManual(vspId, version)) { final QuestionnaireResponse imageQuestionnaire = getImageQuestionnaire(vspId, version, - componentId, imageId, user); + componentId, imageId); final String data = imageQuestionnaire.getData(); if (data != null) { String retrivedFormat = JsonUtil.json2Object(data, ImageDetails.class).getFormat(); @@ -300,34 +255,33 @@ public class ImageManagerImpl implements ImageManager { } } - if(!isImageVersionUnique(vspId, version, componentId, imageId, image, user)) - { + if (!isImageVersionUnique(vspId, version, componentId, imageId, image)) { ErrorCode errorCode = ImageErrorBuilder.getDuplicateImageVersionErrorBuilder(image - .getVersion(), componentId); + .getVersion(), componentId); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.UPDATE_IMAGE, ErrorLevel.ERROR.name(), - errorCode.id(),errorCode.message()); + LoggerTragetServiceName.UPDATE_IMAGE, ErrorLevel.ERROR.name(), + errorCode.id(), errorCode.message()); throw new CoreException(errorCode); } imageDao.updateQuestionnaireData(vspId, version, componentId, imageId, questionnaireData); mdcDataDebugMessage.debugExitMessage("VSP id, component id, imageId", vspId, componentId, - imageId); + imageId); } - private boolean isImageVersionUnique(String vspId, Version version, String componentId, String imageId, - ImageDetails image, String user) - { + 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, user)) + 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); @@ -337,14 +291,17 @@ public class ImageManagerImpl implements ImageManager { return isPresent; } - private String getImageVersion(String vspId, Version version, String componentId, ImageEntity imageEntity, String user) - { + private String getImageVersion(String vspId, Version version, String componentId, + ImageEntity imageEntity) { QuestionnaireResponse imageQuestionnaire = getImageQuestionnaire(vspId, version, - componentId, imageEntity.getId(), user); - ImageDetails imageDetails = JsonUtil.json2Object(imageQuestionnaire.getData(), ImageDetails.class); + componentId, imageEntity.getId()); + ImageDetails imageDetails = + JsonUtil.json2Object(imageQuestionnaire.getData(), ImageDetails.class); - return imageDetails==null?null:imageDetails.getVersion()!=null?imageDetails.getVersion().trim():null; + return imageDetails == null ? null + : imageDetails.getVersion() != null ? imageDetails.getVersion().trim() : null; } + private ImageEntity getImageEntity(String vspId, Version version, String componentId, String imageId) { //validateComponentId(vspId,version,componentId); @@ -352,34 +309,24 @@ public class ImageManagerImpl implements ImageManager { ImageEntity imageEntity = imageDao.get(new ImageEntity(vspId, version, componentId, imageId)); VersioningUtil.validateEntityExistence(imageEntity, new ImageEntity(vspId, version, componentId, - imageId), VspDetails.ENTITY_TYPE); + imageId), VspDetails.ENTITY_TYPE); return imageEntity; } - - private boolean isImageNameDuplicate(Collection images, String fileName) { - for (ImageEntity image : images) { - if (image.getImageCompositionData().getFileName().equalsIgnoreCase(fileName)) { - return true; - } - } - return false; - } - protected String getImageCompositionSchema(SchemaTemplateInput schemaInput) { - mdcDataDebugMessage.debugEntryMessage(null, null); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); + mdcDataDebugMessage.debugExitMessage(null); return SchemaGenerator - .generate(SchemaTemplateContext.composition, CompositionEntityType.image, - schemaInput); + .generate(SchemaTemplateContext.composition, CompositionEntityType.image, + schemaInput); } protected String getImageQuestionnaireSchema(SchemaTemplateInput schemaInput) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); return SchemaGenerator - .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.image, - schemaInput); + .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 8bdc7fdfce..fdb9621bcb 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 @@ -6,8 +6,6 @@ import org.openecomp.sdc.generator.core.services.ManualVspToscaGenerationService import org.openecomp.sdc.generator.datatypes.tosca.DeploymentFlavorModel; import org.openecomp.sdc.generator.datatypes.tosca.MultiFlavorVfcImage; import org.openecomp.sdc.generator.datatypes.tosca.VspModelInfo; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; @@ -29,18 +27,15 @@ public class ManualVspToscaManagerImpl implements ManualVspToscaManager { private ManualVspDataCollectionService manualVspDataCollectionService = new ManualVspDataCollectionService(); - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); - @Override - public VspModelInfo gatherVspInformation(String vspId, Version version, String user) { + public VspModelInfo gatherVspInformation(String vspId, Version version) { mdcDataDebugMessage.debugEntryMessage(null, null); VspModelInfo vspModelInfo = new VspModelInfo(); //Get Release Vendor Name Optional releaseVendor; try { - releaseVendor = manualVspDataCollectionService.getReleaseVendor(vspId, version, user); + releaseVendor = manualVspDataCollectionService.getReleaseVendor(vspId, version); } catch (Exception ex) { - log.debug("", ex); releaseVendor = Optional.empty(); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.COLLECT_MANUAL_VSP_TOSCA_DATA, ErrorLevel.INFO.name(), @@ -52,9 +47,8 @@ public class ManualVspToscaManagerImpl implements ManualVspToscaManager { //Get Allowed Deployment flavors information Map allowedFlavors; try { - allowedFlavors = manualVspDataCollectionService.getAllowedFlavors(vspId, version, user); + allowedFlavors = manualVspDataCollectionService.getAllowedFlavors(vspId, version); } catch (Exception ex) { - log.debug("", ex); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.COLLECT_MANUAL_VSP_TOSCA_DATA, ErrorLevel.INFO.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Unable to collect allowed flavors : " @@ -69,9 +63,8 @@ public class ManualVspToscaManagerImpl implements ManualVspToscaManager { Map> vspComponentImages; try { vspComponentImages = - manualVspDataCollectionService.getVspComponentImages(vspId, version, user); + manualVspDataCollectionService.getVspComponentImages(vspId, version); } catch (Exception ex) { - log.debug("", ex); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.COLLECT_MANUAL_VSP_TOSCA_DATA, ErrorLevel.INFO.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Unable to collect vsp component images : " @@ -85,9 +78,8 @@ public class ManualVspToscaManagerImpl implements ManualVspToscaManager { //Get VFC component information Map vspComponents; try { - vspComponents = manualVspDataCollectionService.getVspComponents(vspId, version, user); + vspComponents = manualVspDataCollectionService.getVspComponents(vspId, version); } catch (Exception ex) { - log.debug("", ex); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.COLLECT_MANUAL_VSP_TOSCA_DATA, ErrorLevel.INFO.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Unable to collect vsp components : " @@ -101,9 +93,8 @@ public class ManualVspToscaManagerImpl implements ManualVspToscaManager { //Get VSP component nic information Map> vspComponentNics; try { - vspComponentNics = manualVspDataCollectionService.getVspComponentNics(vspId, version, user); + vspComponentNics = manualVspDataCollectionService.getVspComponentNics(vspId, version); } catch (Exception ex) { - log.debug("", ex); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.COLLECT_MANUAL_VSP_TOSCA_DATA, ErrorLevel.INFO.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Unable to collect vsp component nics : " 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 6569312f02..eed566de43 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 @@ -20,15 +20,13 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; -import org.openecomp.sdc.activityLog.ActivityLogManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.MonitoringUploadsManager; 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(), - ActivityLogManagerFactory.getInstance().createInterface()); + new MonitoringUploadsManagerImpl(MonitoringUploadDaoFactory.getInstance().createInterface()); @Override public MonitoringUploadsManager createInterface() { 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 0f4d73f8c5..bcfdefbd0c 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 @@ -26,8 +26,6 @@ import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; -import org.openecomp.sdc.activityLog.ActivityLogManager; -import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.common.utils.CommonUtil; @@ -45,7 +43,6 @@ import org.openecomp.sdc.logging.types.LoggerTragetServiceName; import org.openecomp.sdc.vendorsoftwareproduct.MonitoringUploadsManager; import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.errors.MonitoringUploadErrorBuilder; @@ -53,7 +50,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.MonitoringU import org.openecomp.sdc.vendorsoftwareproduct.utils.VendorSoftwareProductUtils; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.errors.VersionableSubEntityNotFoundErrorBuilder; -import org.openecomp.sdcrests.activitylog.types.ActivityType; import java.io.IOException; import java.io.InputStream; @@ -67,26 +63,20 @@ import java.util.Optional; public class MonitoringUploadsManagerImpl implements MonitoringUploadsManager { private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private ActivityLogManager activityLogManager; private ComponentArtifactDao componentArtifactDao; - private VendorSoftwareProductDao vendorSoftwareProductDao; private static final Logger logger = LoggerFactory.getLogger(VendorSoftwareProductManagerImpl.class); - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); - - MonitoringUploadsManagerImpl(ComponentArtifactDao componentArtifactDao, - ActivityLogManager activityLogManager) { + MonitoringUploadsManagerImpl(ComponentArtifactDao componentArtifactDao) { this.componentArtifactDao = componentArtifactDao; - this.activityLogManager = activityLogManager; componentArtifactDao.registerVersioning( VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE); } @Override public void delete(String vspId, Version version, String componentId, - MonitoringUploadType monitoringUploadType, String user) { + MonitoringUploadType monitoringUploadType) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); ComponentMonitoringUploadEntity componentMonitoringUploadEntity = @@ -112,8 +102,7 @@ public class MonitoringUploadsManagerImpl implements MonitoringUploadsManager { @Override public void upload(InputStream object, String filename, String vspId, Version version, String componentId, - MonitoringUploadType type, - String user) { + MonitoringUploadType type) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); if (object == null) { @@ -130,7 +119,7 @@ public class MonitoringUploadsManagerImpl implements MonitoringUploadsManager { final FileContentHandler upload = validateZip(vspId, version, uploadedFileData, errors); if (type.equals(MonitoringUploadType.VES_EVENTS)) { - validateVesEventUpload(upload, errors, vspId, version); + validateVesEventUpload(upload, errors); } if (MapUtils.isNotEmpty(errors)) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, @@ -147,27 +136,18 @@ public class MonitoringUploadsManagerImpl implements MonitoringUploadsManager { uploadedFileData); } catch (Exception exception) { - log.debug("", exception); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.UPLOAD_MONITORING_FILE, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid " + type.toString() + "zip file"); throw new CoreException(new MonitoringUploadErrorBuilder(exception.getMessage()).build()); } } - - ActivityLogEntity activityLogEntity = - new ActivityLogEntity(vspId, String.valueOf(version.getMajor() + 1), - ActivityType.UPLOAD_MONITORING_FILE.toString(), user, true, "", ""); - activityLogManager.addActionLog(activityLogEntity, user); logger.audit("Uploaded Monitoring File for component id:" + componentId + " ,vspId:" + vspId); - - mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); } private void validateVesEventUpload(FileContentHandler upload, - Map> errors, String vspId, - Version version) { + Map> errors) { if (!CommonUtil.validateAllFilesYml(upload)) { ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.UPLOAD_FILE, errors) .add(new ErrorMessage(ErrorLevel.ERROR, @@ -194,8 +174,7 @@ public class MonitoringUploadsManagerImpl implements MonitoringUploadsManager { } @Override - public MonitoringUploadStatus listFilenames(String vspId, Version version, String componentId, - String user) { + public MonitoringUploadStatus listFilenames(String vspId, Version version, String componentId) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); ComponentMonitoringUploadEntity current = @@ -259,10 +238,10 @@ public class MonitoringUploadsManagerImpl implements MonitoringUploadsManager { Map> errors) { FileContentHandler contentMap; try { - contentMap = CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, uploadedFileData); + contentMap = + CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, uploadedFileData); VendorSoftwareProductUtils.validateContentZipData(contentMap, errors); } catch (IOException exception) { - log.debug("", exception); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.VALIDATE_MONITORING_FILE, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid Monitoring zip file"); 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 77b6b0039e..e6233bb79c 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 @@ -59,7 +59,7 @@ public class NetworkManagerImpl implements NetworkManager { } @Override - public Collection listNetworks(String vspId, Version version, String user) { + public Collection listNetworks(String vspId, Version version) { mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); mdcDataDebugMessage.debugExitMessage("VSP id", vspId); @@ -67,7 +67,7 @@ public class NetworkManagerImpl implements NetworkManager { } @Override - public NetworkEntity createNetwork(NetworkEntity network, String user) { + public NetworkEntity createNetwork(NetworkEntity network) { mdcDataDebugMessage.debugEntryMessage("VSP id", network.getVspId()); if (!isManual(network.getVspId(), network.getVersion())) { @@ -87,16 +87,12 @@ public class NetworkManagerImpl implements NetworkManager { return null; } - private NetworkEntity createNetwork(NetworkEntity network) { - return compositionEntityDataManager.createNetwork(network); - } - @Override - public CompositionEntityValidationData updateNetwork(NetworkEntity network, String user) { + public CompositionEntityValidationData updateNetwork(NetworkEntity network) { mdcDataDebugMessage .debugEntryMessage("VSP id, network id", network.getVspId(), network.getId()); - NetworkEntity retrieved = getNetwork(network.getVspId(), network.getVersion(), network.getId()); + NetworkEntity retrieved = getValidatedNetwork(network.getVspId(), network.getVersion(), network.getId()); NetworkCompositionSchemaInput schemaInput = new NetworkCompositionSchemaInput(); schemaInput.setManual(isManual(network.getVspId(), network.getVersion())); @@ -119,10 +115,10 @@ public class NetworkManagerImpl implements NetworkManager { @Override public CompositionEntityResponse getNetwork(String vspId, Version version, - String networkId, String user) { + String networkId) { mdcDataDebugMessage.debugEntryMessage("VSP id, network id", vspId, networkId); - NetworkEntity networkEntity = getNetwork(vspId, version, networkId); + NetworkEntity networkEntity = getValidatedNetwork(vspId, version, networkId); Network network = networkEntity.getNetworkCompositionData(); NetworkCompositionSchemaInput schemaInput = new NetworkCompositionSchemaInput(); @@ -140,7 +136,7 @@ public class NetworkManagerImpl implements NetworkManager { } - private NetworkEntity getNetwork(String vspId, Version version, String networkId) { + 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); @@ -148,7 +144,7 @@ public class NetworkManagerImpl implements NetworkManager { } @Override - public void deleteNetwork(String vspId, Version version, String networkId, String user) { + public void deleteNetwork(String vspId, Version version, String networkId) { mdcDataDebugMessage.debugEntryMessage("VSP id, network id", vspId, networkId); if (!isManual(vspId, version)) { 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 0304353113..f2bb0baf95 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 @@ -37,7 +37,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.composition.CompositionEntityDataManager; import org.openecomp.sdc.vendorsoftwareproduct.services.schemagenerator.SchemaGenerator; import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; @@ -63,7 +68,7 @@ public class NicManagerImpl implements NicManager { private NicDao nicDao; private CompositionEntityDataManager compositionEntityDataManager; private NetworkManager networkManager; - private VendorSoftwareProductInfoDao vspInfoDao; + private VendorSoftwareProductInfoDao vspInfoDao; public NicManagerImpl(NicDao nicDao, CompositionEntityDataManager compositionEntityDataManager, @@ -76,14 +81,13 @@ public class NicManagerImpl implements NicManager { } @Override - public Collection listNics(String vspId, Version version, String componentId, - String user) { + public Collection listNics(String vspId, Version version, String componentId) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); Collection nics = nicDao.list(new NicEntity(vspId, version, componentId, null)); if (!nics.isEmpty()) { - Map networksNameById = listNetworksNameById(vspId, version, user); + Map networksNameById = listNetworksNameById(vspId, version); nics.forEach(nicEntity -> { Nic nic = nicEntity.getNicCompositionData(); nic.setNetworkName(networksNameById.get(nic.getNetworkId())); @@ -96,18 +100,18 @@ public class NicManagerImpl implements NicManager { return nics; } - private Map listNetworksNameById(String vspId, Version version, String user) { - Collection networks = networkManager.listNetworks(vspId, version, user); + 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, String user) { - NicEntity createdNic = null; + public NicEntity createNic(NicEntity nic) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id", nic.getVspId(), nic.getComponentId()); + NicEntity createdNic; if (!vspInfoDao.isManual(nic.getVspId(), nic.getVersion())) { ErrorCode onboardingMethodUpdateErrorCode = NotSupportedHeatOnboardMethodErrorBuilder .getAddNicNotSupportedHeatOnboardMethodErrorBuilder(); @@ -117,25 +121,20 @@ public class NicManagerImpl implements NicManager { onboardingMethodUpdateErrorCode.message()); throw new CoreException(onboardingMethodUpdateErrorCode); } else { - validateNic(nic, user); - createdNic = createNic(nic); + validateNic(nic); + createdNic = compositionEntityDataManager.createNic(nic); } - //nicDao.updateVspLatestModificationTime(nic.getVspId(), nic.getVersion()); - mdcDataDebugMessage .debugExitMessage("VSP id, component id", nic.getVspId(), nic.getComponentId()); return createdNic; } - private NicEntity createNic(NicEntity nic) { - return compositionEntityDataManager.createNic(nic); - } - private void validateNic(NicEntity nic, String user) { + private void validateNic(NicEntity nic) { Collection listNics = listNics(nic.getVspId(), nic.getVersion(), nic - .getComponentId(), user); + .getComponentId()); String networkId = nic.getNicCompositionData().getNetworkId(); NetworkType networkType = nic.getNicCompositionData().getNetworkType(); String networkDescription = nic.getNicCompositionData().getNetworkDescription(); @@ -171,14 +170,12 @@ public class NicManagerImpl implements NicManager { if (!(networkId == null || networkId.equals(""))) { //NetworkEntity ne = getNetwork(nic.getVspId(), activeVersion, networkId); final CompositionEntityResponse network = - networkManager.getNetwork(nic.getVspId(), nic.getVersion(), networkId, - user); + networkManager.getNetwork(nic.getVspId(), nic.getVersion(), networkId); } if (!(networkDescription == null || networkDescription.equals(""))) { final ErrorCode nicNetworkDescriptionErrorBuilder = - new NicInternalNetworkErrorBuilder() - .getNetworkDescriptionInternalNetworkErrorBuilder(); + NicInternalNetworkErrorBuilder.getNetworkDescriptionInternalNetworkErrorBuilder(); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.CREATE_NIC, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), nicNetworkDescriptionErrorBuilder.message()); @@ -200,17 +197,17 @@ public class NicManagerImpl implements NicManager { @Override public CompositionEntityResponse getNic(String vspId, Version version, String componentId, - String nicId, String user) { + String nicId) { mdcDataDebugMessage .debugEntryMessage("VSP id, component id, nic id", vspId, componentId, nicId); - NicEntity nicEntity = getNic(vspId, version, componentId, 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, user); + Map networksNameById = listNetworksNameById(vspId, version); nic.setNetworkName(networksNameById.get(nic.getNetworkId())); schemaInput.setNetworkIds(networksNameById.keySet()); @@ -226,7 +223,8 @@ public class NicManagerImpl implements NicManager { } - private NicEntity getNic(String vspId, Version version, String componentId, String nicId) { + 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), @@ -235,14 +233,13 @@ public class NicManagerImpl implements NicManager { } @Override - public void deleteNic(String vspId, Version version, String componentId, String nicId, - String user) { + public void deleteNic(String vspId, Version version, String componentId, String nicId) { mdcDataDebugMessage .debugEntryMessage("VSP id, component id", vspId, componentId, nicId); if (!vspInfoDao.isManual(vspId, version)) { final ErrorCode deleteNicErrorBuilder = - new DeleteNicErrorBuilder().getDeleteNicForHeatOnboardedVspErrorBuilder(); + DeleteNicErrorBuilder.getDeleteNicForHeatOnboardedVspErrorBuilder(); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.DELETE_NIC, ErrorLevel.ERROR.name(), LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), @@ -250,23 +247,21 @@ public class NicManagerImpl implements NicManager { throw new CoreException(deleteNicErrorBuilder); } - NicEntity nicEntity = getNic(vspId, version, componentId, nicId); - if (nicEntity != null) { - nicDao.delete(nicEntity); - } + NicEntity nicEntity = getValidatedNic(vspId, version, componentId, nicId); + nicDao.delete(nicEntity); mdcDataDebugMessage .debugExitMessage("VSP id, component id", vspId, componentId, nicId); } @Override - public CompositionEntityValidationData updateNic(NicEntity nic, String user) { + public CompositionEntityValidationData updateNic(NicEntity nic) { mdcDataDebugMessage .debugEntryMessage("VSP id, component id", nic.getVspId(), nic.getComponentId(), nic.getId()); NicEntity retrieved = - getNic(nic.getVspId(), nic.getVersion(), nic.getComponentId(), nic.getId()); + getValidatedNic(nic.getVspId(), nic.getVersion(), nic.getComponentId(), nic.getId()); NicCompositionSchemaInput schemaInput = new NicCompositionSchemaInput(); schemaInput.setManual(vspInfoDao.isManual(nic.getVspId(), nic.getVersion())); @@ -289,9 +284,6 @@ public class NicManagerImpl implements NicManager { if (CollectionUtils.isEmpty(validationData.getErrors())) { nicDao.update(nic); } - - //nicDao.updateVspLatestModificationTime(nic.getVspId(), nic.getVersion()); - mdcDataDebugMessage .debugExitMessage("VSP id, component id", nic.getVspId(), nic.getComponentId(), nic.getId()); @@ -301,7 +293,7 @@ public class NicManagerImpl implements NicManager { @Override public QuestionnaireResponse getNicQuestionnaire(String vspId, Version version, - String componentId, String nicId, String user) { + String componentId, String nicId) { mdcDataDebugMessage .debugEntryMessage("VSP id, component id", vspId, componentId, nicId); @@ -321,15 +313,13 @@ public class NicManagerImpl implements NicManager { @Override public void updateNicQuestionnaire(String vspId, Version version, String componentId, - String nicId, String questionnaireData, String user) { + String nicId, String questionnaireData) { mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId, nicId); getNic(vspId, version, componentId, nicId); nicDao.updateQuestionnaireData(vspId, version, componentId, nicId, questionnaireData); - //nicDao.updateVspLatestModificationTime(vspId, version); - mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId, nicId); } @@ -342,9 +332,4 @@ public class NicManagerImpl implements NicManager { return SchemaGenerator .generate(SchemaTemplateContext.composition, CompositionEntityType.nic, schemaInput); } - // todo *************************** move to reusable place! ************************* - - /*private boolean isManual(String vspId, Version version) { - return false; - }*/ } 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 b5464e5708..b8fddcd075 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 @@ -20,40 +20,21 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; -import org.openecomp.core.model.dao.ServiceModelDaoFactory; -import org.openecomp.sdc.activityLog.ActivityLogManagerFactory; import org.openecomp.sdc.healing.factory.HealingManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager; import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.MonitoringUploadDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.factory.CandidateServiceFactory; -import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionDataExtractorFactory; -import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionEntityDataManagerFactory; public class OrchestrationTemplateCandidateManagerFactoryImpl extends OrchestrationTemplateCandidateManagerFactory { + private static final OrchestrationTemplateCandidateManager INSTANCE = new OrchestrationTemplateCandidateManagerImpl( - VendorSoftwareProductDaoFactory.getInstance().createInterface(), VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), - OrchestrationTemplateDaoFactory.getInstance().createInterface(), CandidateServiceFactory.getInstance().createInterface(), - HealingManagerFactory.getInstance().createInterface(), - CompositionDataExtractorFactory.getInstance().createInterface(), - ServiceModelDaoFactory.getInstance().createInterface(), - CompositionEntityDataManagerFactory.getInstance().createInterface(), - NicDaoFactory.getInstance().createInterface(), - ComponentDaoFactory.getInstance().createInterface(), - MonitoringUploadDaoFactory.getInstance().createInterface(), - ProcessDaoFactory.getInstance().createInterface(), - ActivityLogManagerFactory.getInstance().createInterface()); - + HealingManagerFactory.getInstance().createInterface() + ); @Override public OrchestrationTemplateCandidateManager createInterface() { 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 07a3fa7f2c..f613dbb54f 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 @@ -23,11 +23,8 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; -import org.openecomp.core.model.dao.ServiceModelDao; -import org.openecomp.core.model.types.ServiceElement; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; -import org.openecomp.sdc.activityLog.ActivityLogManager; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.common.utils.CommonUtil; @@ -35,7 +32,6 @@ import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.healing.api.HealingManager; -import org.openecomp.sdc.healing.types.HealCode; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.api.annotations.Metrics; @@ -43,14 +39,7 @@ import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.messages.AuditMessages; import org.openecomp.sdc.logging.types.LoggerServiceName; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; -import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; @@ -58,9 +47,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.errors.OrchestrationTemplateNotFo import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationTemplateFileHandler; import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUploadFactory; import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process.OrchestrationProcessFactory; -import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process.OrchestrationTemplateProcessHandler; -import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor; -import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager; import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService; import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; @@ -80,114 +66,52 @@ public class OrchestrationTemplateCandidateManagerImpl private static final Logger logger = LoggerFactory.getLogger(OrchestrationTemplateCandidateManagerImpl.class); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private VendorSoftwareProductDao vendorSoftwareProductDao; + private VendorSoftwareProductInfoDao vspInfoDao; - private OrchestrationTemplateDao orchestrationTemplateDataDao; private CandidateService candidateService; private HealingManager healingManager; - private CompositionDataExtractor compositionDataExtractor; - private ServiceModelDao serviceModelDao; - private CompositionEntityDataManager compositionEntityDataManager; - private NicDao nicDao; - private ComponentDao componentDao; - private ComponentArtifactDao componentArtifactDao; - private ActivityLogManager activityLogManager; - private ProcessDao processDao; - - /** - * Instantiates a new Orchestration template candidate manager. - * - * @param vendorSoftwareProductDao the vendor software product dao - * @param vspInfoDao the vsp info dao - * @param orchestrationTemplateDataDao the orchestration template data dao - * @param candidateService the candidate service - * @param healingManager the healing manager - * @param compositionDataExtractor the composition data extractor - * @param serviceModelDao the service model dao - * @param compositionEntityDataManager the composition entity data manager - * @param nicDao the nic dao - * @param componentDao the component dao - * @param componentArtifactDao the mib dao - * @param processDao the process dao - * @param activityLogManager the activity log manager - */ - public OrchestrationTemplateCandidateManagerImpl( - VendorSoftwareProductDao vendorSoftwareProductDao, VendorSoftwareProductInfoDao - vspInfoDao, - OrchestrationTemplateDao orchestrationTemplateDataDao, - CandidateService candidateService, HealingManager healingManager, - CompositionDataExtractor compositionDataExtractor, - ServiceModelDao serviceModelDao, - CompositionEntityDataManager compositionEntityDataManager, - NicDao nicDao, - ComponentDao componentDao, - ComponentArtifactDao componentArtifactDao, - ProcessDao processDao, - ActivityLogManager activityLogManager) { - this.vendorSoftwareProductDao = vendorSoftwareProductDao; + + public OrchestrationTemplateCandidateManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, + CandidateService candidateService, + HealingManager healingManager) { this.vspInfoDao = vspInfoDao; - this.orchestrationTemplateDataDao = orchestrationTemplateDataDao; this.candidateService = candidateService; this.healingManager = healingManager; - this.compositionDataExtractor = compositionDataExtractor; - this.serviceModelDao = serviceModelDao; - this.compositionEntityDataManager = compositionEntityDataManager; - this.nicDao = nicDao; - this.componentDao = componentDao; - this.componentArtifactDao = componentArtifactDao; - this.processDao = processDao; - this.activityLogManager = activityLogManager; } @Override @Metrics public UploadFileResponse upload(String vspId, Version version, InputStream fileToUpload, - String user, String filePrefix, - String networkPackageName) { + String fileSuffix, String networkPackageName) { mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + OrchestrationTemplateFileHandler orchestrationTemplateFileHandler = - OrchestrationUploadFactory.createOrchestrationTemplateFileHandler(filePrefix); + OrchestrationUploadFactory.createOrchestrationTemplateFileHandler(fileSuffix); + VspDetails vspDetails = getVspDetails(vspId, version); + UploadFileResponse uploadResponse = orchestrationTemplateFileHandler - .upload(vspId, version, fileToUpload, user, candidateService, - vspDetails); - vspDetails.setOnboardingOrigin(filePrefix); - vspDetails.setNetworkPackageName(networkPackageName); - vspInfoDao.update(vspDetails); + .upload(vspDetails, fileToUpload, fileSuffix, networkPackageName, candidateService); uploadResponse.setNetworkPackageName(networkPackageName); return uploadResponse; } - - @Override - public OrchestrationTemplateActionResponse process(String vspId, - Version version, String user) { + public OrchestrationTemplateActionResponse process(String vspId, Version version) { mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); - OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse(); - - Optional candidate = - fetchCandidateDataEntity(vspId, version); - if (!candidate.isPresent()) { - throw new CoreException(new OrchestrationTemplateNotFoundErrorBuilder(vspId).build()); - } - VspDetails vspDetails = - getVspDetails(vspId, version); - Optional processInstance = - OrchestrationProcessFactory.getInstance(vspDetails.getOnboardingOrigin()); + OrchestrationTemplateCandidateData candidate = fetchCandidateDataEntity(vspId, version) + .orElseThrow( + () -> new CoreException(new OrchestrationTemplateNotFoundErrorBuilder(vspId).build())); - if(processInstance.isPresent()){ - response = processInstance.get().process(vspDetails, candidate.get(), user); - } - - return response; + return OrchestrationProcessFactory.getInstance(candidate.getFileSuffix()) + .map(processor -> processor.process(getVspDetails(vspId, version), candidate)) + .orElse(new OrchestrationTemplateActionResponse()); } @Override - public Optional getFilesDataStructure( - String vspId, Version version, String user) { + public Optional getFilesDataStructure(String vspId, Version version) { mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); Optional candidateFileDataStructure = @@ -195,19 +119,13 @@ public class OrchestrationTemplateCandidateManagerImpl if (candidateFileDataStructure.isPresent()) { return candidateFileDataStructure; } else { - Map healingParams = getHealingParamsAsMap(vspId, version, user); - - mdcDataDebugMessage - .debugExitMessage("VSP id", vspId); - return (Optional) healingManager - .heal(HealCode.FILE_DATA_STRUCTURE_HEALER, healingParams); + mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + return Optional.empty(); } } @Override - - public ValidationResponse updateFilesDataStructure(String vspId, - Version version, String user, + public ValidationResponse updateFilesDataStructure(String vspId, Version version, FilesDataStructure fileDataStructure) { mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); @@ -222,27 +140,23 @@ public class OrchestrationTemplateCandidateManagerImpl response.setUploadDataErrors(errorsMap, LoggerServiceName.Update_Manifest, LoggerTragetServiceName.VALIDATE_FILE_DATA_STRUCTURE); - mdcDataDebugMessage - .debugExitMessage("VSP id", vspId); + mdcDataDebugMessage.debugExitMessage("VSP id", vspId); return response; } } - candidateService.updateOrchestrationTemplateCandidateFileDataStructure(vspId, version, - fileDataStructure); + candidateService + .updateOrchestrationTemplateCandidateFileDataStructure(vspId, version, fileDataStructure); - mdcDataDebugMessage - .debugExitMessage("VSP id", vspId); + mdcDataDebugMessage.debugExitMessage("VSP id", vspId); return response; } @Override - public Optional> get(String vspId, Version version, String user) - throws IOException { + public Optional> get(String vspId, Version version) throws IOException { mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); - VspDetails vspDetails = - getVspDetails(vspId, version); + VspDetails vspDetails = getVspDetails(vspId, version); Optional candidateDataEntity = fetchCandidateDataEntity(vspId, version); @@ -252,31 +166,34 @@ public class OrchestrationTemplateCandidateManagerImpl Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage()); logger.error(errorMessage.getMessage()); - mdcDataDebugMessage - .debugExitMessage("VSP id", vspId); + mdcDataDebugMessage.debugExitMessage("VSP id", vspId); return Optional.empty(); } OnboardingTypesEnum type = - OnboardingTypesEnum.getOnboardingTypesEnum(vspDetails.getOnboardingOrigin()); + OnboardingTypesEnum.getOnboardingTypesEnum(candidateDataEntity.get().getFileSuffix()); - if(CommonUtil.isFileOriginFromZip(vspDetails.getOnboardingOrigin())) { + if (CommonUtil.isFileOriginFromZip(candidateDataEntity.get().getFileSuffix())) { FilesDataStructure structure = JsonUtil .json2Object(candidateDataEntity.get().getFilesDataStructure(), FilesDataStructure.class); String manifest = candidateService.createManifest(vspDetails, structure); - mdcDataDebugMessage - .debugExitMessage("VSP id", vspId); + mdcDataDebugMessage.debugExitMessage("VSP id", vspId); return Optional.of( - new ImmutablePair<>(OnboardingTypesEnum.ZIP.toString(),candidateService + new ImmutablePair<>(OnboardingTypesEnum.ZIP.toString(), candidateService .replaceManifestInZip(candidateDataEntity.get().getContentData(), - manifest, vspId, type))); + manifest, vspId, type))); } return Optional.of( - new ImmutablePair<>(vspDetails.getOnboardingOrigin(),candidateDataEntity.get() + new ImmutablePair<>(candidateDataEntity.get().getFileSuffix(), candidateDataEntity.get() .getContentData().array())); } + @Override + public OrchestrationTemplateCandidateData getInfo(String vspId, Version version) { + return candidateService.getOrchestrationTemplateCandidateInfo(vspId, version); + } + private Optional fetchCandidateDataEntity( String vspId, Version version) { return Optional @@ -286,19 +203,22 @@ public class OrchestrationTemplateCandidateManagerImpl // todo *************************** move to reusable place! ************************* - private Map getHealingParamsAsMap(String vspId, Version version, String user) { + private Map getHealingParamsAsMap(String vspId, Version version) { Map healingParams = new HashMap<>(); healingParams.put(SdcCommon.VSP_ID, vspId); healingParams.put(SdcCommon.VERSION, version); - healingParams.put(SdcCommon.USER, user); return healingParams; } private VspDetails getVspDetails(String vspId, Version version) { VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); - vspDetails.setValidationData(orchestrationTemplateDataDao.getValidationData(vspId, version)); +/* OrchestrationTemplateEntity orchestrationTemplateInfo = + orchestrationTemplateDao.getInfo(vspId, version); + vspDetails.setValidationData(orchestrationTemplateInfo.getValidationData()); + vspDetails.setNetworkPackageName(orchestrationTemplateInfo.getFileName()); + vspDetails.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix());*/ return vspDetails; } 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 d870454de7..7a4e4876d2 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 @@ -20,16 +20,13 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; -import org.openecomp.sdc.activityLog.ActivityLogManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.ProcessManager; import org.openecomp.sdc.vendorsoftwareproduct.ProcessManagerFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; public class ProcessManagerFactoryImpl extends ProcessManagerFactory { private static final ProcessManager INSTANCE = - new ProcessManagerImpl( - VendorSoftwareProductDaoFactory.getInstance().createInterface(), - ActivityLogManagerFactory.getInstance().createInterface()); + new ProcessManagerImpl(ProcessDaoFactory.getInstance().createInterface()); @Override public ProcessManager createInterface() { 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 a3d0286019..121abda1ee 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 @@ -22,12 +22,10 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.core.util.UniqueValueUtil; import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.sdc.activityLog.ActivityLogManager; -import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; @@ -35,138 +33,133 @@ import org.openecomp.sdc.logging.types.LoggerErrorCode; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; import org.openecomp.sdc.vendorsoftwareproduct.ProcessManager; import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.errors.UploadInvalidErrorBuilder; import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdcrests.activitylog.types.ActivityType; +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 MdcDataDebugMessage MDC_DATA_DEBUG_MESSAGE = new MdcDataDebugMessage(); - private final ActivityLogManager activityLogManager; + 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 VendorSoftwareProductDao vendorSoftwareProductDao; + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); + private ProcessDao processDao; - public ProcessManagerImpl(VendorSoftwareProductDao vendorSoftwareProductDao, ActivityLogManager activityLogManager) { - this.vendorSoftwareProductDao = vendorSoftwareProductDao; - this.activityLogManager = activityLogManager; + public ProcessManagerImpl(ProcessDao processDao) { + this.processDao = processDao; } @Override public Collection listProcesses(String vspId, Version version, - String componentId, - String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); + String componentId) { + mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); + mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); - return vendorSoftwareProductDao.listProcesses(vspId, version, componentId); + return processDao.list(new ProcessEntity(vspId, version, componentId, null)); } @Override - public void deleteProcesses(String vspId, Version version, String componentId, String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); + public void deleteProcesses(String vspId, Version version, String componentId) { + mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); - Collection processes = - vendorSoftwareProductDao.listProcesses(vspId, version, 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()); } + } - vendorSoftwareProductDao.deleteProcesses(vspId, version, componentId); + if (componentId == null) { + processDao.deleteVspAll(vspId,version); + } else { + processDao.deleteAll(allProcesses); } - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); + + mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); } @Override - public ProcessEntity createProcess(ProcessEntity process, String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", process.getId(), + public ProcessEntity createProcess(ProcessEntity process) { + mdcDataDebugMessage.debugEntryMessage("VSP id, component id", process.getId(), process.getComponentId()); validateUniqueName(process.getVspId(), process.getVersion(), process.getComponentId(), process.getName()); - //process.setId(CommonMethods.nextUuId()); - vendorSoftwareProductDao.createProcess(process); + processDao.create(process); createUniqueName(process.getVspId(), process.getVersion(), process.getComponentId(), process.getName()); - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", process.getId(), + mdcDataDebugMessage.debugExitMessage("VSP id, component id", process.getId(), process.getComponentId()); return process; } - @Override public ProcessEntity getProcess(String vspId, Version version, String componentId, - String processId, String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); + String processId) { + mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); ProcessEntity retrieved = - vendorSoftwareProductDao.getProcess(vspId, version, componentId, processId); + processDao.get(new ProcessEntity(vspId, version, componentId, processId)); validateProcessExistence(vspId, version, componentId, processId, retrieved); - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); + mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); return retrieved; } @Override - public void updateProcess(ProcessEntity process, String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", process.getId(), + public void updateProcess(ProcessEntity process) { + mdcDataDebugMessage.debugEntryMessage("VSP id, component id", process.getId(), process.getComponentId()); - ProcessEntity retrieved = vendorSoftwareProductDao - .getProcess(process.getVspId(), process.getVersion(), process.getComponentId(), - process.getId()); + 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()); - vendorSoftwareProductDao.updateProcess(process); + processDao.update(process); - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", process.getId(), + mdcDataDebugMessage.debugExitMessage("VSP id, component id", process.getId(), process.getComponentId()); } @Override - public void deleteProcess(String vspId, Version version, String componentId, String processId, - String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); + public void deleteProcess(String vspId, Version version, String componentId, String processId) { + mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); - ProcessEntity retrieved = - vendorSoftwareProductDao.getProcess(vspId, version, componentId, processId); - validateProcessExistence(vspId, version, componentId, processId, retrieved); + ProcessEntity retrieved = getProcess(vspId, version, componentId, processId); - vendorSoftwareProductDao.deleteProcess(vspId, version, componentId, processId); + processDao.delete(retrieved); deleteUniqueValue(retrieved.getVspId(), retrieved.getVersion(), retrieved.getComponentId(), retrieved.getName()); - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); + mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); } @Override public File getProcessArtifact(String vspId, Version version, String componentId, - String processId, String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); + String processId) { + mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); - ProcessEntity retrieved = - vendorSoftwareProductDao.getProcessArtifact(vspId, version, componentId, processId); - validateProcessArtifactExistence(vspId, version, componentId, processId, retrieved); + 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)) { @@ -175,125 +168,115 @@ public class ProcessManagerImpl implements ProcessManager { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.GET_PROCESS_ARTIFACT, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Can't get process artifact"); - throw new CoreException(new UploadInvalidErrorBuilder().build(), exception); + throw new CoreException(new UploadInvalidErrorBuilder().build()); } - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); + mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); return file; } @Override public void deleteProcessArtifact(String vspId, Version version, String componentId, - String processId, String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); + String processId) { + mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); - ProcessEntity retrieved = - vendorSoftwareProductDao.getProcessArtifact(vspId, version, componentId, processId); - validateProcessArtifactExistence(vspId, version, componentId, processId, retrieved); + ProcessEntity retrieved = getValidatedProcessArtifact(vspId, version, componentId, processId); - vendorSoftwareProductDao.deleteProcessArtifact(vspId, version, componentId, processId); + processDao.deleteArtifact(retrieved); - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); + mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); } @Override public void uploadProcessArtifact(InputStream artifactFile, String artifactFileName, String vspId, - Version version, String componentId, String processId, - String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); + Version version, String componentId, String processId) { + mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); + + ProcessEntity process = getProcess(vspId, version, componentId, processId); + process.setArtifactName(artifactFileName); + process.setArtifact(readArtifact(artifactFile)); + processDao.uploadArtifact(process); + mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); + } + + private ProcessEntity getValidatedProcessArtifact(String vspId, Version version, + String componentId, String processId) { ProcessEntity retrieved = - vendorSoftwareProductDao.getProcess(vspId, version, componentId, processId); - validateProcessExistence(vspId, version, componentId, processId, retrieved); + processDao.getArtifact(new ProcessEntity(vspId, version, componentId, processId)); + validateProcessArtifactExistence(vspId, version, componentId, processId, retrieved); + return retrieved; + } - if (artifactFile == null) { + private ByteBuffer readArtifact(InputStream artifactInputStream) { + if (artifactInputStream == null) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.UPLOAD_PROCESS_ARTIFACT, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Can't upload process artifact"); throw new CoreException(new UploadInvalidErrorBuilder().build()); } - - byte[] artifact; try { - artifact = FileUtils.toByteArray(artifactFile); + return ByteBuffer.wrap(FileUtils.toByteArray(artifactInputStream)); } catch (RuntimeException exception) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.UPLOAD_PROCESS_ARTIFACT, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Can't upload process artifact"); - throw new CoreException(new UploadInvalidErrorBuilder().build(), exception); + throw new CoreException(new UploadInvalidErrorBuilder().build()); } - - vendorSoftwareProductDao.uploadProcessArtifact(vspId, version, componentId, processId, artifact, - artifactFileName); - ActivityLogEntity activityLogEntity = new ActivityLogEntity(vspId, String.valueOf(version.getMajor()+1), - ActivityType.UPLOAD_MONITORING_FILE.toString(), user, true, "", ""); - activityLogManager.addActionLog(activityLogEntity, user); - - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); } private void validateProcessExistence(String vspId, Version version, String componentId, String processId, ProcessEntity retrieved) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id, process id", vspId, componentId, - processId); - - if (retrieved != null) { - return; - } VersioningUtil.validateEntityExistence(retrieved, new ProcessEntity(vspId, version, componentId, processId), - VspDetails.ENTITY_TYPE);//todo retrieved is always null ?? - - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id, process id", vspId, componentId, - processId); + VspDetails.ENTITY_TYPE); } private void validateProcessArtifactExistence(String vspId, Version version, String componentId, String processId, ProcessEntity retrieved) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id, process id", vspId, componentId, - processId); - - if (retrieved != null) { - VersioningUtil.validateEntityExistence(retrieved.getArtifact(), - new ProcessEntity(vspId, version, componentId, processId), - VspDetails.ENTITY_TYPE); - } else { - VersioningUtil.validateEntityExistence(retrieved, - new ProcessEntity(vspId, version, componentId, processId), - VspDetails.ENTITY_TYPE); //todo retrieved is always null ?? + 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() + .withCategory(ErrorCategory.APPLICATION) + .withId(VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND) + .withMessage(String.format(PROCESS_ARTIFACT_NOT_EXIST_MSG, + processId, VspDetails.ENTITY_TYPE, vspId, version)).build()); } - - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id, process id", vspId, componentId, - processId); } protected void validateUniqueName(String vspId, Version version, String componentId, String processName) { UniqueValueUtil.validateUniqueValue(VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME, - vspId, version.toString(), componentId, processName); + vspId, version.getId(), componentId, processName); } protected void createUniqueName(String vspId, Version version, String componentId, String processName) { UniqueValueUtil .createUniqueValue(VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME, vspId, - version.toString(), componentId, processName); + 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.toString(), componentId); + 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.toString(), componentId, processName); + 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 d4879da8d7..640d5c00c7 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 @@ -34,18 +34,12 @@ import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.core.validation.api.ValidationManager; import org.openecomp.core.validation.util.MessageContainerUtil; -import org.openecomp.sdc.activityLog.ActivityLogManager; -import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.common.errors.ValidationErrorBuilder; import org.openecomp.sdc.common.utils.CommonUtil; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; -import org.openecomp.sdc.generator.datatypes.tosca.VspModelInfo; -import org.openecomp.sdc.healing.api.HealingManager; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; @@ -63,11 +57,14 @@ import org.openecomp.sdc.vendorlicense.licenseartifacts.VendorLicenseArtifactsSe import org.openecomp.sdc.vendorsoftwareproduct.ManualVspToscaManager; import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants; import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.errors.VendorSoftwareProductNotFoundErrorBuilder; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; @@ -76,18 +73,17 @@ 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.OnboardingMethod; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspQuestionnaireEntity; import org.openecomp.sdc.vendorsoftwareproduct.errors.ComponentDependencyModelErrorBuilder; import org.openecomp.sdc.vendorsoftwareproduct.errors.ComponentErrorBuilder; -import org.openecomp.sdc.vendorsoftwareproduct.errors.CreatePackageForNonFinalVendorSoftwareProductErrorBuilder; import org.openecomp.sdc.vendorsoftwareproduct.errors.DeploymentFlavorErrorBuilder; import org.openecomp.sdc.vendorsoftwareproduct.errors.FileCreationErrorBuilder; import org.openecomp.sdc.vendorsoftwareproduct.errors.InformationArtifactCreationErrorBuilder; import org.openecomp.sdc.vendorsoftwareproduct.errors.NicInternalNetworkErrorBuilder; -import org.openecomp.sdc.vendorsoftwareproduct.errors.OnboardingMethodErrorBuilder; import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageInvalidErrorBuilder; import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageNotFoundErrorBuilder; import org.openecomp.sdc.vendorsoftwareproduct.errors.TranslationFileCreationErrorBuilder; @@ -99,7 +95,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.services.schemagenerator.SchemaGe import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireValidationResult; import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse; -import org.openecomp.sdc.vendorsoftwareproduct.types.VersionedVendorSoftwareProductInfo; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentComputeAssociation; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityId; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityType; @@ -111,15 +106,8 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.ComponentQu import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateContext; import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateInput; import org.openecomp.sdc.vendorsoftwareproduct.utils.ComponentDependencyTracker; -import org.openecomp.sdc.versioning.VersioningManager; import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionStatus; -import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; -import org.openecomp.sdcrests.activitylog.types.ActivityType; -import org.slf4j.MDC; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; @@ -136,276 +124,178 @@ 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.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductManager { - private String VALIDATION_VSP_ID = "validationOnlyVspId"; - private static final String VALIDATION_VSP_NAME = "validationOnlyVspName"; - //private static final String VALIDATION_VSP_USER = "validationOnlyVspUser"; - - private static final MdcDataDebugMessage MDC_DATA_DEBUG_MESSAGE = new MdcDataDebugMessage(); + private static MdcDataDebugMessage MDC_DATA_DEBUG_MESSAGE = new MdcDataDebugMessage(); private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductManagerImpl.class); - private final OrchestrationTemplateDao orchestrationTemplateDao; - private final VendorSoftwareProductInfoDao vspInfoDao; - private final VersioningManager versioningManager; - private final VendorSoftwareProductDao vendorSoftwareProductDao; - private final VendorLicenseFacade vendorLicenseFacade; - private final ServiceModelDao serviceModelDao; - private final EnrichedServiceModelDao enrichedServiceModelDao; - private final HealingManager healingManager; - private final VendorLicenseArtifactsService licenseArtifactsService; - private final InformationArtifactGenerator informationArtifactGenerator; - private final PackageInfoDao packageInfoDao; - private final ActivityLogManager activityLogManager; - private final DeploymentFlavorDao deploymentFlavorDao; - private final NicDao nicDao; - private final ManualVspToscaManager manualVspToscaManager; - - /** - * Instantiates a new Vendor software product manager. - * - * @param versioningManager the versioning manager - * @param vendorSoftwareProductDao the vendor software product dao - * @param orchestrationTemplateDataDao the orchestration template data dao - * @param vspInfoDao the vsp info dao - * @param vendorLicenseFacade the vendor license facade - * @param serviceModelDao the service model dao - * @param enrichedServiceModelDao the enriched service model dao - * @param healingManager the healing manager - * @param licenseArtifactsService the license artifacts service - * @param informationArtifactGenerator the information artifact generator - * @param packageInfoDao the package info dao - * @param activityLogManager the activity log manager - * @param deploymentFlavorDao the deployment flavor dao - * @param nicDao the nic dao - */ + private OrchestrationTemplateDao orchestrationTemplateDao; + private VendorSoftwareProductInfoDao vspInfoDao; + private VendorLicenseFacade vendorLicenseFacade; + private ServiceModelDao serviceModelDao; + private EnrichedServiceModelDao enrichedServiceModelDao; + private VendorLicenseArtifactsService licenseArtifactsService; + private InformationArtifactGenerator informationArtifactGenerator; + private PackageInfoDao packageInfoDao; + private DeploymentFlavorDao deploymentFlavorDao; + private ComponentDao componentDao; + private ComponentDependencyModelDao componentDependencyModelDao; + private NicDao nicDao; + private ComputeDao computeDao; + private ImageDao imageDao; + private ManualVspToscaManager manualVspToscaManager; + public VendorSoftwareProductManagerImpl( - VersioningManager versioningManager, - VendorSoftwareProductDao vendorSoftwareProductDao, OrchestrationTemplateDao orchestrationTemplateDataDao, VendorSoftwareProductInfoDao vspInfoDao, VendorLicenseFacade vendorLicenseFacade, ServiceModelDao serviceModelDao, EnrichedServiceModelDao enrichedServiceModelDao, - HealingManager healingManager, VendorLicenseArtifactsService licenseArtifactsService, InformationArtifactGenerator informationArtifactGenerator, PackageInfoDao packageInfoDao, - ActivityLogManager activityLogManager, DeploymentFlavorDao deploymentFlavorDao, + ComponentDao componentDao, + ComponentDependencyModelDao componentDependencyModelDao, NicDao nicDao, + ComputeDao computeDao, + ImageDao imageDao, ManualVspToscaManager manualVspToscaManager) { - this.versioningManager = versioningManager; - this.vendorSoftwareProductDao = vendorSoftwareProductDao; this.orchestrationTemplateDao = orchestrationTemplateDataDao; this.vspInfoDao = vspInfoDao; this.vendorLicenseFacade = vendorLicenseFacade; this.serviceModelDao = serviceModelDao; this.enrichedServiceModelDao = enrichedServiceModelDao; - this.healingManager = healingManager; this.licenseArtifactsService = licenseArtifactsService; this.informationArtifactGenerator = informationArtifactGenerator; this.packageInfoDao = packageInfoDao; - this.activityLogManager = activityLogManager; this.deploymentFlavorDao = deploymentFlavorDao; + this.componentDao = componentDao; + this.componentDependencyModelDao = componentDependencyModelDao; this.nicDao = nicDao; + this.computeDao = computeDao; + this.imageDao = imageDao; this.manualVspToscaManager = manualVspToscaManager; registerToVersioning(); } private void registerToVersioning() { - vendorSoftwareProductDao.registerVersioning( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE); serviceModelDao.registerVersioning( VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE); enrichedServiceModelDao.registerVersioning( VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE); } - @Override - public Version checkout(String vendorSoftwareProductId, String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vendorSoftwareProductId); - MDC.put(LoggerConstants.SERVICE_NAME, LoggerServiceName.Checkout_Entity.toString()); - - Version newVersion = versioningManager - .checkout(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, - vendorSoftwareProductId, user); - - if (newVersion != null) { - ActivityLogEntity activityLogEntity = - new ActivityLogEntity(vendorSoftwareProductId, String.valueOf(newVersion.getMajor() + 1), - ActivityType.CHECKOUT.toString(), user, true, "", ""); - activityLogManager.addActionLog(activityLogEntity, user); - } - - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vendorSoftwareProductId); - return newVersion; - } - - - @Override - public Version undoCheckout(String vendorSoftwareProductId, String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vendorSoftwareProductId); - - Version version = - getVersionInfo(vendorSoftwareProductId, VersionableEntityAction.Read, user) - .getActiveVersion(); - - ActivityLogEntity activityLogEntity = - new ActivityLogEntity(vendorSoftwareProductId, String.valueOf(version.getMajor() + 1), - ActivityType.UNDO_CHECKOUT.toString(), user, true, "", ""); - activityLogManager.addActionLog(activityLogEntity, user); - - String preVspName = vspInfoDao - .get(new VspDetails(vendorSoftwareProductId, version)).getName(); - - Version newVersion = versioningManager.undoCheckout( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, - vendorSoftwareProductId, user); - - String postVspName = vspInfoDao - .get(new VspDetails(vendorSoftwareProductId, newVersion)) - .getName(); - - updateUniqueName(preVspName, postVspName); - - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vendorSoftwareProductId); - - return newVersion; - } @Override - public Version checkin(String vendorSoftwareProductId, String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vendorSoftwareProductId); - - Version newVersion = versioningManager.checkin( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, - vendorSoftwareProductId, user, null); - - if (newVersion != null) { - ActivityLogEntity activityLogEntity = - new ActivityLogEntity(vendorSoftwareProductId, String.valueOf(newVersion.getMajor() + 1), - ActivityType.CHECKIN.toString(), user, true, "", ""); - activityLogManager.addActionLog(activityLogEntity, user); - } - - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vendorSoftwareProductId); - - return newVersion; - } - - @Override - public ValidationResponse submit(String vspId, String user) throws IOException { + public ValidationResponse validate(String vspId, Version version) throws IOException { MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); - Version version = getVersionInfo(vspId, VersionableEntityAction.Read, user).getActiveVersion(); - VspDetails vspDetails = getVsp(vspId, version, user); - UploadDataEntity uploadData = orchestrationTemplateDao.getOrchestrationTemplate(vspId, version); - ToscaServiceModel serviceModel = - serviceModelDao.getServiceModel(vspId, vspDetails.getVersion()); + VspDetails vspDetails = getValidatedVsp(vspId, version); + Collection componentDependencies = + componentDependencyModelDao.list(new ComponentDependencyModelEntity(vspId, version, null)); ValidationResponse validationResponse = new ValidationResponse(); - validationResponse - .setVspErrors(validateCompletedVendorSoftwareProduct(vspDetails, uploadData, serviceModel), - LoggerServiceName.Submit_VSP, LoggerTragetServiceName.SUBMIT_VSP); - - if (isCyclicDependencyInComponents(vspId, vspDetails.getVersion())) { - Collection vspErrors = validationResponse.getVspErrors() == null - ? new ArrayList<>() - : validationResponse.getVspErrors(); - vspErrors.add(ComponentDependencyModelErrorBuilder - .getcyclicDependencyComponentErrorBuilder()); - validationResponse.setVspErrors(vspErrors, LoggerServiceName.Submit_VSP, - LoggerTragetServiceName.SUBMIT_VSP); - } - - validationResponse.setLicensingDataErrors(validateLicensingData(vspDetails)); - validationResponse - .setUploadDataErrors(validateUploadData(uploadData, vspDetails), - LoggerServiceName.Submit_VSP, - LoggerTragetServiceName.SUBMIT_VSP); - validationResponse.setQuestionnaireValidationResult( - validateQuestionnaire(vspDetails.getId(), vspDetails.getVersion(), vspDetails - .getOnboardingMethod())); - - if ("Manual".equals(vspDetails.getOnboardingMethod())) { - Collection deploymentFlavourValidationErrList = - deploymentFlavorValidation(vspDetails.getId(), vspDetails.getVersion()); - if (validationResponse.getVspErrors() != null) { - if (deploymentFlavourValidationErrList != null) { - validationResponse.getVspErrors().addAll(deploymentFlavourValidationErrList); - } - } else { - validationResponse - .setVspErrors(deploymentFlavourValidationErrList, LoggerServiceName.Submit_VSP, - LoggerTragetServiceName.SUBMIT_VSP); + validateQuestionnaire(vspDetails.getId(), vspDetails.getVersion(), + vspDetails.getOnboardingMethod())); + + List vspErrors = new ArrayList<>(); + vspErrors.addAll(validateVspFields(vspDetails)); + if (validateComponentDependencies(componentDependencies)) { + vspErrors + .add(ComponentDependencyModelErrorBuilder.getcyclicDependencyComponentErrorBuilder()); + } + if (Objects.nonNull(vspDetails.getOnboardingMethod()) && + OnboardingMethod.Manual.name().equals(vspDetails.getOnboardingMethod())) { + vspErrors.addAll(validateMandatoryLicenseFields(vspDetails)); + + Collection deploymentFlavors = deploymentFlavorDao + .list(new DeploymentFlavorEntity(vspDetails.getId(), vspDetails.getVersion(), null)); + if (CollectionUtils.isEmpty(deploymentFlavors)) { + vspErrors + .add(VendorSoftwareProductInvalidErrorBuilder.VspMissingDeploymentFlavorErrorBuilder()); } + vspErrors.addAll(validateDeploymentFlavors(deploymentFlavors)); - Set compositionEntityValidationData = + Set componentValidationResult = componentValidation(vspDetails.getId(), vspDetails.getVersion()); - if (validationResponse.getQuestionnaireValidationResult() != null) { - if (!CollectionUtils.isEmpty(compositionEntityValidationData)) { + if (!CollectionUtils.isEmpty(componentValidationResult)) { + if (validationResponse.getQuestionnaireValidationResult() == null || + validationResponse.getQuestionnaireValidationResult().getValidationData() == null) { + validationResponse.setQuestionnaireValidationResult( + new QuestionnaireValidationResult(componentValidationResult)); + } else { validationResponse.getQuestionnaireValidationResult().getValidationData() - .addAll(compositionEntityValidationData); + .addAll(componentValidationResult); } - } else { - validationResponse.setQuestionnaireValidationResult( - CollectionUtils.isEmpty(compositionEntityValidationData) ? null : - new QuestionnaireValidationResult(compositionEntityValidationData)); } - - //Generate Tosca service model for Manual Onboarding flow - VspModelInfo vspModelInfo = manualVspToscaManager.gatherVspInformation(vspId, version, user); - serviceModel = manualVspToscaManager.generateToscaModel(vspModelInfo); - } - validationResponse.setCompilationErrors( - compile(vspId, vspDetails.getVersion(), serviceModel), - LoggerServiceName.Submit_VSP, LoggerTragetServiceName.SUBMIT_VSP); - - if (validationResponse.isValid()) { - Version newVersion = versioningManager.submit( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, - vspId, user, null); - ActivityLogEntity activityLogEntity = new ActivityLogEntity(vspDetails.getId(), String - .valueOf(newVersion.getMajor()), - ActivityType.SUBMIT.toString(), user, true, "", ""); - activityLogManager.addActionLog(activityLogEntity, user); + } else { + if (vspDetails.getVlmVersion() != null || vspDetails.getLicenseAgreement() != null + || vspDetails.getFeatureGroups() != null) { + vspErrors.addAll(validateMandatoryLicenseFields(vspDetails)); + } + OrchestrationTemplateEntity orchestrationTemplate = + orchestrationTemplateDao.get(vspId, version); + ToscaServiceModel serviceModel = + serviceModelDao.getServiceModel(vspId, vspDetails.getVersion()); + if (!isOrchestrationTemplateExist(orchestrationTemplate) || + !isServiceModelExist(serviceModel)) { + vspErrors.add(VendorSoftwareProductInvalidErrorBuilder + .VendorSoftwareProductMissingServiceModelErrorBuilder(vspDetails.getId(), + vspDetails.getVersion())); + } + validationResponse.setUploadDataErrors(validateOrchestrationTemplate(orchestrationTemplate), + LoggerServiceName.Submit_VSP, LoggerTragetServiceName.SUBMIT_VSP); } + validationResponse + .setVspErrors(vspErrors, LoggerServiceName.Submit_VSP, LoggerTragetServiceName.SUBMIT_VSP); + validationResponse.setLicensingDataErrors(validateLicensingData(vspDetails)); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); return validationResponse; } - private boolean isCyclicDependencyInComponents(String vendorSoftwareProductId, - Version version) { - final Collection componentDependencyModelEntities = - vendorSoftwareProductDao.listComponentDependencies(vendorSoftwareProductId, version); + @Override + public Map> compile(String vspId, Version version) { + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); + + 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); + + Map> compilationErrors = compile(vspId, version, serviceModel); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); + return compilationErrors; + } + + private boolean validateComponentDependencies( + Collection componentDependencies) { ComponentDependencyTracker dependencyTracker = new ComponentDependencyTracker(); - for (ComponentDependencyModelEntity entity : componentDependencyModelEntities) { - dependencyTracker.addDependency(entity.getSourceComponentId(), entity.getTargetComponentId()); + for (ComponentDependencyModelEntity componentDependency : componentDependencies) { + dependencyTracker.addDependency(componentDependency.getSourceComponentId(), + componentDependency.getTargetComponentId()); } return dependencyTracker.isCyclicDependencyPresent(); } - private Collection deploymentFlavorValidation(String vspId, - Version version) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); - Set validationData = new HashSet<>(); + private Collection validateDeploymentFlavors( + Collection deploymentFlavors) { + Collection errorCodeList = new ArrayList<>(); - Collection deploymentFlavors = - vendorSoftwareProductDao.listDeploymentFlavors(vspId, version); if (!CollectionUtils.isEmpty(deploymentFlavors)) { deploymentFlavors.forEach(deploymentFlavor -> { - DeploymentFlavorEntity deployment = vendorSoftwareProductDao.getDeploymentFlavor(vspId, - version, deploymentFlavor.getId()); + DeploymentFlavorEntity deployment = deploymentFlavorDao.get(deploymentFlavor); DeploymentFlavor deploymentlocalFlavor = deployment.getDeploymentFlavorCompositionData(); if (deploymentlocalFlavor != null) { if (deploymentlocalFlavor.getFeatureGroupId() == null) { @@ -455,7 +345,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa Set validationData = new HashSet<>(); Collection components = - vendorSoftwareProductDao.listComponents(vspId, version); + componentDao.list(new ComponentEntity(vspId, version, null)); if (!CollectionUtils.isEmpty(components)) { components.forEach(component -> { validateImage(vspId, version, validationData, component); @@ -496,13 +386,13 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa private void validateImage(String vspId, Version version, Set validationData, ComponentEntity component) { - Collection images = vendorSoftwareProductDao.listImages(vspId, version, - component.getId()); + Collection images = + imageDao.list(new ImageEntity(vspId, version, component.getId(), null)); if (CollectionUtils.isEmpty(images)) { CompositionEntityValidationData compositionEntityValidationData = new CompositionEntityValidationData(component.getType(), component.getId()); - compositionEntityValidationData.setEntityName(component.getComponentCompositionData() - .getDisplayName()); + compositionEntityValidationData + .setEntityName(component.getComponentCompositionData().getDisplayName()); ErrorCode vfcMissingImageErrorBuilder = ComponentErrorBuilder.VfcMissingImageErrorBuilder(); List errors = new ArrayList<>(); @@ -512,10 +402,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } } - - private List validateCompletedVendorSoftwareProduct( - VspDetails vspDetails, UploadDataEntity uploadData, Object serviceModel) { - + private List validateVspFields(VspDetails vspDetails) { List errors = new ArrayList<>(); if (vspDetails.getName() == null) { @@ -533,36 +420,13 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa if (vspDetails.getSubCategory() == null) { errors.add(createMissingMandatoryFieldError("sub category")); } - if ("Manual".equals(vspDetails.getOnboardingMethod())) { - //Manual Onboarding specific validations - Collection deploymentFlavorEntities = vendorSoftwareProductDao - .listDeploymentFlavors(vspDetails.getId(), vspDetails.getVersion()); - if (CollectionUtils.isEmpty(deploymentFlavorEntities)) { - ErrorCode vspMissingDeploymentFlavorErrorBuilder = - VendorSoftwareProductInvalidErrorBuilder.VspMissingDeploymentFlavorErrorBuilder(); - errors.add(vspMissingDeploymentFlavorErrorBuilder); - } - errors.addAll(validateMandatoryLicenseFields(vspDetails)); - } else { - //Heat flow specific VSP validations - if (uploadData == null || uploadData.getContentData() == null || serviceModel == null) { - errors.add(VendorSoftwareProductInvalidErrorBuilder - .VendorSoftwareProductMissingServiceModelErrorBuilder(vspDetails.getId(), - vspDetails.getVersion())); - } - if (vspDetails.getVlmVersion() != null || vspDetails.getLicenseAgreement() != null - || vspDetails.getFeatureGroups() != null) { - errors.addAll(validateMandatoryLicenseFields(vspDetails)); - } - } - return errors.isEmpty() ? null : errors; + return errors; } private List validateMandatoryLicenseFields(VspDetails vspDetails) { List errors = new ArrayList<>(); if (vspDetails.getVlmVersion() == null) { - errors.add(createMissingMandatoryFieldError( - "licensing version (in the format of: {integer}.{integer})")); + errors.add(createMissingMandatoryFieldError("licensing version")); } if (vspDetails.getLicenseAgreement() == null) { errors.add(createMissingMandatoryFieldError("license agreement")); @@ -577,23 +441,9 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa return new ValidationErrorBuilder("must be supplied", fieldName).build(); } - String getVspQuestionnaireSchema(SchemaTemplateInput schemaInput) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage(null); - MDC_DATA_DEBUG_MESSAGE.debugExitMessage(null); - return SchemaGenerator - .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.vsp, schemaInput); - } - - private static void sortVspListByModificationTimeDescOrder( - List vsps) { - vsps.sort((o1, o2) -> o2.getVspDetails().getWritetimeMicroSeconds() - .compareTo(o1.getVspDetails().getWritetimeMicroSeconds())); - } - - private Map> compile(String vendorSoftwareProductId, Version version, ToscaServiceModel serviceModel) { - if (serviceModel == null) { + if (!isServiceModelExist(serviceModel)) { return null; } @@ -636,135 +486,47 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } @Override - public String fetchValidationVsp(String user) { - try { - validateUniqueName(VALIDATION_VSP_NAME); - } catch (Exception ignored) { - LOGGER.debug("Ignored exception when validating unique VSP name", ignored); - return VALIDATION_VSP_ID; - } - VspDetails validationVsp = new VspDetails(); - validationVsp.setName(VALIDATION_VSP_NAME); - - vspInfoDao.create(validationVsp); - Version version = versioningManager.create( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, - validationVsp.getId(), user); - validationVsp.setVersion(version); - - createUniqueName(VALIDATION_VSP_NAME); - VALIDATION_VSP_ID = validationVsp.getId(); - return VALIDATION_VSP_ID; - } - - @Override - public VspDetails createVsp(VspDetails vspDetails, String user) { + public VspDetails createVsp(VspDetails vspDetails) { MDC_DATA_DEBUG_MESSAGE.debugEntryMessage(null); - validateUniqueName(vspDetails.getName()); - - vspDetails.setOnboardingOrigin(OnboardingTypesEnum.NONE.toString()); - - vspInfoDao.create(vspDetails);//id will be set in the dao - vspInfoDao.updateQuestionnaireData(vspDetails.getId(), null, + vspInfoDao.create(vspDetails); + vspInfoDao.updateQuestionnaireData(vspDetails.getId(), vspDetails.getVersion(), new JsonSchemaDataGenerator(getVspQuestionnaireSchema(null)).generateData()); - Version version = versioningManager - .create(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, - vspDetails.getId(), user); - vspDetails.setVersion(version); - ActivityLogEntity activityLogEntity = new ActivityLogEntity(vspDetails.getId(), String - .valueOf(vspDetails.getVersion().getMajor() + 1), - ActivityType.CREATE_NEW.toString(), user, true, "", ""); - activityLogManager.addActionLog(activityLogEntity, user); - String vspName = vspDetails.getName(); - createUniqueName(vspName); MDC_DATA_DEBUG_MESSAGE.debugExitMessage(null); return vspDetails; } @Override - public List listVsps(String versionFilter, String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage(null); - - Map idToVersionsInfo = versioningManager.listEntitiesVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, user, - VersionableEntityAction.Read); - - List vsps = new ArrayList<>(); - for (Map.Entry entry : idToVersionsInfo.entrySet()) { - VersionInfo versionInfo = entry.getValue(); - if (versionFilter != null && versionFilter.equals(VersionStatus.Final.name())) { - if (versionInfo.getLatestFinalVersion() == null) { - continue; - } - versionInfo.setActiveVersion(versionInfo.getLatestFinalVersion()); - versionInfo.setStatus(VersionStatus.Final); - versionInfo.setLockingUser(null); - } - - Version version = versionInfo.getActiveVersion(); - if (user.equals(versionInfo.getLockingUser())) { - version.setStatus(VersionStatus.Locked); - } - try { - VspDetails vsp = vspInfoDao.get(new VspDetails(entry.getKey(), version)); - if (vsp != null && !vsp.getId().equals(VALIDATION_VSP_ID)) { - vsp.setValidationDataStructure(null); - vsps.add(new VersionedVendorSoftwareProductInfo(vsp, versionInfo)); - } - } catch (RuntimeException rte) { - LOGGER.error( - "Error trying to retrieve vsp[" + entry.getKey() + "] version[" + version.toString - () + "] " + - "message:" + rte.getMessage(), rte); - } - } - - sortVspListByModificationTimeDescOrder(vsps); - - MDC_DATA_DEBUG_MESSAGE.debugExitMessage(null); - - return vsps; - } - - @Override - public void updateVsp(VspDetails vspDetails, String user) { + public void updateVsp(VspDetails vspDetails) { MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspDetails.getId()); VspDetails retrieved = vspInfoDao.get(vspDetails); - if (!Objects.equals(retrieved.getOnboardingMethod(), vspDetails.getOnboardingMethod())) { - final ErrorCode onboardingMethodUpdateErrorCode = OnboardingMethodErrorBuilder - .getOnboardingUpdateError(); - - MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.UPDATE_VSP, ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), onboardingMethodUpdateErrorCode.message()); - - throw new CoreException(onboardingMethodUpdateErrorCode); + // TODO: 6/21/2017 remove this validation when validation will be added in the REST level + if (retrieved == null) { + throw new RuntimeException(String.format("Vsp with id %s and version %s does not exist.", + vspDetails.getId(), vspDetails.getVersion().getId())); } + 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, user); + updateDeploymentFlavor(vspDetails); updateUniqueName(retrieved.getName(), vspDetails.getName()); - vspDetails.setOldVersion(retrieved.getOldVersion()); - vspInfoDao.update(vspDetails); - //vendorSoftwareProductDao.updateVspLatestModificationTime(vspDetails.getId(), activeVersion); MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspDetails.getId()); } - private void updateDeploymentFlavor(VspDetails vspDetails, String user) { + private void updateDeploymentFlavor(VspDetails vspDetails) { final List featureGroups = vspDetails.getFeatureGroups(); if (featureGroups != null) { final Collection deploymentFlavorEntities = deploymentFlavorDao .list(new DeploymentFlavorEntity(vspDetails.getId(), vspDetails .getVersion(), null)); if (Objects.nonNull(deploymentFlavorEntities)) { - deploymentFlavorEntities.forEach(deploymentFlavorEntity -> { + for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { final String featureGroupId = deploymentFlavorEntity.getDeploymentFlavorCompositionData().getFeatureGroupId(); if (!featureGroups.contains(featureGroupId)) { @@ -773,18 +535,25 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa deploymentFlavorCompositionData.setFeatureGroupId(null); deploymentFlavorEntity.setDeploymentFlavorCompositionData (deploymentFlavorCompositionData); - vendorSoftwareProductDao.updateDeploymentFlavor(deploymentFlavorEntity); + deploymentFlavorDao.update(deploymentFlavorEntity); } - }); + } } } } @Override - public VspDetails getVsp(String vspId, Version version, String user) { + public VspDetails getVsp(String vspId, Version version) { MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); + VspDetails vsp = getValidatedVsp(vspId, version); + + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); + return vsp; + } + + private VspDetails getValidatedVsp(String vspId, Version version) { VspDetails vsp = vspInfoDao.get(new VspDetails(vspId, version)); if (vsp == null) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, @@ -792,64 +561,11 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa LoggerErrorCode.DATA_ERROR.getErrorCode(), "Requested VSP not found"); throw new CoreException(new VendorSoftwareProductNotFoundErrorBuilder(vspId).build()); } - vsp.setValidationData(orchestrationTemplateDao.getValidationData(vspId, version)); - if (Objects.isNull(vsp.getOnboardingOrigin())) { //todo should this only be done for non-Manual? - vsp.setOnboardingOrigin(OnboardingTypesEnum.ZIP.toString()); - } - - if (Objects.isNull(vsp.getNetworkPackageName())) { - vsp.setNetworkPackageName("Upload File"); - } - - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); return vsp; } @Override - public Version callAutoHeal(String vspId, VersionInfo versionInfo, - VspDetails vendorSoftwareProductInfo, String user) - throws Exception { - switch (versionInfo.getStatus()) { - case Locked: - if (user.equals(versionInfo.getLockingUser())) { - autoHeal(vspId, versionInfo.getActiveVersion(), vendorSoftwareProductInfo, - versionInfo.getLockingUser()); - } - return versionInfo.getActiveVersion(); - case Available: - Version checkoutVersion = checkout(vspId, user); - autoHeal(vspId, checkoutVersion, vendorSoftwareProductInfo, user); - return checkin(vspId, user); - case Final: - return healAndAdvanceFinalVersion(vspId, vendorSoftwareProductInfo, user); - default: - //do nothing - break; - } - return versionInfo.getActiveVersion(); - } - - public Version healAndAdvanceFinalVersion(String vspId, VspDetails vendorSoftwareProductInfo, - String user) throws IOException { - - Version checkoutVersion = checkout(vspId, user); - autoHeal(vspId, checkoutVersion, vendorSoftwareProductInfo, user); - Version checkinVersion = checkin(vspId, user); - - ValidationResponse response = Objects.requireNonNull(submit(vspId, user), - "Null response not expected"); - - if (!response.isValid()) { - return checkinVersion; - } - - Version finalVersion = checkinVersion.calculateNextFinal(); - createPackage(vspId, finalVersion, user); - return finalVersion; - } - - @Override - public void deleteVsp(String vspId, String user) { + public void deleteVsp(String vspId) { MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, @@ -861,89 +577,17 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa VendorSoftwareProductConstants.UNSUPPORTED_OPERATION_ERROR); } - @Override - public void heal(String vspId, Version version, String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); - - VersionInfo versionInfo = getVersionInfo(vspId, VersionableEntityAction.Read, user); - - version = VersionStatus.Locked.equals(versionInfo.getStatus()) - ? versionInfo.getActiveVersion() - : checkout(vspId, user); - version.setStatus(VersionStatus.Locked); - - Optional errorMessages = - healingManager.healAll(getHealingParamsAsMap(vspId, version, user)); - - VspDetails vspDetails = new VspDetails(vspId, version); - vspDetails.setOldVersion(null); - vspInfoDao.updateOldVersionIndication(vspDetails); - - LOGGER.audit("Healed VSP " + vspDetails.getId()); - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); - - errorMessages.ifPresent(s -> { - throw new CoreException(new ErrorCode.ErrorCodeBuilder().withId("HEALING_ERROR") - .withCategory(ErrorCategory.APPLICATION).withMessage(s).build()); - }); - } - - private void autoHeal(String vspId, Version checkoutVersion, VspDetails vspDetails, String user) { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); - - checkoutVersion.setStatus(VersionStatus.Locked); - Map healingParams = getHealingParamsAsMap(vspId, checkoutVersion, user); - - Optional errorMessages = healingManager.healAll(healingParams); - - vspDetails.setVersion(checkoutVersion); - vspDetails.setOldVersion(null); - vspInfoDao.updateOldVersionIndication(vspDetails); - - LOGGER.audit("Healed VSP " + vspDetails.getName()); - MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); - - errorMessages.ifPresent(s -> { - throw new CoreException(new ErrorCode.ErrorCodeBuilder().withId("HEALING_ERROR") - .withCategory(ErrorCategory.APPLICATION).withMessage(s).build()); - }); - } - - private Map getHealingParamsAsMap(String vspId, Version version, String user) { - Map healingParams = new HashMap<>(); - - healingParams.put(SdcCommon.VSP_ID, vspId); - healingParams.put(SdcCommon.VERSION, version); - healingParams.put(SdcCommon.USER, user); - - return healingParams; - } - @Override public List listPackages(String category, String subCategory) { return packageInfoDao.listByCategory(category, subCategory); } @Override - public File getTranslatedFile(String vspId, Version version, String user) { + public File getTranslatedFile(String vspId, Version version) { MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); String errorMessage; - if (version == null) { - errorMessage = "Package not found"; - MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.GET_TRANSLATED_FILE, ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), errorMessage); - throw new CoreException(new PackageNotFoundErrorBuilder(vspId).build()); - } else if (!version.isFinal()) { - errorMessage = "Invalid requested version"; - MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.GET_VERSION_INFO, ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), errorMessage); - throw new CoreException(new RequestedVersionInvalidErrorBuilder().build()); - } - PackageInfo packageInfo = - packageInfoDao.get(new PackageInfo(vspId, version)); + PackageInfo packageInfo = packageInfoDao.get(new PackageInfo(vspId, version)); if (packageInfo == null) { errorMessage = "Package not found"; MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, @@ -981,10 +625,10 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @Override - public byte[] getOrchestrationTemplateFile(String vspId, Version version, String user) { + public byte[] getOrchestrationTemplateFile(String vspId, Version version) { MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); - UploadDataEntity uploadData = orchestrationTemplateDao.getOrchestrationTemplate(vspId, version); + OrchestrationTemplateEntity uploadData = orchestrationTemplateDao.get(vspId, version); ByteBuffer contentData = uploadData.getContentData(); if (contentData == null) { return null; @@ -993,7 +637,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (final ZipOutputStream zos = new ZipOutputStream(baos); - ZipInputStream zipStream = new ZipInputStream( + ZipInputStream ignored = new ZipInputStream( new ByteArrayInputStream(contentData.array()))) { zos.write(contentData.array()); } catch (IOException exception) { @@ -1008,29 +652,25 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } @Override - public PackageInfo createPackage(String vspId, Version version, String user) throws IOException { - MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); + public OrchestrationTemplateEntity getOrchestrationTemplateInfo(String vspId, Version version) { + return orchestrationTemplateDao.getInfo(vspId, version); + } - if (!version.isFinal()) { - MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.CREATE_PACKAGE, ErrorLevel.ERROR.name(), - LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Can't create package"); - throw new CoreException( - new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version) - .build()); - } + @Override + public PackageInfo createPackage(String vspId, Version version) throws IOException { + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); ToscaServiceModel toscaServiceModel = enrichedServiceModelDao.getServiceModel(vspId, version); VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); Version vlmVersion = vspDetails.getVlmVersion(); - PackageInfo packageInfo = createPackageInfo(vspId, vspDetails); + PackageInfo packageInfo = createPackageInfo(vspDetails); ToscaFileOutputServiceCsarImpl toscaServiceTemplateServiceCsar = new ToscaFileOutputServiceCsarImpl(); FileContentHandler licenseArtifacts = licenseArtifactsService .createLicenseArtifacts(vspDetails.getId(), vspDetails.getVendorId(), vlmVersion, - vspDetails.getFeatureGroups(), user); + vspDetails.getFeatureGroups()); //todo add tosca validation here packageInfo.setTranslatedFile(ByteBuffer.wrap( toscaServiceTemplateServiceCsar.createOutputFile(toscaServiceModel, licenseArtifacts))); @@ -1043,10 +683,8 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa return packageInfo; } - private PackageInfo createPackageInfo(String vspId, VspDetails vspDetails) { - PackageInfo packageInfo = new PackageInfo(); - packageInfo.setVspId(vspId); - packageInfo.setVersion(vspDetails.getVersion()); + private PackageInfo createPackageInfo(VspDetails vspDetails) { + PackageInfo packageInfo = new PackageInfo(vspDetails.getId(), vspDetails.getVersion()); packageInfo.setVspName(vspDetails.getName()); packageInfo.setVspDescription(vspDetails.getDescription()); packageInfo.setCategory(vspDetails.getCategory()); @@ -1059,7 +697,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @Override - public QuestionnaireResponse getVspQuestionnaire(String vspId, Version version, String user) { + public QuestionnaireResponse getVspQuestionnaire(String vspId, Version version) { MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); VspQuestionnaireEntity retrieved = vspInfoDao.getQuestionnaire(vspId, version); @@ -1078,8 +716,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } @Override - public void updateVspQuestionnaire(String vspId, Version version, String questionnaireData, - String user) { + public void updateVspQuestionnaire(String vspId, Version version, String questionnaireData) { MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); vspInfoDao.updateQuestionnaireData(vspId, version, questionnaireData); @@ -1088,21 +725,19 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } - private Map> validateUploadData(UploadDataEntity uploadData, - VspDetails vspDetails) - throws IOException { + private Map> validateOrchestrationTemplate( + OrchestrationTemplateEntity orchestrationTemplate) throws IOException { - Map> validationErrors = new HashMap<>(); - if (uploadData == null || uploadData.getContentData() == null) { + if (!isOrchestrationTemplateExist(orchestrationTemplate)) { return null; } + Map> validationErrors = new HashMap<>(); - FileContentHandler fileContentMap = - CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.getOnboardingTypesEnum - (vspDetails.getOnboardingOrigin()), - uploadData.getContentData().array()); + FileContentHandler fileContentMap = CommonUtil.validateAndUploadFileContent( + OnboardingTypesEnum.getOnboardingTypesEnum(orchestrationTemplate.getFileSuffix()), + orchestrationTemplate.getContentData().array()); - if (CommonUtil.isFileOriginFromZip(vspDetails.getOnboardingOrigin())) { + if (CommonUtil.isFileOriginFromZip(orchestrationTemplate.getFileSuffix())) { ValidationManager validationManager = ValidationManagerUtil.initValidationManager(fileContentMap); validationErrors.putAll(validationManager.validate()); @@ -1113,14 +748,6 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa ? null : validationErrors; } - private VersionInfo getVersionInfo(String vendorSoftwareProductId, VersionableEntityAction action, - String user) { - return versioningManager.getEntityVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, - vendorSoftwareProductId, user, action); - } - - private QuestionnaireValidationResult validateQuestionnaire(String vspId, Version version, String onboardingMethod) { MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); @@ -1132,7 +759,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa compositionEntityDataManager .addEntity(vspInfoDao.getQuestionnaire(vspId, version), null); - Collection nics = vendorSoftwareProductDao.listNicsByVsp(vspId, version); + Collection nics = nicDao.listByVsp(vspId, version); Map> nicNamesByComponent = new HashMap<>(); for (NicEntity nicEntity : nics) { @@ -1147,16 +774,16 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } Collection components = - vendorSoftwareProductDao.listComponentsCompositionAndQuestionnaire(vspId, version); + componentDao.listCompositionAndQuestionnaire(vspId, version); components.forEach(component -> compositionEntityDataManager.addEntity(component, new ComponentQuestionnaireSchemaInput(nicNamesByComponent.get(component.getId()), JsonUtil.json2Object(component.getQuestionnaireData(), Map.class)))); - Collection computes = vendorSoftwareProductDao.listComputesByVsp(vspId, version); + Collection computes = computeDao.listByVsp(vspId, version); computes.forEach(compute -> compositionEntityDataManager.addEntity(compute, null)); - if ("Manual".equals(onboardingMethod)) { - Collection images = vendorSoftwareProductDao.listImagesByVsp(vspId, version); + if (OnboardingMethod.Manual.name().equals(onboardingMethod)) { + Collection images = imageDao.listByVsp(vspId, version); images.forEach(image -> compositionEntityDataManager.addEntity(image, null)); } @@ -1179,7 +806,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } @Override - public File getInformationArtifact(String vspId, Version version, String user) { + public File getInformationArtifact(String vspId, Version version) { MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); @@ -1209,14 +836,11 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa return infoArtifactFile; } - void validateUniqueName(String vspName) { - UniqueValueUtil.validateUniqueValue( - VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME, vspName); - } - - void createUniqueName(String vspName) { - UniqueValueUtil.createUniqueValue( - VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME, vspName); + String getVspQuestionnaireSchema(SchemaTemplateInput schemaInput) { + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage(null); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage(null); + return SchemaGenerator + .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.vsp, schemaInput); } void updateUniqueName(String oldVspName, String newVspName) { @@ -1226,13 +850,22 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } @Override - public Collection getComputeByVsp(String vspId, Version version, - String user) { - return vendorSoftwareProductDao.listComputesByVsp(vspId, version); + public Collection getComputeByVsp(String vspId, Version version) { + return computeDao.listByVsp(vspId, version); } - private void auditIfContainsErrors(List errorList, String vspId, String auditType) { + private boolean isOrchestrationTemplateExist(OrchestrationTemplateEntity orchestrationTemplate) { + return orchestrationTemplate != null && + orchestrationTemplate.getContentData() != null && + orchestrationTemplate.getFileSuffix() != null && + orchestrationTemplate.getFileName() != null; + } + private boolean isServiceModelExist(ToscaServiceModel serviceModel) { + return serviceModel != null && serviceModel.getEntryDefinitionServiceTemplate() != null; + } + + private void auditIfContainsErrors(List errorList, String vspId, String auditType) { errorList.forEach(errorMessage -> { if (errorMessage.getLevel().equals(ErrorLevel.ERROR)) { LOGGER.audit(AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(), @@ -1240,4 +873,6 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } }); } + + } 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 5615f8f6b5..a2c0aea423 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 @@ -22,38 +22,38 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.core.model.dao.EnrichedServiceModelDaoFactory; import org.openecomp.core.model.dao.ServiceModelDaoFactory; -import org.openecomp.sdc.activityLog.ActivityLogManagerFactory; -import org.openecomp.sdc.healing.factory.HealingManagerFactory; import org.openecomp.sdc.vendorlicense.VendorLicenseArtifactServiceFactory; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacadeFactory; import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager; import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDaoFactory; +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.NicDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.factory.InformationArtifactGeneratorFactory; -import org.openecomp.sdc.versioning.VersioningManagerFactory; public class VspManagerFactoryImpl extends VspManagerFactory { private static final VendorSoftwareProductManager INSTANCE = new VendorSoftwareProductManagerImpl( - VersioningManagerFactory.getInstance().createInterface(), - VendorSoftwareProductDaoFactory.getInstance().createInterface(), OrchestrationTemplateDaoFactory.getInstance().createInterface(), VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), VendorLicenseFacadeFactory.getInstance().createInterface(), ServiceModelDaoFactory.getInstance().createInterface(), EnrichedServiceModelDaoFactory.getInstance().createInterface(), - HealingManagerFactory.getInstance().createInterface(), VendorLicenseArtifactServiceFactory.getInstance().createInterface(), InformationArtifactGeneratorFactory.getInstance().createInterface(), PackageInfoDaoFactory.getInstance().createInterface(), - ActivityLogManagerFactory.getInstance().createInterface(), DeploymentFlavorDaoFactory.getInstance().createInterface(), + ComponentDaoFactory.getInstance().createInterface(), + ComponentDependencyModelDaoFactory.getInstance().createInterface(), NicDaoFactory.getInstance().createInterface(), + ComputeDaoFactory.getInstance().createInterface(), + ImageDaoFactory.getInstance().createInterface(), new ManualVspToscaManagerImpl()); @Override 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 c7fb43770d..d20dc07b63 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 @@ -14,87 +14,94 @@ import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; -import org.openecomp.sdc.versioning.dao.types.Version; import java.io.InputStream; import java.util.Optional; + import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters; + public abstract class BaseOrchestrationTemplateHandler implements OrchestrationTemplateFileHandler { - protected static final Logger logger = - LoggerFactory.getLogger(BaseOrchestrationTemplateHandler.class); - protected static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - - @Override - public UploadFileResponse upload(String vspId, Version version, InputStream fileToUpload, String user, - CandidateService candidateService, VspDetails vspDetails) { - UploadFileResponse uploadFileResponse = new UploadFileResponse(); - uploadFileResponse.setOnboardingType(getHandlerType()); - if (isNotEmptyFileToUpload(fileToUpload, uploadFileResponse, candidateService)) { - return uploadFileResponse; - } - - byte[] uploadedFileData = FileUtils.toByteArray(fileToUpload); - if (isInvalidRawZipData(uploadFileResponse, uploadedFileData, candidateService)) { - return uploadFileResponse; - } - - Optional optionalContentMap = - getFileContentMap(uploadFileResponse, uploadedFileData); - if (!optionalContentMap.isPresent()) { - logger.error(getErrorWithParameters(Messages.FILE_CONTENT_MAP.getErrorMessage(), getHandlerType().toString())); - uploadFileResponse - .addStructureError( - SdcCommon.UPLOAD_FILE, - new ErrorMessage(ErrorLevel.ERROR, - getErrorWithParameters(Messages.FILE_CONTENT_MAP.getErrorMessage(), getHandlerType().toString()))); - - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); - return uploadFileResponse; - } - - if (!MapUtils.isEmpty(uploadFileResponse.getErrors())) { - - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); - return uploadFileResponse; - } - if (updateCandidateData(vspId, user, candidateService, vspDetails, uploadFileResponse, - uploadedFileData, optionalContentMap)) - return uploadFileResponse; - - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); - return uploadFileResponse; + protected static final Logger logger = + LoggerFactory.getLogger(BaseOrchestrationTemplateHandler.class); + protected static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + @Override + public UploadFileResponse upload(VspDetails vspDetails, InputStream fileToUpload, + String fileSuffix, String networkPackageName, + CandidateService candidateService) { + UploadFileResponse uploadFileResponse = new UploadFileResponse(); + uploadFileResponse.setOnboardingType(getHandlerType()); + if (isNotEmptyFileToUpload(fileToUpload, uploadFileResponse, candidateService)) { + return uploadFileResponse; + } + + byte[] uploadedFileData = FileUtils.toByteArray(fileToUpload); + if (isInvalidRawZipData(uploadFileResponse, uploadedFileData, candidateService)) { + return uploadFileResponse; + } + + Optional optionalContentMap = + getFileContentMap(uploadFileResponse, uploadedFileData); + if (!optionalContentMap.isPresent()) { + logger.error(getErrorWithParameters(Messages.FILE_CONTENT_MAP.getErrorMessage(), + getHandlerType().toString())); + uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, + getErrorWithParameters(Messages.FILE_CONTENT_MAP.getErrorMessage(), + getHandlerType().toString()))); + mdcDataDebugMessage.debugExitMessage("VSP id", vspDetails.getId()); + return uploadFileResponse; } - protected abstract boolean updateCandidateData(String vspId, String user, CandidateService candidateService, - VspDetails vspDetails, UploadFileResponse uploadFileResponse, - byte[] uploadedFileData, - Optional optionalContentMap); - - - private boolean isNotEmptyFileToUpload(InputStream fileToUpload, - UploadFileResponse uploadFileResponse, CandidateService candidateService) { - Optional errorMessage = - candidateService.validateNonEmptyFileToUpload(fileToUpload); - if (errorMessage.isPresent()) { - uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, errorMessage.get()); - return true; - } - return false; + if (!MapUtils.isEmpty(uploadFileResponse.getErrors())) { + mdcDataDebugMessage.debugExitMessage("VSP id", vspDetails.getId()); + return uploadFileResponse; } + if (updateCandidateData(vspDetails, uploadedFileData, optionalContentMap.get(), fileSuffix, + networkPackageName, candidateService, uploadFileResponse)) { + return uploadFileResponse; + } + + mdcDataDebugMessage.debugExitMessage("VSP id", vspDetails.getId()); + return uploadFileResponse; + + } + + protected abstract boolean updateCandidateData(VspDetails vspDetails, + byte[] uploadedFileData, + FileContentHandler contentMap, + String fileSuffix, + String networkPackageName, + CandidateService candidateService, + UploadFileResponse uploadFileResponse); - protected boolean isInvalidRawZipData(UploadFileResponse uploadFileResponse, - byte[] uploadedFileData, CandidateService candidateService) { - Optional errorMessage; - errorMessage = candidateService.validateRawZipData(uploadedFileData); - if (errorMessage.isPresent()) { - uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, errorMessage.get()); - return true; - } - return false; + private boolean isNotEmptyFileToUpload(InputStream fileToUpload, + UploadFileResponse uploadFileResponse, + CandidateService candidateService) { + Optional errorMessage = + candidateService.validateNonEmptyFileToUpload(fileToUpload); + if (errorMessage.isPresent()) { + uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, errorMessage.get()); + return true; } + return false; + } + + protected boolean isInvalidRawZipData(UploadFileResponse uploadFileResponse, + byte[] uploadedFileData, + CandidateService candidateService) { + Optional errorMessage; + errorMessage = candidateService.validateRawZipData(uploadedFileData); + if (errorMessage.isPresent()) { + uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, errorMessage.get()); + return true; + } + return false; + } + + public abstract Optional getFileContentMap( + UploadFileResponse uploadFileResponse, + byte[] uploadedFileData); - public abstract Optional getFileContentMap(UploadFileResponse uploadFileResponse, - byte[] uploadedFileData); - 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 db0851cd5f..16147553fe 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 @@ -30,131 +30,139 @@ import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.CS import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.CSARConstants.MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME; public class OrchestrationTemplateCSARHandler extends BaseOrchestrationTemplateHandler - implements OrchestrationTemplateFileHandler { - - - @Override - public Optional getFileContentMap(UploadFileResponse uploadFileResponse, - byte[] uploadedFileData) { - FileContentHandler contentMap = null; - List folderList = new ArrayList<>(); - try { - Pair> fileContentMapFromOrchestrationCandidateZip = CommonUtil.getFileContentMapFromOrchestrationCandidateZip(uploadedFileData); - contentMap = fileContentMapFromOrchestrationCandidateZip.getKey(); - folderList = fileContentMapFromOrchestrationCandidateZip.getRight(); - } catch (IOException exception) { - uploadFileResponse.addStructureError( - SdcCommon.UPLOAD_FILE, - new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_CSAR_FILE.getErrorMessage())); - } catch (CoreException coreException) { - uploadFileResponse.addStructureError( - SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, coreException.getMessage())); - } - validateContent(uploadFileResponse, contentMap, folderList); - return Optional.ofNullable(contentMap); + implements OrchestrationTemplateFileHandler { + + + @Override + public Optional getFileContentMap(UploadFileResponse uploadFileResponse, + byte[] uploadedFileData) { + FileContentHandler contentMap = null; + List folderList = new ArrayList<>(); + try { + Pair> fileContentMapFromOrchestrationCandidateZip = + CommonUtil.getFileContentMapFromOrchestrationCandidateZip(uploadedFileData); + contentMap = fileContentMapFromOrchestrationCandidateZip.getKey(); + folderList = fileContentMapFromOrchestrationCandidateZip.getRight(); + } catch (IOException exception) { + uploadFileResponse.addStructureError( + SdcCommon.UPLOAD_FILE, + new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_CSAR_FILE.getErrorMessage())); + } catch (CoreException coreException) { + uploadFileResponse.addStructureError( + SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, coreException.getMessage())); } - - private void validateContent(UploadFileResponse uploadFileResponse, FileContentHandler contentMap, List folderList) { - validateManifest(uploadFileResponse, contentMap); - validateFileExist(uploadFileResponse, contentMap, MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME); - validateNoExtraFiles(uploadFileResponse, contentMap); - validateFolders(uploadFileResponse, folderList); + validateContent(uploadFileResponse, contentMap, folderList); + return Optional.ofNullable(contentMap); + } + + private void validateContent(UploadFileResponse uploadFileResponse, FileContentHandler contentMap, + List folderList) { + validateManifest(uploadFileResponse, contentMap); + validateFileExist(uploadFileResponse, contentMap, MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME); + validateNoExtraFiles(uploadFileResponse, contentMap); + validateFolders(uploadFileResponse, folderList); + } + + private void validateManifest(UploadFileResponse uploadFileResponse, + FileContentHandler contentMap) { + + if (!validateFileExist(uploadFileResponse, contentMap, MAIN_SERVICE_TEMPLATE_MF_FILE_NAME)) { + return; } - private void validateManifest(UploadFileResponse uploadFileResponse, FileContentHandler contentMap) { - - if (!validateFileExist(uploadFileResponse, contentMap, MAIN_SERVICE_TEMPLATE_MF_FILE_NAME)){ - return; - } - - try (InputStream fileContent = contentMap.getFileContent(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME)) { + try (InputStream fileContent = contentMap.getFileContent(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME)) { - OnboardingManifest onboardingManifest = new OnboardingManifest(fileContent); - if (!onboardingManifest.isValid()) { - onboardingManifest.getErrors().forEach(error -> uploadFileResponse.addStructureError( - SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, error))); - } + OnboardingManifest onboardingManifest = new OnboardingManifest(fileContent); + if (!onboardingManifest.isValid()) { + onboardingManifest.getErrors().forEach(error -> uploadFileResponse.addStructureError( + SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, error))); + } - } catch (IOException e) { - // convert to runtime to keep the throws unchanged - throw new RuntimeException("Failed to validate manifest", e); - } + } catch (IOException e) { + // convert to runtime to keep the throws unchanged + throw new RuntimeException("Failed to validate manifest", e); } - - private void validateNoExtraFiles(UploadFileResponse uploadFileResponse, FileContentHandler contentMap) { - List unwantedFiles = contentMap.getFileList().stream() - .filter(this::filterFiles).collect(Collectors.toList()); - if (!unwantedFiles.isEmpty()) { - unwantedFiles.stream().filter(this::filterFiles).forEach(unwantedFile -> - uploadFileResponse.addStructureError( - SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, - getErrorWithParameters(Messages.CSAR_FILES_NOT_ALLOWED.getErrorMessage(), - unwantedFile)))); - } + } + + private void validateNoExtraFiles(UploadFileResponse uploadFileResponse, + FileContentHandler contentMap) { + List unwantedFiles = contentMap.getFileList().stream() + .filter(this::filterFiles).collect(Collectors.toList()); + if (!unwantedFiles.isEmpty()) { + unwantedFiles.stream().filter(this::filterFiles).forEach(unwantedFile -> + uploadFileResponse.addStructureError( + SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, + getErrorWithParameters(Messages.CSAR_FILES_NOT_ALLOWED.getErrorMessage(), + unwantedFile)))); } + } + + private void validateFolders(UploadFileResponse uploadFileResponse, List folderList) { + List filterResult = + folderList.stream().filter(this::filterFolders).collect(Collectors.toList()); + if (!filterResult.isEmpty()) { + folderList.stream().filter(this::filterFolders).forEach(unwantedFolder -> + uploadFileResponse.addStructureError( + SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, + getErrorWithParameters(Messages.CSAR_DIRECTORIES_NOT_ALLOWED.getErrorMessage(), + unwantedFolder)))); - private void validateFolders(UploadFileResponse uploadFileResponse, List folderList) { - List filterResult = folderList.stream().filter(this::filterFolders).collect(Collectors.toList()); - if (!filterResult.isEmpty()) { - folderList.stream().filter(this::filterFolders).forEach( unwantedFolder -> - uploadFileResponse.addStructureError( - SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, - getErrorWithParameters(Messages.CSAR_DIRECTORIES_NOT_ALLOWED.getErrorMessage(), - unwantedFolder)))); - - } - } - private boolean filterFiles(String inFileName) { - boolean valid = ELIGIBLE_FILES.stream().anyMatch(fileName -> fileName.equals(inFileName)); - return !valid && filterFolders(inFileName); } + } - private boolean filterFolders(String fileName) { - return ELIGBLE_FOLDERS.stream().noneMatch(fileName::startsWith); - } + private boolean filterFiles(String inFileName) { + boolean valid = ELIGIBLE_FILES.stream().anyMatch(fileName -> fileName.equals(inFileName)); + return !valid && filterFolders(inFileName); + } - private boolean validateFileExist(UploadFileResponse uploadFileResponse, FileContentHandler contentMap, String fileName) { + private boolean filterFolders(String fileName) { + return ELIGBLE_FOLDERS.stream().noneMatch(fileName::startsWith); + } - boolean containsFile = contentMap.containsFile(fileName); - if (!containsFile) { - uploadFileResponse.addStructureError( - SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, - getErrorWithParameters(Messages.CSAR_FILE_NOT_FOUND.getErrorMessage(), fileName))); - } - return containsFile; - } + private boolean validateFileExist(UploadFileResponse uploadFileResponse, + FileContentHandler contentMap, String fileName) { - @Override - protected boolean updateCandidateData(String vspId, String user, CandidateService candidateService, - VspDetails vspDetails, UploadFileResponse uploadFileResponse, - byte[] uploadedFileData, Optional optionalContentMap) { - try { - candidateService.updateCandidateUploadData(new OrchestrationTemplateCandidateData( - ByteBuffer.wrap(uploadedFileData), ""), vspDetails.getId()); - } catch (Exception exception) { - logger.error(getErrorWithParameters(Messages.FILE_CONTENT_MAP.getErrorMessage(), - getHandlerType().toString()), exception); - uploadFileResponse - .addStructureError( - SdcCommon.UPLOAD_FILE, - new ErrorMessage(ErrorLevel.ERROR, exception.getMessage())); - - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); - return true; - } - return false; + boolean containsFile = contentMap.containsFile(fileName); + if (!containsFile) { + uploadFileResponse.addStructureError( + SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, + getErrorWithParameters(Messages.CSAR_FILE_NOT_FOUND.getErrorMessage(), fileName))); } - - - @Override - protected OnboardingTypesEnum getHandlerType() { - return OnboardingTypesEnum.CSAR; + return containsFile; + } + + @Override + protected boolean updateCandidateData(VspDetails vspDetails, byte[] uploadedFileData, + FileContentHandler contentMap, + String fileSuffix, String networkPackageName, + CandidateService candidateService, + UploadFileResponse uploadFileResponse) { + try { + candidateService.updateCandidateUploadData(vspDetails.getId(), vspDetails.getVersion(), + new OrchestrationTemplateCandidateData(ByteBuffer.wrap(uploadedFileData), "", fileSuffix, + networkPackageName)); + } catch (Exception exception) { + logger.error(getErrorWithParameters(Messages.FILE_CONTENT_MAP.getErrorMessage(), + getHandlerType().toString()), exception); + uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, + new ErrorMessage(ErrorLevel.ERROR, exception.getMessage())); + + mdcDataDebugMessage.debugExitMessage("VSP id", vspDetails.getId()); + return true; } + return false; + } - @Override - protected boolean isInvalidRawZipData(UploadFileResponse uploadFileResponse, - byte[] uploadedFileData, CandidateService candidateService) { - return super.isInvalidRawZipData(uploadFileResponse, uploadedFileData, candidateService); - } + @Override + protected OnboardingTypesEnum getHandlerType() { + return OnboardingTypesEnum.CSAR; + } + + @Override + protected boolean isInvalidRawZipData(UploadFileResponse uploadFileResponse, + byte[] uploadedFileData, + CandidateService candidateService) { + return super.isInvalidRawZipData(uploadFileResponse, uploadedFileData, candidateService); + } } 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 3f7d18de9f..5e006a29bd 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 @@ -3,10 +3,12 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; -import org.openecomp.sdc.versioning.dao.types.Version; import java.io.InputStream; + public interface OrchestrationTemplateFileHandler { - UploadFileResponse upload(String vspId, Version version, InputStream fileToUpload, String user, - CandidateService candidateService, VspDetails vspDetails); + + UploadFileResponse upload(VspDetails vspDetails, InputStream fileToUpload, + String fileSuffix, String networkPackageName, + 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 626d941911..343c7460d9 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 @@ -15,41 +15,47 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; import java.util.Optional; import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters; + public class OrchestrationTemplateZipHandler extends BaseOrchestrationTemplateHandler - implements OrchestrationTemplateFileHandler { + implements OrchestrationTemplateFileHandler { - @Override - public Optional getFileContentMap(UploadFileResponse uploadFileResponse, - byte[] uploadedFileData) { - return OrchestrationUtil.getFileContentMap(OnboardingTypesEnum.ZIP, uploadFileResponse, uploadedFileData); - } + @Override + public Optional getFileContentMap(UploadFileResponse uploadFileResponse, + byte[] uploadedFileData) { + return OrchestrationUtil + .getFileContentMap(OnboardingTypesEnum.ZIP, uploadFileResponse, uploadedFileData); + } - @Override - protected boolean updateCandidateData(String vspId, String user, CandidateService candidateService, - VspDetails vspDetails, UploadFileResponse uploadFileResponse, - byte[] uploadedFileData, Optional optionalContentMap) { - try { - OrchestrationTemplateCandidateData candidateData = - new CandidateEntityBuilder(candidateService) - .buildCandidateEntityFromZip(vspDetails, uploadedFileData, optionalContentMap.get(), - uploadFileResponse.getErrors(), user); - candidateService.updateCandidateUploadData(candidateData, vspDetails.getId()); - } catch (Exception exception) { - logger.error(getErrorWithParameters(Messages.FILE_CONTENT_MAP.getErrorMessage(), - getHandlerType().toString()),exception); - uploadFileResponse - .addStructureError( - SdcCommon.UPLOAD_FILE, - new ErrorMessage(ErrorLevel.ERROR, exception.getMessage())); - - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); - return true; - } - return false; - } + @Override + protected boolean updateCandidateData(VspDetails vspDetails, byte[] uploadedFileData, + FileContentHandler contentMap, + String fileSuffix, String networkPackageName, + CandidateService candidateService, + UploadFileResponse uploadFileResponse) { + try { + OrchestrationTemplateCandidateData candidateData = + new CandidateEntityBuilder(candidateService) + .buildCandidateEntityFromZip(vspDetails, uploadedFileData, contentMap, + uploadFileResponse.getErrors()); + candidateData.setFileSuffix(fileSuffix); + candidateData.setFileName(networkPackageName); - @Override - protected OnboardingTypesEnum getHandlerType() { - return OnboardingTypesEnum.ZIP; + candidateService + .updateCandidateUploadData(vspDetails.getId(), vspDetails.getVersion(), candidateData); + } catch (Exception exception) { + logger.error(getErrorWithParameters(Messages.FILE_CONTENT_MAP.getErrorMessage(), + getHandlerType().toString()), exception); + uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, + new ErrorMessage(ErrorLevel.ERROR, exception.getMessage())); + + mdcDataDebugMessage.debugExitMessage("VSP id", vspDetails.getId()); + return true; } + return false; + } + + @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 99b311e473..3c3ab81e10 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 @@ -24,8 +24,8 @@ public class OrchestrationUploadFactory { } - public static final OrchestrationTemplateFileHandler createOrchestrationTemplateFileHandler(String filePrefix) { - String fileExtension = filePrefix.toLowerCase(); + public static final OrchestrationTemplateFileHandler createOrchestrationTemplateFileHandler(String fileSuffix) { + String fileExtension = fileSuffix.toLowerCase(); ImplementationConfiguration orchestrationTemplateFileHandler = fileHanlders.get(fileExtension); if(Objects.isNull(orchestrationTemplateFileHandler)){ 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 2ee7b263b9..e312e7c576 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 @@ -1,8 +1,5 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration; -import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.GENERAL_COMPONENT_ID; -import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.model.dao.ServiceModelDao; @@ -35,14 +32,16 @@ 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.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; +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.UploadData; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionDataExtractorFactory; import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionEntityDataManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor; @@ -62,13 +61,13 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME; + public class OrchestrationUtil { public static final String ORCHESTRATION_CONFIG_NAMESPACE = "orchestration"; public static final String ORCHESTRATION_IMPL_KEY = "orchestration_impl"; - - private VendorSoftwareProductDao vendorSoftwareProductDao; private NicDao nicDao; private ComponentArtifactDao componentArtifactDao; private ProcessDao processDao; @@ -80,8 +79,7 @@ public class OrchestrationUtil { private CompositionDataExtractor compositionDataExtractor; public OrchestrationUtil() { - this (VendorSoftwareProductDaoFactory.getInstance().createInterface(), - NicDaoFactory.getInstance().createInterface(), + this(NicDaoFactory.getInstance().createInterface(), MonitoringUploadDaoFactory.getInstance().createInterface(), ProcessDaoFactory.getInstance().createInterface(), OrchestrationTemplateDaoFactory.getInstance().createInterface(), @@ -93,7 +91,6 @@ public class OrchestrationUtil { } public OrchestrationUtil( - VendorSoftwareProductDao vendorSoftwareProductDao, NicDao nicDao, ComponentArtifactDao componentArtifactDao, ProcessDao processDao, @@ -103,7 +100,6 @@ public class OrchestrationUtil { ComponentDependencyModelDao componentDependencyModelDao, CompositionEntityDataManager compositionEntityDataManager, CompositionDataExtractor compositionDataExtractor) { - this.vendorSoftwareProductDao = vendorSoftwareProductDao; this.nicDao = nicDao; this.componentArtifactDao = componentArtifactDao; this.processDao = processDao; @@ -116,8 +112,7 @@ public class OrchestrationUtil { } public static Optional getFileContentMap(OnboardingTypesEnum type, - UploadFileResponse - uploadFileResponse, + UploadFileResponse uploadFileResponse, byte[] uploadedFileData) { FileContentHandler contentMap = null; try { @@ -133,95 +128,63 @@ public class OrchestrationUtil { return Optional.ofNullable(contentMap); } - public void backupComponentsQuestionnaireBeforeDelete(String vspId, Version activeVersion, - Map componentsQustanniare, - Map> - componentNicsQustanniare, - Map> - componentMibList, - Map> - componentProcesses, - Map processArtifact) { - //backup VSP processes - backupProcess(vspId, activeVersion, GENERAL_COMPONENT_ID, GENERAL_COMPONENT_ID, - componentProcesses, processArtifact); - Collection componentsCompositionAndQuestionnaire = vendorSoftwareProductDao - .listComponentsCompositionAndQuestionnaire(vspId, - activeVersion); + 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 -> - backupComponentQuestionnaire(vspId, activeVersion, componentEntity, componentsQustanniare, + backupComponentQuestionnaire(vspId, version, componentEntity, componentsQustanniare, componentNicsQustanniare, componentMibList, componentProcesses, processArtifact)); } - private void backupComponentQuestionnaire(String vspId, Version activeVersion, - ComponentEntity componentEntity, - Map componentsQustanniare, - Map> - componentNicsQustanniare, - Map> - componentMibList, - Map> - componentProcesses, - Map processArtifact) { + private void backupComponentQuestionnaire( + String vspId, Version version, + ComponentEntity componentEntity, + Map componentsQustanniare, + Map> componentNicsQustanniare, + Map> componentMibList, + Map> componentProcesses, + Map processArtifact) { String componentName = componentEntity.getComponentCompositionData().getName(); - backupMibData(componentsQustanniare, componentMibList, componentName, componentEntity, vspId, - activeVersion); - backupComponentProcessData(componentNicsQustanniare, vspId, activeVersion, componentName, - componentEntity, componentProcesses, processArtifact); + 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(Map componentsQustanniare, - Map> - componentMibList, - String componentName, ComponentEntity componentEntity, - String vspId, Version activeVersion) { - componentsQustanniare.put(componentName, componentEntity.getQuestionnaireData()); - //backup mib + private void backupMibData(String vspId, Version version, ComponentEntity componentEntity, + String componentName, + Map> componentMibList) { Collection componentMib = componentArtifactDao.listArtifacts(new - ComponentMonitoringUploadEntity(vspId, activeVersion, componentEntity.getId(), null)); + ComponentMonitoringUploadEntity(vspId, version, componentEntity.getId(), + null)); if (CollectionUtils.isNotEmpty(componentMib)) { componentMibList.put(componentName, componentMib); } } - private void backupComponentProcessData(Map> componentNicsQustanniare, - String vspId, Version activeVersion, String componentName, - ComponentEntity componentEntity, - Map> componentProcesses, - Map processArtifact) { - Collection - nics = nicDao.list(new NicEntity(vspId, activeVersion, componentEntity.getId(), null)); - //backup component processes - backupProcess(vspId, activeVersion, componentEntity.getId(), componentName, - componentProcesses, processArtifact); - if (CollectionUtils.isNotEmpty(nics)) { - Map nicsQustanniare = new HashMap<>(); - nics.forEach(nicEntity -> { - NicEntity nic = nicDao.get(new NicEntity(vspId, activeVersion, componentEntity.getId(), - nicEntity.getId())); - NicEntity nicQuestionnaire = nicDao.getQuestionnaireData(vspId, activeVersion, - componentEntity.getId(), nicEntity.getId()); - - nicsQustanniare - .put(nicEntity.getNicCompositionData().getName(), - nicQuestionnaire.getQuestionnaireData()); - }); - componentNicsQustanniare.put(componentName, nicsQustanniare); - } - } - - private void backupProcess(String vspId, Version activeVersion, String componentId, - String componentName, Map> processes, - Map processArtifact) { - Collection processList = vendorSoftwareProductDao.listProcesses(vspId, - activeVersion, componentId); + 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.get(new ProcessEntity(vspId, activeVersion, componentId, process.getId())); + ProcessEntity artifact = processDao + .getArtifact(new ProcessEntity(vspId, version, componentId, process.getId())); if (artifact.getArtifact() != null) { processArtifact.put(process.getId(), artifact); } @@ -229,29 +192,45 @@ public class OrchestrationUtil { } } - public void retainComponentQuestionnaireData(String vspId, Version activeVersion, - Map componentsQustanniare, - Map> - componentNicsQustanniare, - Map> componentMibList, - Map> processes, - Map processArtifact) { + 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 retainComponentQuestionnaireData(String vspId, Version version, + Map componentsQustanniare, + Map> + componentNicsQustanniare, + Map> componentMibList, + Map> processes, + Map processArtifact) { //VSP processes - restoreProcess(vspId, activeVersion, GENERAL_COMPONENT_ID, GENERAL_COMPONENT_ID, processes, - processArtifact); - Collection - components = vendorSoftwareProductDao.listComponents(vspId, activeVersion); + 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)) { - //Restore component questionnaire - componentDao.updateQuestionnaireData(vspId, activeVersion, + componentDao.updateQuestionnaireData(vspId, version, componentEntity.getId(), componentsQustanniare.get(componentEntity.getComponentCompositionData() .getName())); - //Restore component nic questionnaire if (componentNicsQustanniare.containsKey(componentName)) { - restoreComponentNicQuestionnaire(vspId, activeVersion, componentName, componentEntity, + restoreComponentNicQuestionnaire(vspId, version, componentName, componentEntity, componentNicsQustanniare); } //MIB //todo add for VES_EVENTS @@ -259,33 +238,30 @@ public class OrchestrationUtil { restoreComponentMibData(componentName, componentEntity, componentMibList); } //VFC processes - restoreProcess(vspId, activeVersion, componentEntity.getId(), componentName, processes, + restoreProcess(vspId, version, componentEntity.getId(), componentName, processes, processArtifact); } }); } - private void restoreComponentNicQuestionnaire(String vspId, Version activeVersion, + private void restoreComponentNicQuestionnaire(String vspId, Version version, String componentName, ComponentEntity componentEntity, - Map> - componentNicsQustanniare) { + Map> componentNicsQustanniare) { Map nicsQustanniare = componentNicsQustanniare.get(componentName); Collection nics = - nicDao.list(new NicEntity(vspId, activeVersion, componentEntity.getId(), null)); + nicDao.list(new NicEntity(vspId, version, componentEntity.getId(), null)); nics.forEach(nicEntity -> { if (nicsQustanniare.containsKey(nicEntity.getNicCompositionData().getName())) { - nicDao.updateQuestionnaireData(vspId, activeVersion, + nicDao.updateQuestionnaireData(vspId, version, componentEntity.getId(), nicEntity.getId(), nicsQustanniare.get(nicEntity.getNicCompositionData().getName())); } }); } - private void restoreComponentMibData(String componentName, - ComponentEntity componentEntity, - Map> - componentMibList) { + private void restoreComponentMibData(String componentName, ComponentEntity componentEntity, + Map> componentMibList) { Collection mibList = componentMibList.get(componentName); mibList.forEach(mib -> { mib.setComponentId(componentEntity.getId()); @@ -293,54 +269,58 @@ public class OrchestrationUtil { }); } - private void restoreProcess(String vspId, Version activeVersion, String componentId, - String componentName, - Map> processes, - Map processArtifact) { + 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 -> { - //Reatin VFC process - if (!GENERAL_COMPONENT_ID.equals(componentId) - && processArtifact.containsKey(process.getId())) { + process.setComponentId(componentId); + UniqueValueUtil.createUniqueValue(PROCESS_NAME, vspId, version.getId(), componentId, + process.getName()); + processDao.create(process); + if (processArtifact.containsKey(process.getId())) { ProcessEntity artifact = processArtifact.get(process.getId()); - artifact.setComponentId(componentId); - UniqueValueUtil.createUniqueValue(PROCESS_NAME, vspId, activeVersion.toString(), - componentId, process.getName()); - vendorSoftwareProductDao.createProcess(artifact); + processDao.uploadArtifact(artifact); } }); } } public void deleteUploadDataAndContent(String vspId, Version version) { - //fixme change this when more tables are zusammenized - vendorSoftwareProductDao.deleteUploadData(vspId, version); + VendorSoftwareProductInfoDaoFactory.getInstance().createInterface() + .delete(new VspDetails(vspId, version)); } - public void saveUploadData(String vspId, Version activeVersion, - InputStream uploadedFileData, - FileContentHandler fileContentMap, HeatStructureTree tree) { + public void saveUploadData(VspDetails vspDetails, + OrchestrationTemplateCandidateData candidateData, + InputStream uploadedFileData, + FileContentHandler fileContentMap, HeatStructureTree tree) { Map manifestAsMap = fileContentMap.containsFile(SdcCommon.MANIFEST_NAME) ? (Map) JsonUtil.json2Object(fileContentMap.getFileContent( SdcCommon.MANIFEST_NAME), Map.class) : new HashMap<>(); - UploadData uploadData = new UploadData(); + 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")); - orchestrationTemplateDataDao.updateOrchestrationTemplateData(vspId, uploadData); + orchestrationTemplateDataDao.update(vspDetails.getId(), vspDetails.getVersion(), uploadData); + + VspMergeDaoFactory.getInstance().createInterface() + .updateVspModelId(vspDetails.getId(), vspDetails.getVersion()); } - public void saveServiceModel(String vspId, - Version version, - ToscaServiceModel serviceModelToExtract, - ToscaServiceModel serviceModelToStore) { + 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 @@ -358,15 +338,14 @@ public class OrchestrationUtil { return heatTreeManager.getTree(); } - public void updateVspComponentDependencies(String vspId, Version activeVersion, - Map - vspComponentIdNameInfoBeforeProcess) { - Map updatedVspComponentNameIdInfo = getVspComponentNameIdInfo(vspId, - activeVersion); + public void updateVspComponentDependencies(String vspId, Version version, + Map vspComponentIdNameInfoBeforeProcess) { + Map updatedVspComponentNameIdInfo = getVspComponentNameIdInfo(vspId, version); if (MapUtils.isNotEmpty(updatedVspComponentNameIdInfo)) { Set updatedVspComponentNames = updatedVspComponentNameIdInfo.keySet(); Collection componentDependencies = - vendorSoftwareProductDao.listComponentDependencies(vspId, activeVersion); + componentDependencyModelDao.list(new ComponentDependencyModelEntity(vspId, + version, null)); if (CollectionUtils.isNotEmpty(componentDependencies)) { updateComponentDependency(vspComponentIdNameInfoBeforeProcess, componentDependencies, updatedVspComponentNames, updatedVspComponentNameIdInfo); @@ -374,7 +353,6 @@ public class OrchestrationUtil { } } - private void updateComponentDependency(Map vspComponentIdNameInfoBeforeProcess, Collection componentDependencies, @@ -398,14 +376,14 @@ public class OrchestrationUtil { } } - public Map getVspComponentIdNameInfo(String vspId, Version activeVersion) { + public Map getVspComponentIdNameInfo(String vspId, Version version) { Collection updatedVspComponents = - vendorSoftwareProductDao.listComponents(vspId, activeVersion); + 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 -> componentEntity.getId(), + .collect(Collectors.toMap(ComponentEntity::getId, componentEntity -> componentEntity.getComponentCompositionData().getName())); } @@ -413,15 +391,16 @@ public class OrchestrationUtil { } private Map getVspComponentNameIdInfo(String vspId, - Version activeVersion) { + Version version) { Collection updatedVspComponents = - vendorSoftwareProductDao.listComponents(vspId, activeVersion); + 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 -> componentEntity.getId())); + .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/CSARConstants.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/CSARConstants.java index 0d204ef2c0..cf04aadcfc 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/CSARConstants.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/CSARConstants.java @@ -1,6 +1,7 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar; import com.google.common.collect.ImmutableSet; + import static com.google.common.collect.ImmutableSet.of; public class CSARConstants { diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/OnboardingManifest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/OnboardingManifest.java index d88d883e67..c0da130a9f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/OnboardingManifest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/OnboardingManifest.java @@ -7,12 +7,22 @@ import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import java.io.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; import java.nio.charset.StandardCharsets; -import java.util.*; +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.vendorsoftwareproduct.impl.orchestration.csar.CSARConstants.*; +import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.CSARConstants.METADATA_MF_ATTRIBUTE; +import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.CSARConstants.SEPERATOR_MF_ATTRIBUTE; +import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.CSARConstants.SOURCE_MF_ATTRIBUTE; public class OnboardingManifest { private static final Logger logger = LoggerFactory.getLogger(OnboardingManifest.class); 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 516d85c2a7..6200b287a1 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 @@ -27,13 +27,13 @@ public class OrchestrationProcessFactory { } - public static Optional getInstance(String filePrefix) { - if (filePrefix == null) { + public static Optional getInstance(String fileSuffix) { + if (fileSuffix == null) { return Optional.empty(); } - filePrefix = filePrefix.toLowerCase().trim(); - OnboardingTypesEnum onboardingTypesEnum = OnboardingTypesEnum.getOnboardingTypesEnum(filePrefix); + fileSuffix = fileSuffix.toLowerCase().trim(); + OnboardingTypesEnum onboardingTypesEnum = OnboardingTypesEnum.getOnboardingTypesEnum(fileSuffix); if (onboardingTypesEnum == null) { return Optional.empty(); } 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 d217c31f65..b0e1e17f57 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 @@ -1,7 +1,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process; import org.apache.commons.collections4.MapUtils; -import org.openecomp.core.converter.ToscaConverter; import org.openecomp.core.impl.ToscaConverterImpl; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; @@ -26,7 +25,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationU import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService; import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; -import org.openecomp.sdc.versioning.dao.types.Version; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -37,35 +35,35 @@ import java.util.List; import java.util.Map; import java.util.Optional; -public class OrchestrationTemplateProcessCsarHandler implements OrchestrationTemplateProcessHandler { - - private static final Logger logger = LoggerFactory.getLogger(OrchestrationTemplateProcessCsarHandler.class); - private CandidateService candidateService = CandidateServiceFactory.getInstance().createInterface(); +public class OrchestrationTemplateProcessCsarHandler + implements OrchestrationTemplateProcessHandler { + private static final Logger LOGGER = + LoggerFactory.getLogger(OrchestrationTemplateProcessCsarHandler.class); + private CandidateService candidateService = + CandidateServiceFactory.getInstance().createInterface(); ToscaTreeManager toscaTreeManager = new ToscaTreeManager(); @Override public OrchestrationTemplateActionResponse process(VspDetails vspDetails, - OrchestrationTemplateCandidateData candidateData, - String user) { - String vspId = vspDetails.getId(); - Version version = vspDetails.getVersion(); - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.CSAR_VALIDATION_STARTED + vspId); - OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse(); + OrchestrationTemplateCandidateData candidateData) { + LOGGER.audit( + AuditMessages.AUDIT_MSG + AuditMessages.CSAR_VALIDATION_STARTED + vspDetails.getId()); + UploadFileResponse uploadFileResponse = new UploadFileResponse(); - Optional fileContent = - OrchestrationUtil - .getFileContentMap( - OnboardingTypesEnum.CSAR, uploadFileResponse, candidateData.getContentData().array()); + Optional fileContent = OrchestrationUtil + .getFileContentMap(OnboardingTypesEnum.CSAR, uploadFileResponse, + candidateData.getContentData().array()); - if(fileContent.isPresent()){ + OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse(); + if (fileContent.isPresent()) { try { FileContentHandler fileContentHandler = fileContent.get(); - processCsar(vspId, version, fileContentHandler, candidateData, response); - } catch (CoreException e){ - logger.error(e.getMessage()); + processCsar(vspDetails, fileContentHandler, candidateData, response); + } catch (CoreException e) { + LOGGER.error(e.getMessage()); response.addErrorMessageToMap(e.code().id(), e.code().message(),ErrorLevel.ERROR); } catch (IOException ioe) { - logger.error(ioe.getMessage()); + LOGGER.error(ioe.getMessage()); ErrorCode errorCode = new GeneralErrorBuilder(ioe.getMessage()).build(); response.addErrorMessageToMap(errorCode.id(), errorCode.message(),ErrorLevel.ERROR); } @@ -77,13 +75,13 @@ public class OrchestrationTemplateProcessCsarHandler implements OrchestrationTem return response; } - private void processCsar(String vspId, Version version, + private void processCsar(VspDetails vspDetails, FileContentHandler fileContentHandler, OrchestrationTemplateCandidateData candidateData, OrchestrationTemplateActionResponse response) throws IOException { response.setFileNames(new ArrayList<>(fileContentHandler.getFileList())); - Map> errors = validateCsar(fileContentHandler, response); - if(!isValid(errors)){ + Map> errors = validateCsar(fileContentHandler); + if (!isValid(errors)) { return; } @@ -95,32 +93,31 @@ public class OrchestrationTemplateProcessCsarHandler implements OrchestrationTem Map> processes = new HashMap<>(); Map processArtifact = new HashMap<>(); OrchestrationUtil orchestrationUtil = new OrchestrationUtil(); - orchestrationUtil.backupComponentsQuestionnaireBeforeDelete(vspId, - version, componentsQuestionnaire, + orchestrationUtil.backupComponentsQuestionnaireBeforeDelete(vspDetails.getId(), + vspDetails.getVersion(), componentsQuestionnaire, componentNicsQuestionnaire, componentMibList, processes, processArtifact); Optional zipByteArrayInputStream = candidateService - .fetchZipFileByteArrayInputStream(vspId, candidateData, null, OnboardingTypesEnum.CSAR, errors); + .fetchZipFileByteArrayInputStream(vspDetails.getId(), candidateData, null, + OnboardingTypesEnum.CSAR, errors); - orchestrationUtil.deleteUploadDataAndContent(vspId, version); - orchestrationUtil.saveUploadData( - vspId, version, zipByteArrayInputStream.get(), fileContentHandler, tree); + orchestrationUtil.deleteUploadDataAndContent(vspDetails.getId(), vspDetails.getVersion()); + orchestrationUtil.saveUploadData(vspDetails, candidateData, zipByteArrayInputStream.get(), + fileContentHandler, tree); ToscaServiceModel toscaServiceModel = new ToscaConverterImpl().convert(fileContentHandler); - orchestrationUtil.saveServiceModel(vspId, version, toscaServiceModel, toscaServiceModel); + orchestrationUtil.saveServiceModel(vspDetails.getId(), vspDetails.getVersion(), toscaServiceModel, + toscaServiceModel); } - private void addFiles(FileContentHandler fileContentHandler){ - for(Map.Entry fileEntry : fileContentHandler.getFiles().entrySet()){ + private void addFiles(FileContentHandler fileContentHandler) { + for (Map.Entry fileEntry : fileContentHandler.getFiles().entrySet()) { toscaTreeManager.addFile(fileEntry.getKey(), fileEntry.getValue()); } } - private Map> validateCsar(FileContentHandler fileContentHandler, - OrchestrationTemplateActionResponse response){ - - + private Map> validateCsar(FileContentHandler fileContentHandler) { Map> errors = new HashMap<>(); addFiles(fileContentHandler); toscaTreeManager.createTree(); @@ -129,7 +126,7 @@ public class OrchestrationTemplateProcessCsarHandler implements OrchestrationTem return errors; } - private boolean isValid(Map> 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 8b513b4347..1db48a5cc7 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 @@ -6,7 +6,7 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse; public interface OrchestrationTemplateProcessHandler { + OrchestrationTemplateActionResponse process(VspDetails vspDetails, - OrchestrationTemplateCandidateData candidateData, - String user); + 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 85ac26223f..da5cb01c79 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 @@ -1,19 +1,12 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process; -import static org.openecomp.sdc.logging.messages.AuditMessages.HEAT_VALIDATION_ERROR; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; -import org.openecomp.core.model.dao.ServiceModelDao; -import org.openecomp.core.model.dao.ServiceModelDaoFactory; import org.openecomp.core.translator.datatypes.TranslatorOutput; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.core.validation.util.MessageContainerUtil; -import org.openecomp.sdc.activityLog.ActivityLogManager; -import org.openecomp.sdc.activityLog.ActivityLogManagerFactory; -import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; @@ -31,18 +24,13 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCan 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.factory.CompositionDataExtractorFactory; -import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionEntityDataManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUtil; -import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor; -import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager; import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService; import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure; import org.openecomp.sdc.vendorsoftwareproduct.utils.VendorSoftwareProductUtils; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdcrests.activitylog.types.ActivityType; import java.io.ByteArrayInputStream; import java.util.Collection; @@ -51,41 +39,29 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import static org.openecomp.sdc.logging.messages.AuditMessages.HEAT_VALIDATION_ERROR; + public class OrchestrationTemplateProcessZipHandler implements OrchestrationTemplateProcessHandler { - Logger logger = LoggerFactory.getLogger(OrchestrationTemplateProcessZipHandler.class); + private Logger logger = LoggerFactory.getLogger(OrchestrationTemplateProcessZipHandler.class); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private CandidateService candidateService = CandidateServiceFactory.getInstance().createInterface(); - private ServiceModelDao serviceModelDao = ServiceModelDaoFactory.getInstance().createInterface(); - private CompositionEntityDataManager compositionEntityDataManager = - CompositionEntityDataManagerFactory.getInstance().createInterface(); - private CompositionDataExtractor compositionDataExtractor = - CompositionDataExtractorFactory.getInstance().createInterface(); - private ActivityLogManager activityLogManager = - ActivityLogManagerFactory.getInstance().createInterface(); - - - public OrchestrationTemplateProcessZipHandler(){} + @Override public OrchestrationTemplateActionResponse process(VspDetails vspDetails, - OrchestrationTemplateCandidateData - candidateData, - String user) { + OrchestrationTemplateCandidateData candidateData) { String vspId = vspDetails.getId(); Version version = vspDetails.getVersion(); - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.HEAT_VALIDATION_STARTED - + vspId); + logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.HEAT_VALIDATION_STARTED + vspId); OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse(); UploadFileResponse uploadFileResponse = new UploadFileResponse(); - Optional fileContent = - OrchestrationUtil - .getFileContentMap( - OnboardingTypesEnum.ZIP, uploadFileResponse, - candidateData.getContentData().array()); + Optional fileContent = OrchestrationUtil + .getFileContentMap(OnboardingTypesEnum.ZIP, uploadFileResponse, + candidateData.getContentData().array()); if (!fileContent.isPresent()) { response.addStructureErrors(uploadFileResponse.getErrors()); mdcDataDebugMessage.debugExitMessage("VSP id", vspId); - response.getErrors().values().forEach(errorList -> printAuditForErrors(errorList,vspId, + response.getErrors().values().forEach(errorList -> printAuditForErrors(errorList, vspId, HEAT_VALIDATION_ERROR)); return response; } @@ -100,7 +76,7 @@ public class OrchestrationTemplateProcessZipHandler implements OrchestrationTemp Messages.FOUND_UNASSIGNED_FILES.getErrorMessage(), ErrorLevel.ERROR); mdcDataDebugMessage.debugExitMessage("VSP id", vspId); - response.getErrors().values().forEach(errorList -> printAuditForErrors(errorList,vspId, + response.getErrors().values().forEach(errorList -> printAuditForErrors(errorList, vspId, HEAT_VALIDATION_ERROR)); return response; } @@ -113,8 +89,8 @@ public class OrchestrationTemplateProcessZipHandler implements OrchestrationTemp .fetchZipFileByteArrayInputStream( vspId, candidateData, manifest, OnboardingTypesEnum.ZIP, uploadErrors); if (!zipByteArrayInputStream.isPresent()) { - response.getErrors().values().forEach(errorList -> printAuditForErrors(errorList,vspId, - HEAT_VALIDATION_ERROR)); + response.getErrors().values() + .forEach(errorList -> printAuditForErrors(errorList, vspId, HEAT_VALIDATION_ERROR)); return response; } @@ -129,18 +105,19 @@ public class OrchestrationTemplateProcessZipHandler implements OrchestrationTemp OrchestrationUtil orchestrationUtil = new OrchestrationUtil(); Map vspComponentIdNameInfoBeforeProcess = orchestrationUtil.getVspComponentIdNameInfo(vspId, version); - orchestrationUtil.backupComponentsQuestionnaireBeforeDelete(vspId, - version, componentsQuestionnaire, - componentNicsQuestionnaire, componentMibList, processes, processArtifact); + orchestrationUtil + .backupComponentsQuestionnaireBeforeDelete(vspId, version, componentsQuestionnaire, + componentNicsQuestionnaire, componentMibList, processes, processArtifact); orchestrationUtil.deleteUploadDataAndContent(vspId, version); - orchestrationUtil.saveUploadData(vspId, version, zipByteArrayInputStream.get(), fileContentMap, - tree); + orchestrationUtil + .saveUploadData(vspDetails, candidateData, zipByteArrayInputStream.get(), fileContentMap, + tree); - response.getErrors().values().forEach(errorList -> printAuditForErrors(errorList,vspId, + response.getErrors().values().forEach(errorList -> printAuditForErrors(errorList, vspId, HEAT_VALIDATION_ERROR)); - if ( MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, - response.getErrors()))) { + if (MapUtils + .isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, response.getErrors()))) { logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.HEAT_VALIDATION_COMPLETED + vspId); } @@ -150,20 +127,17 @@ public class OrchestrationTemplateProcessZipHandler implements OrchestrationTemp HeatToToscaUtil.loadAndTranslateTemplateData(fileContentMap); ToscaServiceModel toscaServiceModel = translatorOutput.getToscaServiceModel(); - orchestrationUtil.saveServiceModel(vspId, version, translatorOutput - .getNonUnifiedToscaServiceModel(), toscaServiceModel); + orchestrationUtil + .saveServiceModel(vspId, version, translatorOutput.getNonUnifiedToscaServiceModel(), + toscaServiceModel); orchestrationUtil.retainComponentQuestionnaireData(vspId, version, componentsQuestionnaire, componentNicsQuestionnaire, componentMibList, processes, processArtifact); orchestrationUtil.updateVspComponentDependencies(vspId, version, vspComponentIdNameInfoBeforeProcess); + logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.HEAT_TRANSLATION_COMPLETED + vspId); uploadFileResponse.addStructureErrors(uploadErrors); - ActivityLogEntity activityLogEntity = - new ActivityLogEntity(vspId, String.valueOf(version.getMajor() + 1), - ActivityType.UPLOAD_HEAT.toString(), user, true, "", ""); - activityLogManager.addActionLog(activityLogEntity, user); - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); return response; } @@ -182,8 +156,8 @@ public class OrchestrationTemplateProcessZipHandler implements OrchestrationTemp errorList.forEach(errorMessage -> { if (errorMessage.getLevel().equals(ErrorLevel.ERROR)) { - logger.audit(AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(), - vspId)); + logger.audit( + AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(), vspId)); } }); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/FileDataStructureDto.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/FileDataStructureDto.java deleted file mode 100644 index 8cb367367c..0000000000 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/FileDataStructureDto.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.vendorsoftwareproduct.types; - -import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.Module; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Avrahamg - * @since November 07, 2016 - */ -public class FileDataStructureDto { - private List modules = new ArrayList<>(); - private List unassigned = new ArrayList<>(); - private List artifacts = new ArrayList<>(); - private List nested = new ArrayList<>(); - - public List getModules() { - return modules; - } - - public void setModules(List modules) { - this.modules = modules; - } - - public List getUnassigned() { - return unassigned; - } - - public void setUnassigned(List unassigned) { - this.unassigned = unassigned; - } - - public List getArtifacts() { - return artifacts; - } - - public void setArtifacts(List artifacts) { - this.artifacts = artifacts; - } - - public List getNested() { - return nested; - } - - public void setNested(List nested) { - this.nested = nested; - } -} diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/GetFileDataStructureResponseDTO.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/GetFileDataStructureResponseDTO.java deleted file mode 100644 index c30978266f..0000000000 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/GetFileDataStructureResponseDTO.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.vendorsoftwareproduct.types; - -import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.Module; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Avrahamg - * @since November 07, 2016 - */ -public class GetFileDataStructureResponseDTO { - private List modules = new ArrayList<>(); - private List unassigned = new ArrayList<>(); - private List artifacts = new ArrayList<>(); - private List nested = new ArrayList<>(); - - public List getModules() { - return modules; - } - - public void setModules(List modules) { - this.modules = modules; - } - - public List getUnassigned() { - return unassigned; - } - - public void setUnassigned(List unassigned) { - this.unassigned = unassigned; - } - - public List getArtifacts() { - return artifacts; - } - - public void setArtifacts(List artifacts) { - this.artifacts = artifacts; - } - - public List getNested() { - return nested; - } - - public void setNested(List nested) { - this.nested = nested; - } -} diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/ComputeTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/ComputeTest.java index ab7a70b6a7..3df06ba8eb 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/ComputeTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/ComputeTest.java @@ -1,33 +1,5 @@ package org.openecomp.sdc.vendorsoftwareproduct; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.DUPLICATE_COMPUTE_NAME_NOT_ALLOWED; - -import org.openecomp.core.utilities.CommonMethods; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; -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.VspDetails; -import org.openecomp.sdc.vendorsoftwareproduct.impl.VendorSoftwareProductManagerImpl; -import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; -import org.openecomp.sdc.vendorsoftwareproduct.types.ListComputeResponse; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentComputeAssociation; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentData; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComputeData; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.DeploymentFlavor; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.errors.VersioningErrorCodes; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - public class ComputeTest { /*private static final String USER1 = "componentsTestUser1"; diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/DeploymentFlavorTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/DeploymentFlavorTest.java index 45ba4fb434..77c81111a5 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/DeploymentFlavorTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/DeploymentFlavorTest.java @@ -1,33 +1,5 @@ package org.openecomp.sdc.vendorsoftwareproduct; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.CREATE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.DUPLICATE_DEPLOYMENT_FLAVOR_MODEL_NOT_ALLOWED; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.FEATURE_GROUP_NOT_EXIST_FOR_VSP; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.INVALID_COMPONENT_COMPUTE_ASSOCIATION; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.INVALID_COMPUTE_FLAVOR_ID; -import static org.openecomp.sdc.versioning.errors.VersioningErrorCodes.VERSIONABLE_ENTITY_NOT_EXIST; -import static org.openecomp.sdc.versioning.errors.VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND; - -import org.openecomp.core.utilities.CommonMethods; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; -import org.openecomp.sdc.vendorsoftwareproduct.impl.VendorSoftwareProductManagerImpl; - -import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentComputeAssociation; -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.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - public class DeploymentFlavorTest { /*private static final String USER1 = "deploymentTestUser1"; private static final String USER2 = "deploymentTestUser2"; diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/ImagesTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/ImagesTest.java index 5dcb7f9b62..d78f4045b6 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/ImagesTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/ImagesTest.java @@ -21,50 +21,48 @@ import static org.mockito.Mockito.verify; public class ImagesTest { - private static String VSP_ID = "VSP_ID"; - private static String COMP_ID = "COMP_ID"; - private static String ID = "ID"; - private static String USER = "USER"; - public static final Version VERSION01 = new Version(0, 1); + private static String VSP_ID = "VSP_ID"; + private static String COMP_ID = "COMP_ID"; + private static String ID = "ID"; + public static final Version VERSION01 = new Version("version_id"); - @Mock - private VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao; + @Mock + private VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao; - @Mock - private CompositionEntityDataManager compositionEntityDataManager; + @Mock + private CompositionEntityDataManager compositionEntityDataManager; - @InjectMocks - @Spy - private ImageManagerImpl imageManager; + @InjectMocks + @Spy + private ImageManagerImpl imageManager; - @BeforeMethod - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } - @Test - public void createImage() - { - ImageEntity imageEntity = new ImageEntity(VSP_ID, VERSION01, COMP_ID, ID); - doReturn(true).when(vendorSoftwareProductInfoDao).isManual(anyObject(), anyObject()); + @Test + public void createImage() { + ImageEntity imageEntity = new ImageEntity(VSP_ID, VERSION01, COMP_ID, ID); + doReturn(true).when(vendorSoftwareProductInfoDao).isManual(anyObject(), anyObject()); - imageManager.createImage(imageEntity, USER); - verify(compositionEntityDataManager).createImage(imageEntity); - } + imageManager.createImage(imageEntity); + verify(compositionEntityDataManager).createImage(imageEntity); + } - @Test - public void createImageHeat() - { - ImageEntity imageEntity = new ImageEntity(VSP_ID, VERSION01, COMP_ID, ID); - doReturn(false).when(vendorSoftwareProductInfoDao).isManual(anyObject(), anyObject()); - - try { - imageManager.createImage(imageEntity, USER); - Assert.fail(); - } catch (CoreException exception) { - Assert.assertEquals(exception.code().id(), VendorSoftwareProductErrorCodes.ADD_IMAGE_NOT_ALLOWED_IN_HEAT_ONBOARDING); - } + @Test + public void createImageHeat() { + ImageEntity imageEntity = new ImageEntity(VSP_ID, VERSION01, COMP_ID, ID); + doReturn(false).when(vendorSoftwareProductInfoDao).isManual(anyObject(), anyObject()); + + try { + imageManager.createImage(imageEntity); + Assert.fail(); + } catch (CoreException exception) { + Assert.assertEquals(exception.code().id(), + VendorSoftwareProductErrorCodes.ADD_IMAGE_NOT_ALLOWED_IN_HEAT_ONBOARDING); } + } /*private static final String USER1 = "imageTestUser1"; private static final String USER2 = "imageTestUser2"; private static final Version VERSION01 = new Version(0, 1); @@ -93,40 +91,40 @@ public class ImagesTest { vsp1 = vendorSoftwareProductManager.createNewVsp(VSPCommon .createVspDetails(null, null, "VSP_" + CommonMethods.nextUuId(), "Test-vsp1", "vendorName", "vlm1Id", "icon", "category", "subCategory", "123", null, - VSPCommon.OnboardingMethod.Manual.name()), USER1 + VSPCommon.OnboardingMethod.Manual.name())1 ); vsp1Id = vsp1.getId(); VspDetails vsp2 = vendorSoftwareProductManager.createNewVsp(VSPCommon .createVspDetails(null, null, "VSP_" + CommonMethods.nextUuId(), "Test-vsp2", "vendorName", "vlm1Id", "icon", "category", "subCategory", "123", null, VSPCommon.OnboardingMethod. - Manual.name()), USER1); + Manual.name())1); vsp2Id = vsp2.getId(); VspDetails vsp3 = vendorSoftwareProductManager.createNewVsp(VSPCommon .createVspDetails(null, null, "VSP_" + CommonMethods.nextUuId(), "Test-vsp3", "vendorName", "vlm1Id", "icon", "category", "subCategory", "123", null, VSPCommon - .OnboardingMethod.HEAT.name()), USER1); + .OnboardingMethod.HEAT.name())1); vsp3Id = vsp3.getId(); ComponentEntity comp = new ComponentEntity(); comp.setVspId(vsp2Id); comp.setCompositionData(comp1); - ComponentEntity createdComp = vendorSoftwareProductManager.createComponent(comp, USER1); + ComponentEntity createdComp = vendorSoftwareProductManager.createComponent(comp1); comp1Id = createdComp.getId(); } @Test public void testListImagesNonExistingVspId_negative() { - testList_negative("non existing vsp id", null, image1Id, USER1, + testList_negative("non existing vsp id", null, image1Id1, VersioningErrorCodes.VERSIONABLE_ENTITY_NOT_EXIST, "Versionable entity VendorSoftwareProduct with id non existing vsp id does not exist." ); } @Test public void testListImagesNonExistingVfcId_negative() { - testList_negative(vsp1Id, VERSION01, "444", USER1, + testList_negative(vsp1Id, VERSION01, "444"1, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND, "Vendor Software Product Component with Id 444 does not exist for Vendor Software Product " + "with id "+vsp1Id+ " and version "+VERSION01); @@ -137,20 +135,20 @@ public class ImagesTest { createImageEntity("media-vsrx-vmdisk-15.1X49-D40.6.aki", "aki"); createImageEntity("riverbed-15.1X49-D40.6.vdi", "vdi"); final Collection imageEntities = - vendorSoftwareProductManager.listImages(vsp2Id, VERSION01, comp1Id, USER1); + vendorSoftwareProductManager.listImages(vsp2Id, VERSION01, comp1Id1); System.out.println("size::"+imageEntities.size()); } @Test public void testCreateNonExistingVspId_negative() { - testCreate_negative(new ImageEntity("non existing vsp id", null, null, null), USER1, + testCreate_negative(new ImageEntity("non existing vsp id", null, null, null)1, VersioningErrorCodes.VERSIONABLE_ENTITY_NOT_EXIST, "Versionable entity VendorSoftwareProduct with id non existing vsp id does not exist."); } @Test public void testCreateNonExistingVfcId_negative() { - testCreate_negative(new ImageEntity(vsp1Id, VERSION01, "222", null), USER1, + testCreate_negative(new ImageEntity(vsp1Id, VERSION01, "222", null)1, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND, "Vendor Software Product Component with Id 222 does not exist for Vendor Software Product " + "with id "+vsp1Id + " and version "+VERSION01); @@ -158,8 +156,8 @@ public class ImagesTest { @Test(dependsOnMethods = "testUpdateNonExistingImageId_negative") public void testCreateOnAvailableVsp_negative() { - vendorSoftwareProductManager.checkin(vsp1Id, USER1); - testCreate_negative(new ImageEntity(vsp1Id, null, null, null), USER1, + vendorSoftwareProductManager.checkin(vsp1Id1); + testCreate_negative(new ImageEntity(vsp1Id, null, null, null)1, VersioningErrorCodes.EDIT_ON_UNLOCKED_ENTITY, "Can not edit versionable entity VendorSoftwareProduct with id "+vsp1Id+ " since it is not" + " checked out."); @@ -167,8 +165,8 @@ public class ImagesTest { @Test(dependsOnMethods = "testCreateOnAvailableVsp_negative") public void testCreateOnVspOtherUser_negative() { - vendorSoftwareProductManager.checkout(vsp1Id, USER1); - testCreate_negative(new ImageEntity(vsp1Id, null, null, null), USER2, + vendorSoftwareProductManager.checkout(vsp1Id1); + testCreate_negative(new ImageEntity(vsp1Id, null, null, null)2, VersioningErrorCodes.EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER, "Versionable entity VendorSoftwareProduct with id " +vsp1Id+ " can not be edited since it is locked by other user "+ USER1+ "."); @@ -180,11 +178,11 @@ public class ImagesTest { ComponentEntity comp = new ComponentEntity(); comp.setVspId(vsp1Id); comp.setCompositionData(comp1); - ComponentEntity createdComp = vendorSoftwareProductManager.createComponent(comp, USER1); + ComponentEntity createdComp = vendorSoftwareProductManager.createComponent(comp1); String compId = createdComp.getId(); - vendorSoftwareProductManager.checkin(vsp1Id, USER1); - vendorSoftwareProductManager.checkout(vsp1Id, USER1); + vendorSoftwareProductManager.checkin(vsp1Id1); + vendorSoftwareProductManager.checkout(vsp1Id1); for(int i = 1; i<=3; i++) { ImageEntity imageEntity = new ImageEntity(); @@ -197,17 +195,17 @@ public class ImagesTest { //image.setFormat("aki"); //image.setMd5("233343DDDD"); imageEntity.setImageCompositionData(image); - ImageEntity createdImage = vendorSoftwareProductManager.createImage(imageEntity, USER1); + ImageEntity createdImage = vendorSoftwareProductManager.createImage(imageEntity1); } Collection imageEntities = - vendorSoftwareProductManager.listImages(vsp1Id, null, compId, USER1); + vendorSoftwareProductManager.listImages(vsp1Id, null, compId1); Assert.assertEquals(imageEntities.size(), 3); - vendorSoftwareProductManager.undoCheckout(vsp1Id, USER1); + vendorSoftwareProductManager.undoCheckout(vsp1Id1); - imageEntities = vendorSoftwareProductManager.listImages(vsp1Id, null, compId, USER1); + imageEntities = vendorSoftwareProductManager.listImages(vsp1Id, null, compId1); Assert.assertEquals(imageEntities.size(), 0); } @@ -217,7 +215,7 @@ public class ImagesTest { final ErrorCode addImageNotSupportedHeatOnboardMethodErrorBuilder = NotSupportedHeatOnboardMethodErrorBuilder .getAddImageNotSupportedHeatOnboardMethodErrorBuilder(); - testCreate_negative(new ImageEntity(vsp3Id, null, null, null), USER1, + testCreate_negative(new ImageEntity(vsp3Id, null, null, null)1, addImageNotSupportedHeatOnboardMethodErrorBuilder.id(), addImageNotSupportedHeatOnboardMethodErrorBuilder.message() ); @@ -252,19 +250,19 @@ public class ImagesTest { @Test public void testGet() { ImageEntity createdImage = createImageEntity("read-riverbed-WX-IMG-9.2.0.qcow2", "qcow2"); - testGet(vsp2Id, VERSION01, comp1Id, createdImage.getId(), USER1, createdImage); + testGet(vsp2Id, VERSION01, comp1Id, createdImage.getId()1, createdImage); } @Test public void testGetNonExistingVspId_negative() { - testGet_negative("non existing vsp id", null, null, image1Id, USER1, + testGet_negative("non existing vsp id", null, null, image1Id1, VersioningErrorCodes.VERSIONABLE_ENTITY_NOT_EXIST, "Versionable entity VendorSoftwareProduct with id non existing vsp id does not exist." ); } @Test public void testGetNonExistingVfcId_negative() { - testGet_negative(vsp1Id, VERSION01, "111", null, USER1, + testGet_negative(vsp1Id, VERSION01, "111", null1, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND, "Vendor Software Product Component with Id 111 does not exist for Vendor Software Product " + "with id "+vsp1Id + " and version "+VERSION01); @@ -274,7 +272,7 @@ public class ImagesTest { public void testUpdateNonExistingVspId_negative() { ImageEntity imageEntity = new ImageEntity("non existing vsp id", null, null, image1Id); - testUpdate_negative(imageEntity, USER1, + testUpdate_negative(imageEntity1, VersioningErrorCodes.VERSIONABLE_ENTITY_NOT_EXIST, "Versionable entity VendorSoftwareProduct with id non existing vsp id does not exist." ); } @@ -283,7 +281,7 @@ public class ImagesTest { public void testUpdateNonExistingVfcId_negative() { ImageEntity imageEntity = new ImageEntity(vsp1Id, VERSION01, "111", null); - testUpdate_negative(imageEntity, USER1, + testUpdate_negative(imageEntity1, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND, "Vendor Software Product Component with Id 111 does not exist for Vendor Software Product " + "with id "+vsp1Id + " and version "+VERSION01); @@ -293,7 +291,7 @@ public class ImagesTest { public void testUpdateNonExistingImageId_negative() { ImageEntity imageEntity = new ImageEntity(vsp2Id, VERSION01, comp1Id, "222"); - testUpdate_negative(imageEntity, USER1, + testUpdate_negative(imageEntity1, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND, "Vendor Software Product Component Image with Id 222 does not exist for Vendor " + "Software Product with id "+vsp2Id+ " and version "+VERSION01 ); @@ -308,7 +306,7 @@ public class ImagesTest { //imageCompositionData.setVersion("10.0"); imageCompositionData.setDescription("updated image"); - vendorSoftwareProductManager.updateImage(imageEntity, USER1); + vendorSoftwareProductManager.updateImage(imageEntity1); testGet(vsp2Id, VERSION01, comp1Id, imageEntity.getId(),USER1, imageEntity ); image2Id = imageEntity.getId(); @@ -318,7 +316,7 @@ public class ImagesTest { public void testUpdateNegative_UniqueName() { final CompositionEntityResponse image = vendorSoftwareProductManager.getImage(vsp2Id, VERSION01, comp1Id, - image2Id, USER1); + image2Id1); final Image data = image.getData(); final Image imageCompositionData = data; @@ -326,7 +324,7 @@ public class ImagesTest { ImageEntity entity = new ImageEntity(vsp2Id, VERSION01, comp1Id, image2Id ); entity.setImageCompositionData(imageCompositionData); - testUpdate_negative(entity, USER1, ImageErrorBuilder.getDuplicateImageNameErrorBuilder( + testUpdate_negative(entity1, ImageErrorBuilder.getDuplicateImageNameErrorBuilder( "riverbed-WX-IMG-9.2.0.qcow2", comp1Id).id() ,ImageErrorBuilder.getDuplicateImageNameErrorBuilder("riverbed-WX-IMG-9.2.0.qcow2", comp1Id) .message() ); @@ -335,13 +333,13 @@ public class ImagesTest { @Test(dependsOnMethods = "testUpdateNegative_UniqueName") public void testDeleteImage() { CompositionEntityResponse image = - vendorSoftwareProductManager.getImage(vsp2Id, VERSION01, comp1Id, image2Id, USER1); + vendorSoftwareProductManager.getImage(vsp2Id, VERSION01, comp1Id, image2Id1); Assert.assertNotNull(image.getData()); - vendorSoftwareProductManager.deleteImage(vsp2Id, comp1Id, image2Id, USER1); + vendorSoftwareProductManager.deleteImage(vsp2Id, comp1Id, image2Id1); - testGet_negative(vsp2Id, VERSION01, comp1Id, image2Id, USER1, + testGet_negative(vsp2Id, VERSION01, comp1Id, image2Id1, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND, "Vendor Software Product Component Image with Id "+image2Id+ " does not exist for " + "Vendor Software Product with id "+vsp2Id+ " and version "+VERSION01 ); @@ -352,7 +350,7 @@ public class ImagesTest { public void testDeleteNonExistingVspId_negative() { ImageEntity imageEntity = new ImageEntity("non existing vsp id", null, null, image1Id); - testDelete_negative(imageEntity, USER1, + testDelete_negative(imageEntity1, VersioningErrorCodes.VERSIONABLE_ENTITY_NOT_EXIST, "Versionable entity VendorSoftwareProduct with id non existing vsp id does not exist." ); } @@ -361,7 +359,7 @@ public class ImagesTest { public void testDeleteNonExistingVfcId_negative() { ImageEntity imageEntity = new ImageEntity(vsp1Id, VERSION01, "111", null); - testDelete_negative(imageEntity, USER1, + testDelete_negative(imageEntity1, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND, "Vendor Software Product Component with Id 111 does not exist for Vendor Software Product " + "with id "+vsp1Id + " and version "+VERSION01); @@ -371,7 +369,7 @@ public class ImagesTest { public void testDeleteNonExistingImageId_negative() { ImageEntity imageEntity = new ImageEntity(vsp2Id, VERSION01, comp1Id, "222"); - testDelete_negative(imageEntity, USER1, + testDelete_negative(imageEntity1, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND, "Vendor Software Product Component Image with Id 222 does not exist for Vendor " + "Software Product with id "+vsp2Id+ " and version "+VERSION01 ); @@ -386,7 +384,7 @@ public class ImagesTest { final QuestionnaireResponse imageQuestionnaire = vendorSoftwareProductManager.getImageQuestionnaire(vsp2Id, VERSION01, comp1Id, - imageEntity.getId(), USER1); + imageEntity.getId()1); String imageDetails = imageQuestionnaire.getData(); Assert.assertEquals("vdi", JsonUtil.json2Object(imageDetails, ImageDetails.class).getFormat()); @@ -422,7 +420,7 @@ public class ImagesTest { // image.setMd5("233343DDDD"); imageEntity.setImageCompositionData(image); - ImageEntity createdImage = vendorSoftwareProductManager.createImage(imageEntity, USER1); + ImageEntity createdImage = vendorSoftwareProductManager.createImage(imageEntity1); image1Id = createdImage.getId(); return createdImage; } @@ -430,7 +428,7 @@ public class ImagesTest { private void testGet(String vspId, Version version, String componentId, String imageId, String user, ImageEntity expected) { CompositionEntityResponse - response = vendorSoftwareProductManager.getImage(vspId, null, componentId, imageId, user); + response = vendorSoftwareProductManager.getImage(vspId, null, componentId, imageId); Assert.assertEquals(response.getId(), expected.getId()); Assert.assertEquals(expected.getImageCompositionData().getFileName(), response.getData(). getFileName()); @@ -442,7 +440,7 @@ public class ImagesTest { private void testCreate_negative(ImageEntity image, String user, String expectedErrorCode, String expectedErrorMsg) { try { - vendorSoftwareProductManager.createImage(image, user); + vendorSoftwareProductManager.createImage(image); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), expectedErrorCode); @@ -454,7 +452,7 @@ public class ImagesTest { String user, String expectedErrorCode, String expectedErrorMsg) { try { - vendorSoftwareProductManager.getImage(vspId, version, componentId, imageId, user); + vendorSoftwareProductManager.getImage(vspId, version, componentId, imageId); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), expectedErrorCode); @@ -465,7 +463,7 @@ public class ImagesTest { private void testList_negative(String vspId, Version version, String componentId, String user, String expectedErrorCode, String expectedErrorMsg) { try { - vendorSoftwareProductManager.listImages(vspId, version, componentId, user); + vendorSoftwareProductManager.listImages(vspId, version, componentId); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), expectedErrorCode); @@ -478,7 +476,7 @@ public class ImagesTest { String expectedErrorCode, String expectedErrorMsg) { try { - vendorSoftwareProductManager.updateImage(imageEntity, user); + vendorSoftwareProductManager.updateImage(imageEntity); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), expectedErrorCode); @@ -491,7 +489,7 @@ public class ImagesTest { String expectedErrorCode, String expectedErrorMsg) { try { - vendorSoftwareProductManager.updateImage(imageEntity, user); + vendorSoftwareProductManager.updateImage(imageEntity); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), expectedErrorCode); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/QuestionnaireDataServiceTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/QuestionnaireDataServiceTest.java index b544d13ec7..e8e0f2c92b 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/QuestionnaireDataServiceTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/QuestionnaireDataServiceTest.java @@ -30,12 +30,10 @@ import org.mockito.MockitoAnnotations; import org.openecomp.core.model.dao.ServiceModelDao; import org.openecomp.core.model.types.ServiceElement; import org.openecomp.core.validation.util.MessageContainerUtil; -import org.openecomp.sdc.activityLog.ActivityLogManager; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.healing.api.HealingManager; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.impl.OrchestrationTemplateCandidateManagerImpl; import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.InformationArtifactData; import org.openecomp.sdc.vendorsoftwareproduct.questionnaire.QuestionnaireDataService; @@ -54,15 +52,10 @@ import java.io.InputStream; import java.util.List; import java.util.Objects; -import static org.mockito.Mockito.verify; -import static org.mockito.Matchers.eq; - public class QuestionnaireDataServiceTest { public static final Version VERSION = new Version(0, 1); private QuestionnaireDataService questionnaireDataService;// = new QuestionnaireDataServiceImpl(); - @Mock - private VendorSoftwareProductDao vendorSoftwareProductDaoMock; @Mock private CandidateService candidateServiceMock; @Mock @@ -73,8 +66,6 @@ public class QuestionnaireDataServiceTest { private ServiceModelDao serviceModelDaoMock; @Mock private CompositionEntityDataManager compositionEntityDataManagerMock; - @Mock - private ActivityLogManager activityLogManagerMock; @Captor private ArgumentCaptor activityLogEntityArg; @@ -82,7 +73,7 @@ public class QuestionnaireDataServiceTest { @InjectMocks private OrchestrationTemplateCandidateManagerImpl candidateManager; - private final UploadFileTest uploadFileTest = new UploadFileTest(); + private UploadFileTest uploadFileTest = new UploadFileTest(); private static String vspId; private static Version vspActiveVersion; @@ -110,31 +101,27 @@ public class QuestionnaireDataServiceTest { // TODO: 3/15/2017 fix and enable //@Test public void testQuestionnaireDataAfterIllegalUpload() throws IOException { - try (InputStream zipInputStream = uploadFileTest.getZipInputStream("/missingYml")) { - UploadFileResponse uploadFileResponse = candidateManager - .upload(vspId, VERSION, zipInputStream, USER1, "zip", "missingYml"); + UploadFileResponse uploadFileResponse = + candidateManager.upload(vspId, VERSION, zipInputStream, "zip", "missingYml"); } - InformationArtifactData informationArtifactData = questionnaireDataService .generateQuestionnaireDataForInformationArtifact(vspId, vspActiveVersion); } private InformationArtifactData uploadFileAndValidateInformationArtifactData(String filePath, - int listSizeToCheck) throws IOException { + int listSizeToCheck) + throws IOException { try (InputStream zipInputStream = uploadFileTest.getZipInputStream(filePath)) { - UploadFileResponse uploadFileResponse = candidateManager - .upload(vspId, VERSION, - zipInputStream, USER1, "zip", "file"); - - candidateManager.process(vspId, VERSION, USER1); + UploadFileResponse uploadFileResponse = + candidateManager.upload(vspId, VERSION, zipInputStream, "zip", "file"); + candidateManager.process(vspId, VERSION); Assert.assertTrue(MapUtils.isEmpty( MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, uploadFileResponse.getErrors()))); } - InformationArtifactData informationArtifactData = questionnaireDataService .generateQuestionnaireDataForInformationArtifact(vspId, vspActiveVersion); Assert.assertNotNull(informationArtifactData); @@ -143,11 +130,6 @@ public class QuestionnaireDataServiceTest { informationArtifactData.getComponentQuestionnaires(); Assert.assertEquals(componentQuestionnaireList.size(), listSizeToCheck); - verify(activityLogManagerMock).addActionLog(activityLogEntityArg.capture(),eq(USER1)); - ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue(); - Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION.getMajor()+1)); - Assert.assertTrue(activityLogEntity.isSuccess()); - return informationArtifactData; } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentDependencyModelTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentDependencyModelTest.java index c3f78b6cb0..a2cbaa7eb6 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentDependencyModelTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentDependencyModelTest.java @@ -6,136 +6,217 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy; 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.vendorsoftwareproduct.ComponentManager; -import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.errors.ComponentDependencyModelErrorBuilder; import org.openecomp.sdc.versioning.dao.types.Version; import org.testng.Assert; -import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.when; + public class ComponentDependencyModelTest { - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); + private static final String VSP_ID = "vsp_id"; + private static final Version VERSION = new Version("version_id"); + private static final String COMP_DEP_ID = "comp_dep_id"; + + private static final String COMP_ID_1 = "comp_id_1"; + private static final String COMP_ID_2 = "comp_id_2"; + private static final String COMP_ID_3 = "comp_id_3"; + private static final String COMP_ID_4 = "comp_id_4"; @Spy @InjectMocks private ComponentDependencyModelManagerImpl componentDependencyModelManager; @Mock - private VendorSoftwareProductManager vendorSoftwareProductManager; - @Mock - private VendorSoftwareProductDao vendorSoftwareProductDao; - @Mock - private ComponentDao componentDao; - @Mock private ComponentManager componentManager; + @Mock + private ComponentDependencyModelDao componentDependencyModelDao; - private static String vsp1Id; - private static String sourceComp1Id; - private static String sourceComp2Id; - private static String sourceComp3Id; - private static String sourceComp4Id; - private static final String USER1 = "TestUser1"; - private static final String USER2 = "TestUser2"; - private static final Version VERSION01 = new Version(0, 1); - private static String modelId = "model1"; - - - @BeforeClass + @BeforeMethod private void init() { MockitoAnnotations.initMocks(this); } - public static VspDetails createVspDetails(String id, Version version, String name, String desc, - String vendorName, String vlm, String icon, - String category, String subCategory, - String licenseAgreement, List featureGroups - ) { - VspDetails vspDetails = new VspDetails(id, version); - vspDetails.setName(name); - vspDetails.setDescription(desc); - vspDetails.setIcon(icon); - vspDetails.setCategory(category); - vspDetails.setSubCategory(subCategory); - vspDetails.setVendorName(vendorName); - vspDetails.setVendorId(vlm); - vspDetails.setVlmVersion(new Version(1, 0)); - vspDetails.setLicenseAgreement(licenseAgreement); - vspDetails.setFeatureGroups(featureGroups); - return vspDetails; + @Test + public void testListDependency() { + List entities = new ArrayList<>(); + entities.add(createModelEntity(COMP_ID_1, COMP_ID_2)); + entities.add(createModelEntity(COMP_ID_3, COMP_ID_4)); + + Mockito.when(componentDependencyModelDao + .list(new ComponentDependencyModelEntity(VSP_ID, VERSION, null))) + .thenReturn(entities); + + Collection list = + componentDependencyModelManager.list(VSP_ID, VERSION); + + Mockito.verify(componentDependencyModelDao, Mockito.times(1)) + .list(new ComponentDependencyModelEntity(VSP_ID, VERSION, null)); + + Assert.assertEquals(2, list.size()); + } + + @Test + public void testCreateDependency() { + ComponentDependencyModelEntity modelEntity = + createModelEntity(COMP_ID_1, COMP_ID_2); + + componentDependencyModelManager.createComponentDependency(modelEntity, VSP_ID, VERSION); + Mockito.verify(componentDependencyModelDao, Mockito.times(1)).create(modelEntity); + } + + @Test + public void testCreateDependencyNegative_SameSourceTarget() { + ComponentDependencyModelEntity modelEntity = + createModelEntity(COMP_ID_1, COMP_ID_1); + testCreateDependency_negative(modelEntity, VSP_ID, VERSION, + ComponentDependencyModelErrorBuilder.getSourceTargetComponentEqualErrorBuilder().id(), + ComponentDependencyModelErrorBuilder.getSourceTargetComponentEqualErrorBuilder().message()); } @Test - public void testCreateNegative_NoSourceId() { - List entities = new ArrayList(); - entities.add(createModelEntity(null, sourceComp2Id)); - testCreate_negative(entities, vsp1Id, VERSION01, USER1, + public void testCreateDependencyNegative_NoSourceId() { + + ComponentDependencyModelEntity modelEntity = createModelEntity(null, COMP_ID_1); + testCreateDependency_negative(modelEntity, VSP_ID, VERSION, ComponentDependencyModelErrorBuilder.getNoSourceComponentErrorBuilder().id(), ComponentDependencyModelErrorBuilder.getNoSourceComponentErrorBuilder().message()); - entities.clear(); - entities.add(createModelEntity("", sourceComp2Id)); - testCreate_negative(entities, vsp1Id, VERSION01, USER1, + + ComponentDependencyModelEntity modelEntity1 = createModelEntity("", COMP_ID_1); + testCreateDependency_negative(modelEntity1, VSP_ID, VERSION, ComponentDependencyModelErrorBuilder.getNoSourceComponentErrorBuilder().id(), ComponentDependencyModelErrorBuilder.getNoSourceComponentErrorBuilder().message()); } @Test - public void testCreateNegative_SameSourceTarget() { - List entities = new ArrayList(); - entities.add(createModelEntity("sourceComp1Id", "sourceComp1Id")); - testCreate_negative(entities, vsp1Id, VERSION01, USER1, + public void testUpdateDependency() { + ComponentDependencyModelEntity modelEntity = + createModelEntity(COMP_ID_1, COMP_ID_2); + modelEntity.setId(COMP_DEP_ID); + + when(componentDependencyModelDao.get(anyObject())).thenReturn(modelEntity); + + componentDependencyModelManager.update(modelEntity); + Mockito.verify(componentDependencyModelDao, Mockito.times(1)).update(modelEntity); + } + + @Test + public void testUpdateDependencyNegative_NoSourceId() { + + ComponentDependencyModelEntity modelEntity = createModelEntity(null, COMP_ID_1); + modelEntity.setId(COMP_DEP_ID); + + when(componentDependencyModelDao.get(anyObject())).thenReturn(modelEntity); + + testUpdateDependency_negative(modelEntity, + ComponentDependencyModelErrorBuilder.getNoSourceComponentErrorBuilder().id(), + ComponentDependencyModelErrorBuilder.getNoSourceComponentErrorBuilder().message()); + + ComponentDependencyModelEntity modelEntity1 = createModelEntity("", COMP_ID_1); + modelEntity1.setId(COMP_DEP_ID); + + when(componentDependencyModelDao.get(anyObject())).thenReturn(modelEntity1); + + testUpdateDependency_negative(modelEntity1, + ComponentDependencyModelErrorBuilder.getNoSourceComponentErrorBuilder().id(), + ComponentDependencyModelErrorBuilder.getNoSourceComponentErrorBuilder().message()); + } + + @Test + public void testUpdateDependencyNegative_SameSourceTarget() { + ComponentDependencyModelEntity modelEntity = + createModelEntity(COMP_ID_1, COMP_ID_1); + modelEntity.setId(COMP_DEP_ID); + + when(componentDependencyModelDao.get(anyObject())).thenReturn(modelEntity); + testUpdateDependency_negative(modelEntity, ComponentDependencyModelErrorBuilder.getSourceTargetComponentEqualErrorBuilder().id(), ComponentDependencyModelErrorBuilder.getSourceTargetComponentEqualErrorBuilder().message()); } @Test - public void testCreate() { - List entities = new ArrayList(); - entities.add(createModelEntity("sourceComp1Id", "sourceComp2Id")); - entities.add(createModelEntity("sourceComp3Id", "sourceComp4Id")); - - componentDependencyModelManager.createComponentDependencyModel(entities, vsp1Id, VERSION01, - USER1); - Mockito.verify(vendorSoftwareProductDao, Mockito.times(1)).createComponentDependencyModel - (entities, vsp1Id, - VERSION01); + public void testDeleteDependency() { + ComponentDependencyModelEntity modelEntity = + createModelEntity(COMP_ID_1, COMP_ID_2); + modelEntity.setId(COMP_DEP_ID); + + when(componentDependencyModelDao.get(anyObject())).thenReturn(modelEntity); + + componentDependencyModelManager.delete(VSP_ID, VERSION, COMP_DEP_ID); + Mockito.verify(componentDependencyModelDao, Mockito.times(1)).delete(modelEntity); + } + + @Test + public void testDeleteInvalidDependency() { + ComponentDependencyModelEntity delModelEntity = + createModelEntity(COMP_ID_1, COMP_ID_2); + delModelEntity.setId(COMP_DEP_ID); + + try { + componentDependencyModelManager.delete(VSP_ID, VERSION, COMP_DEP_ID); + Assert.fail(); + } catch (CoreException exception) { + Assert.assertEquals(exception.code().id(), "VERSIONABLE_SUB_ENTITY_NOT_FOUND"); + Assert.assertEquals(exception.getMessage(), + String.format("Vendor Software Product Component Dependency Model with Id %s " + + "does not exist for Vendor Software Product with id %s and version %s", + COMP_DEP_ID, VSP_ID, VERSION.getId())); + } + } + + + @Test + public void testGetDependency() { + ComponentDependencyModelEntity modelEntity = + createModelEntity(COMP_ID_1, COMP_ID_2); + modelEntity.setId(COMP_DEP_ID); + + when(componentDependencyModelDao.get(anyObject())).thenReturn(modelEntity); + + ComponentDependencyModelEntity retrieved = + componentDependencyModelManager.get(VSP_ID, VERSION, COMP_DEP_ID); + + Assert.assertEquals(retrieved.getSourceComponentId(), COMP_ID_1); + } private ComponentDependencyModelEntity createModelEntity(String sourceId, String targetId) { ComponentDependencyModelEntity entity = - new ComponentDependencyModelEntity(vsp1Id, VERSION01, modelId); + new ComponentDependencyModelEntity(VSP_ID, VERSION, COMP_DEP_ID); entity.setSourceComponentId(sourceId); entity.setTargetComponentId(targetId); entity.setRelation("dependsOn"); return entity; } - private Collection getDependencyModel(String vspId, - Version version, - String user) { - return componentDependencyModelManager.list(vspId, version, user); + private void testCreateDependency_negative(ComponentDependencyModelEntity entity, String vspId, + Version version, String expectedErrorCode, + String expectedErrorMsg) { + try { + componentDependencyModelManager.createComponentDependency(entity, vspId, version); + Assert.fail(); + } catch (CoreException exception) { + Assert.assertEquals(exception.code().id(), expectedErrorCode); + Assert.assertEquals(exception.getMessage(), expectedErrorMsg); + } } - private void testCreate_negative(List entities, String vspId, - Version version, String user, - String expectedErrorCode, String expectedErrorMsg) { + private void testUpdateDependency_negative(ComponentDependencyModelEntity entity, + String expectedErrorCode, String expectedErrorMsg) { try { - componentDependencyModelManager.createComponentDependencyModel(entities, vspId, version, - user); + componentDependencyModelManager.update(entity); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); Assert.assertEquals(exception.getMessage(), expectedErrorMsg); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentManagerImplTest.java index ee8295cafc..c7aa81873b 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentManagerImplTest.java @@ -2,12 +2,9 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy; 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.vendorsoftwareproduct.NicManager; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; @@ -37,16 +34,13 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; public class ComponentManagerImplTest { - - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); - - private static final String COMP_NOT_EXIST_MSG = - "Vendor Software Product Component with Id 1 does not exist for Vendor Software Product with id VSP_ID and version 0.1"; - private static final String USER = "componentsTestUser"; private static final String VSP_ID = "VSP_ID"; - private static final Version VERSION = new Version(0, 1); - private static final String COMP1_ID = "1"; - private static final String COMP2_ID = "2"; + private static final Version VERSION = new Version("version_id"); + private static final String COMP1_ID = "comp1"; + private static final String COMP2_ID = "comp2"; + private static final String COMP_NOT_EXIST_MSG = + "Vendor Software Product Component with Id comp1 does not exist " + + "for Vendor Software Product with id VSP_ID and version version_id"; @Mock private ComponentDao componentDaoMock; @@ -67,20 +61,15 @@ public class ComponentManagerImplTest { @Test public void testListWhenNone() { - Collection components = - componentManager.listComponents(VSP_ID, VERSION, USER); + Collection components = componentManager.listComponents(VSP_ID, VERSION); Assert.assertEquals(components.size(), 0); } @Test(expectedExceptions = CoreException.class, - expectedExceptionsMessageRegExp = "Vendor Software Product Component with Id dummyComponentId " + - "does not exist for Vendor Software Product with id dummyVsp and version 1.0") + expectedExceptionsMessageRegExp = COMP_NOT_EXIST_MSG) public void validateExceptionWhenTryingToRetriveNotExistingComponentEntity() { - Version version = Mockito.mock(Version.class); - doReturn("1.0").when(version).toString(); doReturn(null).when(componentDaoMock).get(anyObject()); - componentManager.validateComponentExistence("dummyVsp", version, "dummyComponentId", - "dummyUser"); + componentManager.validateComponentExistence(VSP_ID, VERSION, COMP1_ID); } @Test @@ -90,21 +79,20 @@ public class ComponentManagerImplTest { createComponent(VSP_ID, VERSION, COMP2_ID))) .when(componentDaoMock).list(anyObject()); - Collection actual = - componentManager.listComponents(VSP_ID, VERSION, USER); + Collection actual = componentManager.listComponents(VSP_ID, VERSION); Assert.assertEquals(actual.size(), 2); } @Test public void testDeleteListOnUploadVsp_negative() { - testDeleteList_negative(VSP_ID, VERSION, USER, + testDeleteList_negative(VSP_ID, VERSION, VendorSoftwareProductErrorCodes.VSP_COMPOSITION_EDIT_NOT_ALLOWED); } -/* @Test - public void testCreate() { - COMP1_ID = testCreate(VSP_ID); - }*/ + /* @Test + public void testCreate() { + COMP1_ID = testCreate(VSP_ID); + }*/ @Test public void testCreate() { ComponentEntity expected = new ComponentEntity(VSP_ID, null, null); @@ -113,12 +101,12 @@ public class ComponentManagerImplTest { compData.setDescription("comp1 desc"); expected.setComponentCompositionData(compData); - doReturn(true).when(vspInfoDao).isManual(anyObject(),anyObject()); + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); Collection vspComponentList = new ArrayList<>(); doReturn(vspComponentList).when(componentDaoMock).list(anyObject()); doReturn(expected).when(compositionEntityDataManagerMock).createComponent(anyObject()); - ComponentEntity created = componentManager.createComponent(expected, USER); + ComponentEntity created = componentManager.createComponent(expected); Assert.assertNotNull(created); //expected.setId(created.getId()); //expected.setVersion(VERSION); @@ -137,15 +125,14 @@ public class ComponentManagerImplTest { compData.setDescription("comp1 desc"); expected.setComponentCompositionData(compData); - doReturn(true).when(vspInfoDao).isManual(anyObject(),anyObject()); + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); Collection vspComponentList = new ArrayList<>(); vspComponentList.add(expected); doReturn(vspComponentList).when(componentDaoMock).list(anyObject()); try { - ComponentEntity created = componentManager.createComponent(expected, USER); - } catch (CoreException exception) { - log.debug("",exception); + ComponentEntity created = componentManager.createComponent(expected); + } catch (CoreException exception) { Assert.assertEquals("Creation of only one VFC per VSP allowed.", exception.code().message()); Assert.assertEquals(VendorSoftwareProductErrorCodes.VSP_VFC_COUNT_EXCEED, exception.code().id()); @@ -161,14 +148,14 @@ public class ComponentManagerImplTest { expected.setComponentCompositionData(compData); doReturn(expected).when(componentDaoMock).get(anyObject()); - doReturn(true).when(vspInfoDao).isManual(anyObject(),anyObject()); + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); Collection vspComponentList = new ArrayList<>(); vspComponentList.add(expected); doReturn(vspComponentList).when(componentDaoMock).list(anyObject()); - doReturn(new CompositionEntityValidationData(null,null)).when(compositionEntityDataManagerMock) - .validateEntity(anyObject(),anyObject(),anyObject()); + doReturn(new CompositionEntityValidationData(null, null)).when(compositionEntityDataManagerMock) + .validateEntity(anyObject(), anyObject(), anyObject()); - CompositionEntityValidationData created = componentManager.updateComponent(expected, USER); + CompositionEntityValidationData created = componentManager.updateComponent(expected); Assert.assertNotNull(created); } @@ -182,20 +169,19 @@ public class ComponentManagerImplTest { expected.setComponentCompositionData(compData); doReturn(expected).when(componentDaoMock).get(anyObject()); - doReturn(true).when(vspInfoDao).isManual(anyObject(),anyObject()); + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); Collection vspComponentList = new ArrayList<>(); vspComponentList.add(expected); - ComponentEntity expected2 = new ComponentEntity(VSP_ID+"2", null, COMP1_ID+"2"); + ComponentEntity expected2 = new ComponentEntity(VSP_ID + "2", null, COMP1_ID + "2"); expected2.setComponentCompositionData(compData); vspComponentList.add(expected2); doReturn(vspComponentList).when(componentDaoMock).list(anyObject()); - doReturn(new CompositionEntityValidationData(null,null)).when(compositionEntityDataManagerMock) - .validateEntity(anyObject(),anyObject(),anyObject()); + doReturn(new CompositionEntityValidationData(null, null)).when(compositionEntityDataManagerMock) + .validateEntity(anyObject(), anyObject(), anyObject()); try { - CompositionEntityValidationData created = componentManager.updateComponent(expected, USER); - } catch (CoreException exception) { - log.debug("",exception); + CompositionEntityValidationData created = componentManager.updateComponent(expected); + } catch (CoreException exception) { Assert.assertEquals("VFC with specified name already present in given VSP.", exception.code().message()); Assert.assertEquals(VendorSoftwareProductErrorCodes.VSP_VFC_DUPLICATE_NAME, @@ -220,7 +206,7 @@ public class ComponentManagerImplTest { @Test public void testCreateOnUploadVsp_negative() { - testCreate_negative(new ComponentEntity(VSP_ID, VERSION, null), USER, + testCreate_negative(new ComponentEntity(VSP_ID, VERSION, null), VendorSoftwareProductErrorCodes.VFC_ADD_NOT_ALLOWED_IN_HEAT_ONBOARDING); } @@ -229,7 +215,7 @@ public class ComponentManagerImplTest { String componentId = "non existing component id"; doReturn(null).when(componentDaoMock).get(anyObject()); - testUpdate_negative(VSP_ID, VERSION, componentId, USER, + testUpdate_negative(VSP_ID, VERSION, componentId, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @@ -254,7 +240,7 @@ public class ComponentManagerImplTest { CompositionEntityValidationData validationData = - componentManager.updateComponent(component, USER); + componentManager.updateComponent(component); Assert.assertTrue(validationData == null || validationData.getErrors() == null); verify(componentDaoMock).update(component); } @@ -277,7 +263,7 @@ public class ComponentManagerImplTest { component.setComponentCompositionData(compData); CompositionEntityValidationData validationData = - componentManager.updateComponent(component, USER); + componentManager.updateComponent(component); Assert.assertNotNull(validationData); Assert.assertEquals(validationData.getErrors().size(), 2); @@ -289,7 +275,7 @@ public class ComponentManagerImplTest { String componentId = "non existing component id"; doReturn(null).when(componentDaoMock).get(anyObject()); - testGet_negative(VSP_ID, VERSION, componentId, USER, + testGet_negative(VSP_ID, VERSION, componentId, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @@ -300,7 +286,7 @@ public class ComponentManagerImplTest { doReturn("schema string").when(componentManager).getComponentCompositionSchema(anyObject()); - testGet(VSP_ID, VERSION, COMP1_ID, USER, expected); + testGet(VSP_ID, VERSION, COMP1_ID, expected); } @@ -329,14 +315,14 @@ public class ComponentManagerImplTest { @Test public void testDeleteOnUploadVsp_negative() { - testDelete_negative(VSP_ID, VERSION, COMP1_ID, USER, + testDelete_negative(VSP_ID, VERSION, COMP1_ID, VendorSoftwareProductErrorCodes.VSP_COMPOSITION_EDIT_NOT_ALLOWED); } @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = COMP_NOT_EXIST_MSG) public void testGetNonExistingComponentQuestionnaire() throws Exception { - componentManager.getQuestionnaire(VSP_ID, VERSION, COMP1_ID, USER); + componentManager.getQuestionnaire(VSP_ID, VERSION, COMP1_ID); } @Test @@ -347,7 +333,7 @@ public class ComponentManagerImplTest { doReturn(schema).when(componentManager).getComponentQuestionnaireSchema(anyObject()); QuestionnaireResponse questionnaire = - componentManager.getQuestionnaire(VSP_ID, VERSION, COMP1_ID, USER); + componentManager.getQuestionnaire(VSP_ID, VERSION, COMP1_ID); Assert.assertNotNull(questionnaire); Assert.assertEquals(questionnaire.getData(), null); Assert.assertEquals(questionnaire.getSchema(), schema); @@ -372,13 +358,13 @@ public class ComponentManagerImplTest { nicEntity2.setNicCompositionData(nic2); doReturn(Arrays.asList(nicEntity1, nicEntity2)) - .when(nicManagerMock).listNics(VSP_ID, VERSION, COMP1_ID, USER); + .when(nicManagerMock).listNics(VSP_ID, VERSION, COMP1_ID); String schema = "schema string"; doReturn(schema).when(componentManager).getComponentQuestionnaireSchema(anyObject()); QuestionnaireResponse questionnaire = - componentManager.getQuestionnaire(VSP_ID, VERSION, COMP1_ID, USER); + componentManager.getQuestionnaire(VSP_ID, VERSION, COMP1_ID); Assert.assertNotNull(questionnaire); Assert.assertEquals(questionnaire.getData(), component.getQuestionnaireData()); Assert.assertEquals(questionnaire.getSchema(), schema); @@ -389,7 +375,7 @@ public class ComponentManagerImplTest { expectedExceptionsMessageRegExp = COMP_NOT_EXIST_MSG) public void testUpdateNonExistingComponentQuestionnaire() throws Exception { doReturn(null).when(componentDaoMock).get(anyObject()); - componentManager.updateQuestionnaire(VSP_ID, VERSION, COMP1_ID, "questionnaire data", USER); + componentManager.updateQuestionnaire(VSP_ID, VERSION, COMP1_ID, "questionnaire data"); } @Test @@ -397,7 +383,7 @@ public class ComponentManagerImplTest { ComponentEntity component = createComponent(VSP_ID, VERSION, COMP1_ID); doReturn(component).when(componentDaoMock).get(anyObject()); - componentManager.updateQuestionnaire(VSP_ID, VERSION, COMP1_ID, "questionnaire data", USER); + componentManager.updateQuestionnaire(VSP_ID, VERSION, COMP1_ID, "questionnaire data"); verify(componentDaoMock) .updateQuestionnaireData(VSP_ID, VERSION, COMP1_ID, "questionnaire data"); @@ -417,79 +403,72 @@ public class ComponentManagerImplTest { Assert.assertEquals(actual.size(), 0); }*/ - private void testGet(String vspId, Version version, String componentId, String user, + private void testGet(String vspId, Version version, String componentId, ComponentEntity expected) { CompositionEntityResponse - response = componentManager.getComponent(vspId, version, componentId, user); + response = componentManager.getComponent(vspId, version, componentId); Assert.assertEquals(response.getId(), expected.getId()); Assert.assertEquals(response.getData(), expected.getComponentCompositionData()); Assert.assertNotNull(response.getSchema()); } - private void testCreate_negative(ComponentEntity component, String user, + private void testCreate_negative(ComponentEntity component, String expectedErrorCode) { try { - componentManager.createComponent(component, user); + componentManager.createComponent(component); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } - private void testGet_negative(String vspId, Version version, String componentId, String user, + private void testGet_negative(String vspId, Version version, String componentId, String expectedErrorCode) { try { - componentManager.getComponent(vspId, version, componentId, user); + componentManager.getComponent(vspId, version, componentId); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } - private void testUpdate_negative(String vspId, Version version, String componentId, String user, + private void testUpdate_negative(String vspId, Version version, String componentId, String expectedErrorCode) { try { - componentManager - .updateComponent(new ComponentEntity(vspId, version, componentId), user); + componentManager.updateComponent(new ComponentEntity(vspId, version, componentId)); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } - private void testList_negative(String vspId, Version version, String user, + private void testList_negative(String vspId, Version version, String expectedErrorCode) { try { - componentManager.listComponents(vspId, version, user); + componentManager.listComponents(vspId, version); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } - private void testDeleteList_negative(String vspId, Version version, String user, + private void testDeleteList_negative(String vspId, Version version, String expectedErrorCode) { try { - componentManager.deleteComponents(vspId, version, user); + componentManager.deleteComponents(vspId, version); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } - private void testDelete_negative(String vspId, Version version, String componentId, String user, + private void testDelete_negative(String vspId, Version version, String componentId, String expectedErrorCode) { try { - componentManager.deleteComponent(vspId, version, componentId, user); + componentManager.deleteComponent(vspId, version, componentId); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComputeManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComputeManagerImplTest.java index eda5693cce..9058a73632 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComputeManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComputeManagerImplTest.java @@ -1,378 +1,348 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; 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.vendorsoftwareproduct.NetworkManager; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; import org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager; 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.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.versioning.dao.types.Version; import org.openecomp.sdc.versioning.errors.VersioningErrorCodes; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.List; -public class ComputeManagerImplTest { +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); +public class ComputeManagerImplTest { - private static final String COMPUTE_NOT_EXIST_MSG = - "Vendor Software Product COMPUTE with Id compute1 does not exist for Vendor Software Product with " + - "id VSP_ID and version 0.1"; + private static final String COMPUTE_NOT_EXIST_MSG = + "Vendor Software Product COMPUTE with Id compute1 does not exist for Vendor Software Product with " + + "id VSP_ID and version version_id"; - private static final String USER = "computeTestUser"; - private static final String VSP_ID = "VSP_ID"; - private static final Version VERSION = new Version(0, 1); - private static final String COMPONENT_ID = "COMPONENT_ID"; - private static final String COMPUTE1_ID = "compute1"; - private static final String COMPUTE2_ID = "compute2"; + private static final String VSP_ID = "VSP_ID"; + private static final Version VERSION = new Version("version_id"); + private static final String COMPONENT_ID = "COMPONENT_ID"; + private static final String COMPUTE1_ID = "compute1"; + private static final String COMPUTE2_ID = "compute2"; @Mock private ComputeDao computeDao; - @Mock private CompositionEntityDataManager compositionEntityDataManagerMock; - - @Mock - private NetworkManager networkManagerMock; - @Mock private VendorSoftwareProductInfoDao vspInfoDao; - - @Mock - private ComputeEntity computeEntity; - - @Mock - private ListComputeResponse listComputeResponse; - - @Mock - private DeploymentFlavorEntity deploymentFlavorEntity; - @Mock private DeploymentFlavorDao deploymentFlavorDao; - - @Mock - private ComponentComputeAssociation componentComputeAssociation; - - @Mock - DeploymentFlavor deploymentFlavor; - @InjectMocks @Spy private ComputeManagerImpl computeManager; @BeforeMethod public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.initMocks(this); } - @Test + @Test public void testListWhenNone() { - Collection computes = computeManager.listCompute(VSP_ID, VERSION, COMPONENT_ID, USER); + Collection computes = + computeManager.listComputes(VSP_ID, VERSION, COMPONENT_ID); Assert.assertEquals(computes.size(), 0); } @Test - public void testList(){ - doReturn(Arrays.asList( + public void testList() { + doReturn(Arrays.asList( createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID), createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE2_ID))) - .when(computeDao).list(anyObject()); - + .when(computeDao).list(anyObject()); - Collection computes = computeManager.listCompute(VSP_ID, VERSION, COMPONENT_ID, USER); - Assert.assertEquals(computes.size(), 2); - for (ListComputeResponse compute : computes) { - Assert.assertEquals(compute.getComputeEntity().getComputeCompositionData().getName(), - COMPUTE1_ID.equals(compute.getComputeEntity().getId()) - ? "compute1name" - : "compute2name"); - }; - } - @Test - public void testCreateOnNotManualCompute_negative() { - - testCreate_negative(new ComputeEntity(VSP_ID, VERSION, COMPONENT_ID, null), USER, - VendorSoftwareProductErrorCodes.ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING); - } - - @Test - public void testCreateManualCompute() { - ComputeEntity expected = createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - computeManager.createCompute(expected, USER); - verify(compositionEntityDataManagerMock).createCompute(expected); - verify(compositionEntityDataManagerMock).createCompute(expected); - } - - @Test - public void testCreateManualComputeWithDuplicateName() { - ComputeEntity expected = createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - - ComputeEntity expectedDiffName = createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); - expectedDiffName.setId(COMPUTE1_ID + "Name"); - ComputeData computeData = expectedDiffName.getComputeCompositionData(); - computeData.setName(COMPUTE1_ID + "Name"); - expectedDiffName.setComputeCompositionData(computeData); - List vfcImageList = new ArrayList(); - vfcImageList.add(expectedDiffName); - doReturn(vfcImageList).when(computeDao).list(anyObject()); - - try { - computeManager.createCompute(expected, USER); - Assert.fail(); - } - catch (CoreException ex) { - log.debug("",ex); - Assert.assertEquals(VendorSoftwareProductErrorCodes.DUPLICATE_COMPUTE_NAME_NOT_ALLOWED, - ex.code().id()); - } - } - - @Test - public void testUpdateNonExistingComputeId_negative() { - - testUpdate_negative(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID, USER, - VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); + Collection computes = + computeManager.listComputes(VSP_ID, VERSION, COMPONENT_ID); + Assert.assertEquals(computes.size(), 2); + for (ListComputeResponse compute : computes) { + Assert.assertEquals(compute.getComputeEntity().getComputeCompositionData().getName(), + COMPUTE1_ID.equals(compute.getComputeEntity().getId()) + ? "compute1name" + : "compute2name"); } + } - @Test - public void testUpdateCompute() { - doReturn(createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID)) - .when(computeDao).get(anyObject()); - - doReturn(new CompositionEntityValidationData(CompositionEntityType.compute, COMPUTE1_ID)) - .when(compositionEntityDataManagerMock) - .validateEntity(anyObject(), anyObject(), anyObject()); - - ComputeEntity computeEntity = new ComputeEntity(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); - ComputeData computeData = new ComputeData(); - computeData.setName(COMPUTE1_ID + "name"); - computeData.setDescription(COMPUTE1_ID + "desc updated"); - computeEntity.setComputeCompositionData(computeData); - - CompositionEntityValidationData validationData = - computeManager.updateCompute(computeEntity, USER); - Assert.assertTrue(validationData == null || validationData.getErrors() == null); - verify(computeDao).update(computeEntity); - } + @Test + public void testCreateOnNotManualCompute_negative() { + testCreate_negative(new ComputeEntity(VSP_ID, VERSION, COMPONENT_ID, null), + VendorSoftwareProductErrorCodes.ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING); + } - @Test - public void testIllegalComputeUpdate() { - doReturn(createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID)) - .when(computeDao).get(anyObject()); + @Test + public void testCreateManualCompute() { + ComputeEntity expected = createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); + doNothing().when(computeManager) + .validateUniqueName(VSP_ID, VERSION, COMPONENT_ID, + expected.getComputeCompositionData().getName()); + doNothing().when(computeManager) + .createUniqueName(VSP_ID, VERSION, COMPONENT_ID, + expected.getComputeCompositionData().getName()); + String questionnaireSchema = "{}"; + doReturn(questionnaireSchema).when(computeManager).getComputeQuestionnaireSchema(anyObject()); + + computeManager.createCompute(expected); + verify(computeDao).create(expected); + } - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); + @Test(expectedExceptions = CoreException.class) + public void testCreateManualComputeWithDuplicateName() { + ComputeEntity expected = createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - CompositionEntityValidationData toBeReturned = - new CompositionEntityValidationData(CompositionEntityType.compute, COMPUTE1_ID); - toBeReturned.setErrors(Arrays.asList("error1", "error2")); - doReturn(toBeReturned) - .when(compositionEntityDataManagerMock) - .validateEntity(anyObject(), anyObject(), anyObject()); + doThrow(new CoreException( + new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).build())) + .when(computeManager).validateUniqueName(VSP_ID, VERSION, COMPONENT_ID, + expected.getComputeCompositionData().getName()); - ComputeEntity computeEntity = new ComputeEntity(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); - ComputeData computeData = new ComputeData(); - computeData.setName(COMPUTE1_ID + "_name_updated"); - computeData.setDescription(COMPUTE1_ID + " desc updated"); - computeEntity.setComputeCompositionData(computeData); + computeManager.createCompute(expected); + } - CompositionEntityValidationData validationData = computeManager.updateCompute(computeEntity, USER); - Assert.assertNotNull(validationData); - Assert.assertEquals(validationData.getErrors().size(), 2); + @Test + public void testUpdateNonExistingComputeId_negative() { + testUpdate_negative(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID, + VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); + } - verify(computeDao, never()).update(computeEntity); - } + @Test + public void testUpdateCompute() { + ComputeEntity retrieved = createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); + doReturn(retrieved).when(computeDao).get(anyObject()); + + doReturn(new CompositionEntityValidationData(CompositionEntityType.compute, COMPUTE1_ID)) + .when(compositionEntityDataManagerMock) + .validateEntity(anyObject(), anyObject(), anyObject()); + + ComputeEntity computeEntity = new ComputeEntity(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); + ComputeData computeData = new ComputeData(); + computeData.setName(COMPUTE1_ID + "name"); + computeData.setDescription(COMPUTE1_ID + "desc updated"); + computeEntity.setComputeCompositionData(computeData); + + doNothing().when(computeManager) + .updateUniqueName(VSP_ID, VERSION, COMPONENT_ID, retrieved.getComputeCompositionData().getName(), + computeData.getName()); + + CompositionEntityValidationData validationData = + computeManager.updateCompute(computeEntity); + Assert.assertTrue(validationData == null || validationData.getErrors() == null); + verify(computeDao).update(computeEntity); + } - @Test - public void testUpdateHEATComputeName() throws Exception { - doReturn(createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID)) - .when(computeDao).get(anyObject()); - ComputeEntity computeEntity = new ComputeEntity(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); - ComputeData computeData = new ComputeData(); - computeData.setName(COMPUTE1_ID + " name updated"); - computeData.setDescription(COMPUTE1_ID + " desc updated"); - computeEntity.setComputeCompositionData(computeData); - - try { - computeManager.updateCompute(computeEntity, USER); - } - catch (CoreException ex) { - log.debug("",ex); - Assert.assertEquals(ex.code().id(), VendorSoftwareProductErrorCodes.UPDATE_COMPUTE_NOT_ALLOWED); - } + @Test + public void testIllegalComputeUpdate() { + doReturn(createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID)) + .when(computeDao).get(anyObject()); + + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); + + CompositionEntityValidationData toBeReturned = + new CompositionEntityValidationData(CompositionEntityType.compute, COMPUTE1_ID); + toBeReturned.setErrors(Arrays.asList("error1", "error2")); + doReturn(toBeReturned) + .when(compositionEntityDataManagerMock) + .validateEntity(anyObject(), anyObject(), anyObject()); + + ComputeEntity computeEntity = new ComputeEntity(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); + ComputeData computeData = new ComputeData(); + computeData.setName(COMPUTE1_ID + "_name_updated"); + computeData.setDescription(COMPUTE1_ID + " desc updated"); + computeEntity.setComputeCompositionData(computeData); + + CompositionEntityValidationData validationData = + computeManager.updateCompute(computeEntity); + Assert.assertNotNull(validationData); + Assert.assertEquals(validationData.getErrors().size(), 2); + + verify(computeDao, never()).update(computeEntity); + } + @Test + public void testUpdateHEATComputeName() throws Exception { + doReturn(createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID)) + .when(computeDao).get(anyObject()); + ComputeEntity computeEntity = new ComputeEntity(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); + ComputeData computeData = new ComputeData(); + computeData.setName(COMPUTE1_ID + " name updated"); + computeData.setDescription(COMPUTE1_ID + " desc updated"); + computeEntity.setComputeCompositionData(computeData); + + try { + computeManager.updateCompute(computeEntity); + } catch (CoreException ex) { + Assert + .assertEquals(ex.code().id(), VendorSoftwareProductErrorCodes.UPDATE_COMPUTE_NOT_ALLOWED); } + } - @Test - public void testUpdateManualComputeQuestionnaire() throws Exception { - String json = "{\"md5\" :\"FFDSD33SS\"}"; - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - doReturn(new ComputeEntity(null,null,null,null)).when(computeDao).get(anyObject()); + @Test + public void testUpdateManualComputeQuestionnaire() throws Exception { + String json = "{\"md5\" :\"FFDSD33SS\"}"; + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); + doReturn(new ComputeEntity(null, null, null, null)).when(computeDao).get(anyObject()); + + computeManager + .updateComputeQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID, json); + verify(computeDao).updateQuestionnaireData(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID, json); + } - computeManager.updateComputeQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID, json, USER); - verify(computeDao).updateQuestionnaireData(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID, json); - } + @Test + public void testGetNonExistingComputeId_negative() { + testGet_negative(VSP_ID, VERSION, COMPONENT_ID, "non existing compute id", + VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); + } - @Test - public void testGetNonExistingComputeId_negative() { - testGet_negative(VSP_ID, VERSION, COMPONENT_ID, "non existing compute id", USER, - VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); - } + @Test + public void testGet() { + ComputeEntity expected = createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); + doReturn(expected).when(computeDao).get(anyObject()); + String compositionSchema = "schema string"; + doReturn(compositionSchema).when(computeManager).getComputeCompositionSchema(anyObject()); + + CompositionEntityResponse response = + computeManager.getCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); + Assert.assertEquals(response.getId(), expected.getId()); + Assert + .assertEquals(response.getData().getName(), expected.getComputeCompositionData().getName()); + Assert.assertEquals(response.getData().getDescription(), expected.getComputeCompositionData(). + getDescription()); + Assert.assertEquals(response.getSchema(), compositionSchema); + } - @Test - public void testGet() { - ComputeEntity expected = createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); - doReturn(expected).when(computeDao).get(anyObject()); - String compositionSchema = "schema string"; - doReturn(compositionSchema).when(computeManager).getComputeCompositionSchema(anyObject()); - - CompositionEntityResponse response = - computeManager.getCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID, USER); - Assert.assertEquals(response.getId(), expected.getId()); - Assert.assertEquals(response.getData().getName(), expected.getComputeCompositionData().getName()); - Assert.assertEquals(response.getData().getDescription(), expected.getComputeCompositionData(). - getDescription()); - Assert.assertEquals(response.getSchema(), compositionSchema); - } + @Test + public void testGetQuestionnaire() throws Exception { + ComputeEntity compute = new ComputeEntity(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); + compute.setQuestionnaireData("{}"); + doReturn(compute).when(computeDao) + .getQuestionnaireData(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); - @Test - public void testGetQuestionnaire() throws Exception { - ComputeEntity compute = new ComputeEntity(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); - compute.setQuestionnaireData("{}"); - doReturn(compute).when(computeDao).getQuestionnaireData(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); + String schema = "schema string"; - String schema = "schema string"; + doReturn(schema).when(computeManager).getComputeQuestionnaireSchema(anyObject()); + QuestionnaireResponse questionnaire = + computeManager.getComputeQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); - doReturn(schema).when(computeManager).getComputeQuestionnaireSchema(anyObject()); + Assert.assertNotNull(questionnaire); + Assert.assertEquals(questionnaire.getData(), compute.getQuestionnaireData()); + Assert.assertEquals(questionnaire.getSchema(), schema); + Assert.assertNull(questionnaire.getErrorMessage()); + } - QuestionnaireResponse questionnaire = - computeManager.getComputeQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID, USER); + @Test + public void testDeleteOnNotManualCompute() { + ComputeEntity expected = createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); + doReturn(expected).when(computeDao).get(anyObject()); + testDelete_negative(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID, + VendorSoftwareProductErrorCodes.VSP_COMPOSITION_EDIT_NOT_ALLOWED); + } - Assert.assertNotNull(questionnaire); - Assert.assertEquals(questionnaire.getData(), compute.getQuestionnaireData()); - Assert.assertEquals(questionnaire.getSchema(), schema); - Assert.assertNull(questionnaire.getErrorMessage()); - } + @Test + public void testDeleteOnManualCompute() { + ComputeEntity expected = createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); + doReturn(expected).when(computeDao).get(anyObject()); + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); + doNothing().when(computeManager).deleteUniqueValue(VSP_ID, VERSION, COMPONENT_ID, + expected.getComputeCompositionData().getName()); + + computeManager.deleteCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); + verify(computeDao).delete(anyObject()); + } - @Test - public void testDeleteOnNotManualCompute() { - ComputeEntity expected = createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); - doReturn(expected).when(computeDao).get(anyObject()); - testDelete_negative(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID, USER, - VendorSoftwareProductErrorCodes.VSP_COMPOSITION_EDIT_NOT_ALLOWED); - } + @Test + public void testDeleteOnNotExistCompute() { + testDelete_negative(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID, + VendorSoftwareProductErrorCodes.VSP_COMPOSITION_EDIT_NOT_ALLOWED); + } - @Test - public void testDeleteOnManualCompute() { - ComputeEntity expected = createCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID); - doReturn(expected).when(computeDao).get(anyObject()); - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - computeManager.deleteCompute(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID, USER); - verify(computeDao).delete(anyObject()); - } - @Test - public void testDeleteOnNotExistCompute() { - testDelete_negative(VSP_ID, VERSION, COMPONENT_ID, COMPUTE1_ID, USER, - VendorSoftwareProductErrorCodes.VSP_COMPOSITION_EDIT_NOT_ALLOWED); + private void testDelete_negative(String vspId, Version version, String componentId, + String computeId, + String expectedErrorCode) { + try { + computeManager.deleteCompute(vspId, version, componentId, computeId); + Assert.fail(); + } catch (CoreException exception) { + Assert.assertEquals(exception.code().id(), expectedErrorCode); } + } - - private void testDelete_negative(String vspId, Version version, String componentId, String computeId, - String user, - String expectedErrorCode) { - try { - computeManager.deleteCompute(vspId, version, componentId, computeId, user); - Assert.fail(); - } catch (CoreException exception) { - log.debug("",exception); - Assert.assertEquals(exception.code().id(), expectedErrorCode); - } + private void testGet_negative(String vspId, Version version, String componentId, String computeId, + String expectedErrorCode) { + try { + computeManager.getCompute(vspId, version, componentId, computeId); + Assert.fail(); + } catch (CoreException exception) { + Assert.assertEquals(exception.code().id(), expectedErrorCode); } - - private void testGet_negative(String vspId, Version version, String componentId, String computeId, - String user, String expectedErrorCode) { - try { - computeManager.getCompute(vspId, version, componentId, computeId, user); - Assert.fail(); - } catch (CoreException exception) { - log.debug("",exception); - Assert.assertEquals(exception.code().id(), expectedErrorCode); - } } - private void testList_negative(String vspId, Version version, String componentId, String user, - String expectedErrorCode, String expectedErrorMsg) { - try { - computeManager.listCompute(vspId, version, componentId, user); - Assert.fail(); - } catch (CoreException exception) { - log.debug("",exception); - Assert.assertEquals(exception.code().id(), expectedErrorCode); - Assert.assertEquals(exception.getMessage(), expectedErrorMsg); - } + private void testList_negative(String vspId, Version version, String componentId, + String expectedErrorCode, String expectedErrorMsg) { + try { + computeManager.listComputes(vspId, version, componentId); + Assert.fail(); + } catch (CoreException exception) { + Assert.assertEquals(exception.code().id(), expectedErrorCode); + Assert.assertEquals(exception.getMessage(), expectedErrorMsg); } + } - - private void testUpdate_negative(String vspId, Version version, String componentId, String computeId, - String user, String expectedErrorCode) { - try { - computeManager.updateCompute(new ComputeEntity(vspId, version, componentId, computeId), user); - Assert.fail(); - } catch (CoreException exception) { - log.debug("",exception); + private void testUpdate_negative(String vspId, Version version, String componentId, + String computeId, String expectedErrorCode) { + try { + computeManager.updateCompute(new ComputeEntity(vspId, version, componentId, computeId)); + Assert.fail(); + } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), expectedErrorCode); } } - private void testCreate_negative(ComputeEntity computeEntity1, String user, String expectedErrorCode) { - try { - computeManager.createCompute(computeEntity1, user); - Assert.fail(); - } catch (CoreException exception) { - log.debug("",exception); - Assert.assertEquals(exception.code().id(), expectedErrorCode); - } + private void testCreate_negative(ComputeEntity computeEntity1, String expectedErrorCode) { + try { + computeManager.createCompute(computeEntity1); + Assert.fail(); + } catch (CoreException exception) { + Assert.assertEquals(exception.code().id(), expectedErrorCode); } + } - static ComputeEntity createCompute(String vspId, Version version, String compId, String computeId){ - ComputeEntity computeEntity1 = new ComputeEntity(vspId, version, compId, computeId); - ComputeData computeData = new ComputeData(); - computeData.setName(computeId+"name"); - computeData.setDescription(computeId+"desc"); - computeEntity1.setComputeCompositionData(computeData); - return computeEntity1; + private static ComputeEntity createCompute(String vspId, Version version, String compId, + String computeId) { + ComputeEntity computeEntity1 = new ComputeEntity(vspId, version, compId, computeId); + ComputeData computeData = new ComputeData(); + computeData.setName(computeId + "name"); + computeData.setDescription(computeId + "desc"); + computeEntity1.setComputeCompositionData(computeData); + return computeEntity1; } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeplomentFlavorManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeplomentFlavorManagerImplTest.java deleted file mode 100644 index 598b97b34e..0000000000 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeplomentFlavorManagerImplTest.java +++ /dev/null @@ -1,463 +0,0 @@ -package org.openecomp.sdc.vendorsoftwareproduct.impl; - - -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.verify; - -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; -import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; -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.VspDetails; -import org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes; -import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager; -import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; -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.DeploymentFlavor; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.errors.VersioningErrorCodes; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -public class DeplomentFlavorManagerImplTest { - private static final String USER = "depFlavorTestUser"; - private static final String VSP_ID = "VSP_ID"; - private static final Version VERSION = new Version(0, 1); - private static final String COMPONENT_ID = "COMPONENT_ID"; - private static final String DF1_ID = "df1"; - private static final String DF2_ID = "df2"; - - @Mock - private CompositionEntityDataManager compositionEntityDataManagerMock; - @Mock - private VendorSoftwareProductInfoDao vspInfoDao; - @Mock - DeploymentFlavorDao deploymentFlavorDaoMock; - @Mock - ComponentDao componentDaoMock; - @Mock - ComputeDao computeDaoMock; - @InjectMocks - @Spy - private DeploymentFlavorManagerImpl deploymentFlavorManager; - - @BeforeMethod - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testListWhenNone() { - final Collection deploymentFlavorEntities = - deploymentFlavorManager.listDeploymentFlavors(VSP_ID, VERSION, USER); - Assert.assertEquals(deploymentFlavorEntities.size(), 0); - } - - @Test - public void testCreateOnNotManual_negative() { - - testCreate_negative(new DeploymentFlavorEntity(VSP_ID, VERSION, null), USER, - VendorSoftwareProductErrorCodes.CREATE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING); - } - - @Test - public void testCreateManualDepFlavor() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - - VspDetails vspDetails = new VspDetails(VSP_ID, VERSION); - doReturn(vspDetails).when(vspInfoDao).get(anyObject()); - - deploymentFlavorManager.createDeploymentFlavor(expected, USER); - verify(compositionEntityDataManagerMock).createDeploymentFlavor(expected); - } - - @Test - public void testCreateManualDepFlavorWithDuplicateName() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - - DeploymentFlavorEntity expectedDiffName = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); - DeploymentFlavor deploymentFlavor = expectedDiffName.getDeploymentFlavorCompositionData(); - deploymentFlavor.setModel(DF1_ID + "Name"); - expectedDiffName.setDeploymentFlavorCompositionData(deploymentFlavor); - List list = new ArrayList(); - list.add(expectedDiffName); - doReturn(list).when(deploymentFlavorDaoMock).list(anyObject()); - - try { - deploymentFlavorManager.createDeploymentFlavor(expected, USER); - Assert.fail(); - } - catch (CoreException ex) { - Assert.assertEquals(VendorSoftwareProductErrorCodes.DUPLICATE_DEPLOYMENT_FLAVOR_MODEL_NOT_ALLOWED, - ex.code().id()); - } - } - - @Test - public void testCreateManualDepFlavorWithIncorrectNameFormat() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - - DeploymentFlavorEntity expectedDiffName = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); - DeploymentFlavor deploymentFlavor = expectedDiffName.getDeploymentFlavorCompositionData(); - deploymentFlavor.setModel(DF1_ID + "Name/*"); - expectedDiffName.setDeploymentFlavorCompositionData(deploymentFlavor); - List list = new ArrayList(); - list.add(expectedDiffName); - doReturn(list).when(deploymentFlavorDaoMock).list(anyObject()); - - try { - deploymentFlavorManager.createDeploymentFlavor(expectedDiffName, USER); - Assert.fail(); - } - catch (CoreException ex) { - Assert.assertEquals(VendorSoftwareProductErrorCodes.DEPLOYMENT_FLAVOR_NAME_FORMAT_NOT_ALLOWED, - ex.code().id()); - } - } - @Test - public void testCreateManualDepFlavorWithFGNotInVSP() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); - final DeploymentFlavor deploymentFlavor = - JsonUtil.json2Object(expected.getCompositionData(), DeploymentFlavor.class); - deploymentFlavor.setFeatureGroupId("fg3"); - expected.setCompositionData(JsonUtil.object2Json(deploymentFlavor)); - - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - - List featureGrps = new ArrayList(); - featureGrps.add("fg1"); - featureGrps.add("fg2"); - - VspDetails vspDetails = new VspDetails(VSP_ID, VERSION); - vspDetails.setFeatureGroups(featureGrps); - doReturn(vspDetails).when(vspInfoDao).get(anyObject()); - - - try { - deploymentFlavorManager.createDeploymentFlavor(expected, USER); - Assert.fail(); - } - catch (CoreException ex) { - Assert.assertEquals(VendorSoftwareProductErrorCodes.FEATURE_GROUP_NOT_EXIST_FOR_VSP, - ex.code().id()); - } - } - - @Test - public void testCreateManualDepFlavorWithNullCompInAssociation() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); - final DeploymentFlavor deploymentFlavor = - JsonUtil.json2Object(expected.getCompositionData(), DeploymentFlavor.class); - ComponentComputeAssociation association = new ComponentComputeAssociation(); - association.setComponentId(null); - association.setComputeFlavorId("CF1"); - List list = new ArrayList(); - list.add(association); - deploymentFlavor.setComponentComputeAssociations(list); - expected.setCompositionData(JsonUtil.object2Json(deploymentFlavor)); - - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - - VspDetails vspDetails = new VspDetails(VSP_ID, VERSION); - doReturn(vspDetails).when(vspInfoDao).get(anyObject()); - - try { - deploymentFlavorManager.createDeploymentFlavor(expected, USER); - } - catch (CoreException ex) { - Assert.assertEquals(VendorSoftwareProductErrorCodes.INVALID_COMPONENT_COMPUTE_ASSOCIATION, - ex.code().id()); - Assert.assertEquals("Invalid request,for valid association please provide ComponentId for Compute Flavor", - ex.getMessage()); - } - } - - @Test - public void testCreateManualDepFlavorWithInvalidComputeInAssociation() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); - final DeploymentFlavor deploymentFlavor = - JsonUtil.json2Object(expected.getCompositionData(), DeploymentFlavor.class); - ComponentComputeAssociation association = new ComponentComputeAssociation(); - association.setComponentId(COMPONENT_ID); - association.setComputeFlavorId("CF1"); - List list = new ArrayList(); - list.add(association); - deploymentFlavor.setComponentComputeAssociations(list); - expected.setCompositionData(JsonUtil.object2Json(deploymentFlavor)); - - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - - VspDetails vspDetails = new VspDetails(VSP_ID, VERSION); - doReturn(vspDetails).when(vspInfoDao).get(anyObject()); - - ComponentEntity component = new ComponentEntity(VSP_ID, VERSION, USER); - doReturn(component).when(componentDaoMock).get(anyObject()); - - doReturn(null).when(computeDaoMock).get(anyObject()); - - try { - deploymentFlavorManager.createDeploymentFlavor(expected, USER); - } - catch (CoreException ex) { - Assert.assertEquals(VendorSoftwareProductErrorCodes.INVALID_COMPUTE_FLAVOR_ID, - ex.code().id()); - } - } - - @Test - public void testCreateManualDepFlavorWithDuplicateVfcAssociation() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); - final DeploymentFlavor deploymentFlavor = - JsonUtil.json2Object(expected.getCompositionData(), DeploymentFlavor.class); - ComponentComputeAssociation association = new ComponentComputeAssociation(); - association.setComponentId(COMPONENT_ID); - association.setComputeFlavorId("CF1"); - List list = new ArrayList(); - list.add(association); - list.add(association); - deploymentFlavor.setComponentComputeAssociations(list); - expected.setCompositionData(JsonUtil.object2Json(deploymentFlavor)); - - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - - VspDetails vspDetails = new VspDetails(VSP_ID, VERSION); - doReturn(vspDetails).when(vspInfoDao).get(anyObject()); - - ComponentEntity component = new ComponentEntity(VSP_ID, VERSION, USER); - doReturn(component).when(componentDaoMock).get(anyObject()); - - ComputeEntity computeEntity = new ComputeEntity(VSP_ID, VERSION, COMPONENT_ID, "CF1"); - doReturn(computeEntity).when(computeDaoMock).get(anyObject()); - - try { - deploymentFlavorManager.createDeploymentFlavor(expected, USER); - } - catch (CoreException ex) { - Assert.assertEquals(VendorSoftwareProductErrorCodes.SAME_VFC_ASSOCIATION_MORE_THAN_ONCE_NOT_ALLOWED, - ex.code().id()); - } - } - - @Test - public void testList() { - - doReturn(Arrays.asList( - createDeploymentFlavor(VSP_ID, VERSION, DF1_ID), - createDeploymentFlavor(VSP_ID, VERSION, DF2_ID))) - .when(deploymentFlavorDaoMock).list(anyObject()); - - - final Collection deploymentFlavorEntities = - deploymentFlavorManager.listDeploymentFlavors(VSP_ID, VERSION, USER); - Assert.assertEquals(deploymentFlavorEntities.size(), 2); - for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { - Assert.assertEquals(deploymentFlavorEntity.getDeploymentFlavorCompositionData().getModel() - , DF1_ID.equals(deploymentFlavorEntity.getId()) ? DF1_ID+"name" : DF2_ID+"name" ); - } - } - - @Test - public void testUpdateHeatDepFlavor() { - testUpdate_negative(VSP_ID, VERSION, DF1_ID, USER, - VendorSoftwareProductErrorCodes.EDIT_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING); - } - - @Test - public void testUpdateNonExistingManualDepFlavorId_negative() { - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - testUpdate_negative(VSP_ID, VERSION, DF1_ID, USER, - VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); - } - - @Test - public void testManualUpdateDepFlavor() { - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - - doReturn(createDeploymentFlavor(VSP_ID, VERSION, DF1_ID)) - .when(deploymentFlavorDaoMock).get(anyObject()); - - doReturn(new CompositionEntityValidationData(CompositionEntityType.image, DF1_ID)) - .when(compositionEntityDataManagerMock) - .validateEntity(anyObject(), anyObject(), anyObject()); - - VspDetails vspDetails = new VspDetails(VSP_ID, VERSION); - doReturn(vspDetails).when(vspInfoDao).get(anyObject()); - - DeploymentFlavorEntity deploymentFlavorEntity = new DeploymentFlavorEntity(VSP_ID, VERSION, DF1_ID); - DeploymentFlavor deploymentFlavor = new DeploymentFlavor(); - deploymentFlavor.setModel(DF1_ID + "_name"); - deploymentFlavor.setDescription(DF1_ID + " desc updated"); - deploymentFlavorEntity.setDeploymentFlavorCompositionData(deploymentFlavor); - - CompositionEntityValidationData validationData = - deploymentFlavorManager.updateDeploymentFlavor(deploymentFlavorEntity, USER); - Assert.assertTrue(validationData == null || validationData.getErrors() == null); - verify(deploymentFlavorDaoMock).update(deploymentFlavorEntity); - } - - @Test - public void testManualUpdateDepFlavorIncorrectNameFormat() { - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - - doReturn(createDeploymentFlavor(VSP_ID, VERSION, DF1_ID)) - .when(deploymentFlavorDaoMock).get(anyObject()); - - doReturn(new CompositionEntityValidationData(CompositionEntityType.image, DF1_ID)) - .when(compositionEntityDataManagerMock) - .validateEntity(anyObject(), anyObject(), anyObject()); - - VspDetails vspDetails = new VspDetails(VSP_ID, VERSION); - doReturn(vspDetails).when(vspInfoDao).get(anyObject()); - - DeploymentFlavorEntity deploymentFlavorEntity = new DeploymentFlavorEntity(VSP_ID, VERSION, DF1_ID); - DeploymentFlavor deploymentFlavor = new DeploymentFlavor(); - deploymentFlavor.setModel(DF1_ID + "_name/*"); - deploymentFlavor.setDescription(DF1_ID + " desc updated"); - deploymentFlavorEntity.setDeploymentFlavorCompositionData(deploymentFlavor); - - try { - deploymentFlavorManager.updateDeploymentFlavor(deploymentFlavorEntity, USER); - Assert.fail(); - } - catch (CoreException ex) { - Assert.assertEquals(VendorSoftwareProductErrorCodes.DEPLOYMENT_FLAVOR_NAME_FORMAT_NOT_ALLOWED, - ex.code().id()); - } - } - - @Test - public void testGetNonExistingDepFlavorId_negative() { - testGet_negative(VSP_ID, VERSION, "non existing image id", USER, - VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); - } - - @Test - public void testGet() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); - doReturn(expected).when(deploymentFlavorDaoMock).get(anyObject()); - - VspDetails vspDetails = new VspDetails(VSP_ID, VERSION); - doReturn(vspDetails).when(vspInfoDao).get(anyObject()); - - CompositionEntityResponse response = - deploymentFlavorManager.getDeploymentFlavor(VSP_ID, VERSION, DF1_ID, USER); - Assert.assertEquals(response.getId(), expected.getId()); - Assert.assertEquals(response.getData().getModel(), expected.getDeploymentFlavorCompositionData(). - getModel()); - Assert.assertEquals(response.getData().getDescription(), expected.getDeploymentFlavorCompositionData(). - getDescription()); - } - - @Test - public void testDeleteDepFlavorOnHEAT() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); - doReturn(expected).when(deploymentFlavorDaoMock).get(anyObject()); - testDelete_negative(VSP_ID, VERSION, DF1_ID, USER, - VendorSoftwareProductErrorCodes.DELETE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING); - } - - @Test - public void testDeleteOnNotExistImage() { - testDelete_negative(VSP_ID, VERSION, DF1_ID, USER, - VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); - } - - @Test - public void testDeleteOnManualImage() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); - doReturn(expected).when(deploymentFlavorDaoMock).get(anyObject()); - doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - deploymentFlavorManager.deleteDeploymentFlavor(VSP_ID, VERSION, DF1_ID, USER); - verify(deploymentFlavorDaoMock).delete(anyObject()); - } - - private void testList_negative(String vspId, Version version, String componentId, String user, - String expectedErrorCode, String expectedErrorMsg) { - try { - deploymentFlavorManager.listDeploymentFlavors(vspId, version, user); - Assert.fail(); - } catch (CoreException exception) { - Assert.assertEquals(exception.code().id(), expectedErrorCode); - Assert.assertEquals(exception.getMessage(), expectedErrorMsg); - } - } - - private void testCreate_negative(DeploymentFlavorEntity deploymentFlavorEntity, String user, String - expectedErrorCode) { - try { - deploymentFlavorManager.createDeploymentFlavor(deploymentFlavorEntity, user); - Assert.fail(); - } catch (CoreException exception) { - Assert.assertEquals(exception.code().id(), expectedErrorCode); - } - } - - private void testDelete_negative(String vspId, Version version, String deploymentFlavorId, - String user, - String expectedErrorCode) { - try { - deploymentFlavorManager.deleteDeploymentFlavor(vspId, version, deploymentFlavorId, user); - Assert.fail(); - } catch (CoreException exception) { - Assert.assertEquals(exception.code().id(), expectedErrorCode); - } - } - - static DeploymentFlavorEntity createDeploymentFlavor(String vspId, Version version, String deploymentFlavorId) { - - DeploymentFlavorEntity deploymentFlavorEntity = new DeploymentFlavorEntity(vspId, version, deploymentFlavorId); - DeploymentFlavor deploymentFlavor = new DeploymentFlavor(); - deploymentFlavor.setModel(deploymentFlavorId + "name"); - deploymentFlavor.setDescription(deploymentFlavorId + " desc"); - - deploymentFlavorEntity.setDeploymentFlavorCompositionData(deploymentFlavor); - return deploymentFlavorEntity; - } - - private void testUpdate_negative(String vspId, Version version, String - deploymentFlavorId, String user, String expectedErrorCode) { - try { - DeploymentFlavorEntity deploymentFlavorEntity = new DeploymentFlavorEntity(vspId, version, deploymentFlavorId); - DeploymentFlavor deploymentFlavor = new DeploymentFlavor(); - deploymentFlavor.setModel("Name"); - deploymentFlavorEntity.setDeploymentFlavorCompositionData(deploymentFlavor); - deploymentFlavorManager - .updateDeploymentFlavor(deploymentFlavorEntity, user); - Assert.fail(); - } catch (CoreException exception) { - Assert.assertEquals(exception.code().id(), expectedErrorCode); - } - } - - private void testGet_negative(String vspId, Version version, String deploymentFlavorId, - String user, String expectedErrorCode) { - try { - deploymentFlavorManager.getDeploymentFlavor(vspId, version, deploymentFlavorId, user); - Assert.fail(); - } catch (CoreException exception) { - Assert.assertEquals(exception.code().id(), expectedErrorCode); - } - } - -} diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeploymentFlavorManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeploymentFlavorManagerImplTest.java index 82715d3fe6..6a5e7fa70c 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeploymentFlavorManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeploymentFlavorManagerImplTest.java @@ -1,18 +1,12 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.verify; - import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.openecomp.core.utilities.json.JsonUtil; 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.vendorsoftwareproduct.dao.ComponentDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; @@ -23,7 +17,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager; -import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentComputeAssociation; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityType; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; @@ -39,13 +32,13 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; -public class DeploymentFlavorManagerImplTest { - - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; - private static final String USER = "depFlavorTestUser"; +public class DeploymentFlavorManagerImplTest { private static final String VSP_ID = "VSP_ID"; - private static final Version VERSION = new Version(0, 1); + private static final Version VERSION = new Version("version_id"); private static final String COMPONENT_ID = "COMPONENT_ID"; private static final String DF1_ID = "df1"; private static final String DF2_ID = "df2"; @@ -55,11 +48,11 @@ public class DeploymentFlavorManagerImplTest { @Mock private VendorSoftwareProductInfoDao vspInfoDao; @Mock - DeploymentFlavorDao deploymentFlavorDaoMock; + private DeploymentFlavorDao deploymentFlavorDaoMock; @Mock - ComponentDao componentDaoMock; + private ComponentDao componentDaoMock; @Mock - ComputeDao computeDaoMock; + private ComputeDao computeDaoMock; @InjectMocks @Spy private DeploymentFlavorManagerImpl deploymentFlavorManager; @@ -72,26 +65,26 @@ public class DeploymentFlavorManagerImplTest { @Test public void testListWhenNone() { final Collection deploymentFlavorEntities = - deploymentFlavorManager.listDeploymentFlavors(VSP_ID, VERSION, USER); + deploymentFlavorManager.listDeploymentFlavors(VSP_ID, VERSION); Assert.assertEquals(deploymentFlavorEntities.size(), 0); } @Test public void testCreateOnNotManual_negative() { - testCreate_negative(new DeploymentFlavorEntity(VSP_ID, VERSION, null), USER, + testCreate_negative(new DeploymentFlavorEntity(VSP_ID, VERSION, null), VendorSoftwareProductErrorCodes.CREATE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING); } @Test public void testCreateManualDepFlavor() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); + DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); VspDetails vspDetails = new VspDetails(VSP_ID, VERSION); doReturn(vspDetails).when(vspInfoDao).get(anyObject()); - deploymentFlavorManager.createDeploymentFlavor(expected, USER); + deploymentFlavorManager.createDeploymentFlavor(expected); verify(compositionEntityDataManagerMock).createDeploymentFlavor(expected); } @@ -104,17 +97,16 @@ public class DeploymentFlavorManagerImplTest { DeploymentFlavor deploymentFlavor = expectedDiffName.getDeploymentFlavorCompositionData(); deploymentFlavor.setModel(DF1_ID + "Name"); expectedDiffName.setDeploymentFlavorCompositionData(deploymentFlavor); - List list = new ArrayList(); + List list = new ArrayList<>(); list.add(expectedDiffName); doReturn(list).when(deploymentFlavorDaoMock).list(anyObject()); try { - deploymentFlavorManager.createDeploymentFlavor(expected, USER); + deploymentFlavorManager.createDeploymentFlavor(expected); Assert.fail(); - } - catch (CoreException ex) { - log.debug("",ex); - Assert.assertEquals(VendorSoftwareProductErrorCodes.DUPLICATE_DEPLOYMENT_FLAVOR_MODEL_NOT_ALLOWED, + } catch (CoreException ex) { + Assert.assertEquals( + VendorSoftwareProductErrorCodes.DUPLICATE_DEPLOYMENT_FLAVOR_MODEL_NOT_ALLOWED, ex.code().id()); } } @@ -129,7 +121,7 @@ public class DeploymentFlavorManagerImplTest { doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - List featureGrps = new ArrayList(); + List featureGrps = new ArrayList<>(); featureGrps.add("fg1"); featureGrps.add("fg2"); @@ -139,11 +131,9 @@ public class DeploymentFlavorManagerImplTest { try { - deploymentFlavorManager.createDeploymentFlavor(expected, USER); + deploymentFlavorManager.createDeploymentFlavor(expected); Assert.fail(); - } - catch (CoreException ex) { - log.debug("",ex); + } catch (CoreException ex) { Assert.assertEquals(VendorSoftwareProductErrorCodes.FEATURE_GROUP_NOT_EXIST_FOR_VSP, ex.code().id()); } @@ -151,13 +141,13 @@ public class DeploymentFlavorManagerImplTest { @Test public void testCreateManualDepFlavorWithNullCompInAssociation() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); + DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); final DeploymentFlavor deploymentFlavor = JsonUtil.json2Object(expected.getCompositionData(), DeploymentFlavor.class); ComponentComputeAssociation association = new ComponentComputeAssociation(); association.setComponentId(null); association.setComputeFlavorId("CF1"); - List list = new ArrayList(); + List list = new ArrayList<>(); list.add(association); deploymentFlavor.setComponentComputeAssociations(list); expected.setCompositionData(JsonUtil.object2Json(deploymentFlavor)); @@ -168,26 +158,25 @@ public class DeploymentFlavorManagerImplTest { doReturn(vspDetails).when(vspInfoDao).get(anyObject()); try { - deploymentFlavorManager.createDeploymentFlavor(expected, USER); - } - catch (CoreException ex) { - log.debug("",ex); + deploymentFlavorManager.createDeploymentFlavor(expected); + } catch (CoreException ex) { Assert.assertEquals(VendorSoftwareProductErrorCodes.INVALID_COMPONENT_COMPUTE_ASSOCIATION, ex.code().id()); - Assert.assertEquals("Invalid request,for valid association please provide ComponentId for Compute Flavor", + Assert.assertEquals( + "Invalid request,for valid association please provide ComponentId for Compute Flavor", ex.getMessage()); } } @Test public void testCreateManualDepFlavorWithInvalidComputeInAssociation() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); + DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); final DeploymentFlavor deploymentFlavor = JsonUtil.json2Object(expected.getCompositionData(), DeploymentFlavor.class); ComponentComputeAssociation association = new ComponentComputeAssociation(); association.setComponentId(COMPONENT_ID); association.setComputeFlavorId("CF1"); - List list = new ArrayList(); + List list = new ArrayList<>(); list.add(association); deploymentFlavor.setComponentComputeAssociations(list); expected.setCompositionData(JsonUtil.object2Json(deploymentFlavor)); @@ -197,16 +186,14 @@ public class DeploymentFlavorManagerImplTest { VspDetails vspDetails = new VspDetails(VSP_ID, VERSION); doReturn(vspDetails).when(vspInfoDao).get(anyObject()); - ComponentEntity component = new ComponentEntity(VSP_ID, VERSION, USER); + ComponentEntity component = new ComponentEntity(VSP_ID, VERSION, null); doReturn(component).when(componentDaoMock).get(anyObject()); doReturn(null).when(computeDaoMock).get(anyObject()); try { - deploymentFlavorManager.createDeploymentFlavor(expected, USER); - } - catch (CoreException ex) { - log.debug("",ex); + deploymentFlavorManager.createDeploymentFlavor(expected); + } catch (CoreException ex) { Assert.assertEquals(VendorSoftwareProductErrorCodes.INVALID_COMPUTE_FLAVOR_ID, ex.code().id()); } @@ -214,13 +201,13 @@ public class DeploymentFlavorManagerImplTest { @Test public void testCreateManualDepFlavorWithDuplicateVfcAssociation() { - DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); + DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); final DeploymentFlavor deploymentFlavor = JsonUtil.json2Object(expected.getCompositionData(), DeploymentFlavor.class); ComponentComputeAssociation association = new ComponentComputeAssociation(); association.setComponentId(COMPONENT_ID); association.setComputeFlavorId("CF1"); - List list = new ArrayList(); + List list = new ArrayList<>(); list.add(association); list.add(association); deploymentFlavor.setComponentComputeAssociations(list); @@ -231,18 +218,17 @@ public class DeploymentFlavorManagerImplTest { VspDetails vspDetails = new VspDetails(VSP_ID, VERSION); doReturn(vspDetails).when(vspInfoDao).get(anyObject()); - ComponentEntity component = new ComponentEntity(VSP_ID, VERSION, USER); + ComponentEntity component = new ComponentEntity(VSP_ID, VERSION, null); doReturn(component).when(componentDaoMock).get(anyObject()); ComputeEntity computeEntity = new ComputeEntity(VSP_ID, VERSION, COMPONENT_ID, "CF1"); doReturn(computeEntity).when(computeDaoMock).get(anyObject()); try { - deploymentFlavorManager.createDeploymentFlavor(expected, USER); - } - catch (CoreException ex) { - log.debug("",ex); - Assert.assertEquals(VendorSoftwareProductErrorCodes.SAME_VFC_ASSOCIATION_MORE_THAN_ONCE_NOT_ALLOWED, + deploymentFlavorManager.createDeploymentFlavor(expected); + } catch (CoreException ex) { + Assert.assertEquals( + VendorSoftwareProductErrorCodes.SAME_VFC_ASSOCIATION_MORE_THAN_ONCE_NOT_ALLOWED, ex.code().id()); } } @@ -251,30 +237,30 @@ public class DeploymentFlavorManagerImplTest { public void testList() { doReturn(Arrays.asList( - createDeploymentFlavor(VSP_ID, VERSION, DF1_ID), - createDeploymentFlavor(VSP_ID, VERSION, DF2_ID))) + createDeploymentFlavor(VSP_ID, VERSION, DF1_ID), + createDeploymentFlavor(VSP_ID, VERSION, DF2_ID))) .when(deploymentFlavorDaoMock).list(anyObject()); final Collection deploymentFlavorEntities = - deploymentFlavorManager.listDeploymentFlavors(VSP_ID, VERSION, USER); + deploymentFlavorManager.listDeploymentFlavors(VSP_ID, VERSION); Assert.assertEquals(deploymentFlavorEntities.size(), 2); for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { Assert.assertEquals(deploymentFlavorEntity.getDeploymentFlavorCompositionData().getModel() - , DF1_ID.equals(deploymentFlavorEntity.getId()) ? DF1_ID+"name" : DF2_ID+"name" ); + , DF1_ID.equals(deploymentFlavorEntity.getId()) ? DF1_ID + "name" : DF2_ID + "name"); } } @Test public void testUpdateHeatDepFlavor() { - testUpdate_negative(VSP_ID, VERSION, DF1_ID, USER, + testUpdate_negative(VSP_ID, VERSION, DF1_ID, VendorSoftwareProductErrorCodes.EDIT_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING); } @Test public void testUpdateNonExistingManualDepFlavorId_negative() { doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - testUpdate_negative(VSP_ID, VERSION, DF1_ID, USER, + testUpdate_negative(VSP_ID, VERSION, DF1_ID, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @@ -292,21 +278,22 @@ public class DeploymentFlavorManagerImplTest { VspDetails vspDetails = new VspDetails(VSP_ID, VERSION); doReturn(vspDetails).when(vspInfoDao).get(anyObject()); - DeploymentFlavorEntity deploymentFlavorEntity = new DeploymentFlavorEntity(VSP_ID, VERSION, DF1_ID); + DeploymentFlavorEntity deploymentFlavorEntity = + new DeploymentFlavorEntity(VSP_ID, VERSION, DF1_ID); DeploymentFlavor deploymentFlavor = new DeploymentFlavor(); deploymentFlavor.setModel(DF1_ID + "_name"); deploymentFlavor.setDescription(DF1_ID + " desc updated"); deploymentFlavorEntity.setDeploymentFlavorCompositionData(deploymentFlavor); CompositionEntityValidationData validationData = - deploymentFlavorManager.updateDeploymentFlavor(deploymentFlavorEntity, USER); + deploymentFlavorManager.updateDeploymentFlavor(deploymentFlavorEntity); Assert.assertTrue(validationData == null || validationData.getErrors() == null); verify(deploymentFlavorDaoMock).update(deploymentFlavorEntity); } @Test public void testGetNonExistingDepFlavorId_negative() { - testGet_negative(VSP_ID, VERSION, "non existing image id", USER, + testGet_negative(VSP_ID, VERSION, "non existing image id", VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @@ -320,25 +307,27 @@ public class DeploymentFlavorManagerImplTest { doReturn(vspDetails).when(vspInfoDao).get(anyObject()); CompositionEntityResponse response = - deploymentFlavorManager.getDeploymentFlavor(VSP_ID, VERSION, DF1_ID, USER); + deploymentFlavorManager.getDeploymentFlavor(VSP_ID, VERSION, DF1_ID); Assert.assertEquals(response.getId(), expected.getId()); - Assert.assertEquals(response.getData().getModel(), expected.getDeploymentFlavorCompositionData(). - getModel()); - Assert.assertEquals(response.getData().getDescription(), expected.getDeploymentFlavorCompositionData(). - getDescription()); + Assert + .assertEquals(response.getData().getModel(), expected.getDeploymentFlavorCompositionData(). + getModel()); + Assert.assertEquals(response.getData().getDescription(), + expected.getDeploymentFlavorCompositionData(). + getDescription()); } */ @Test public void testDeleteDepFlavorOnHEAT() { DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); doReturn(expected).when(deploymentFlavorDaoMock).get(anyObject()); - testDelete_negative(VSP_ID, VERSION, DF1_ID, USER, + testDelete_negative(VSP_ID, VERSION, DF1_ID, VendorSoftwareProductErrorCodes.DELETE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING); } @Test public void testDeleteOnNotExistImage() { - testDelete_negative(VSP_ID, VERSION, DF1_ID, USER, + testDelete_negative(VSP_ID, VERSION, DF1_ID, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @@ -347,48 +336,35 @@ public class DeploymentFlavorManagerImplTest { DeploymentFlavorEntity expected = createDeploymentFlavor(VSP_ID, VERSION, DF1_ID); doReturn(expected).when(deploymentFlavorDaoMock).get(anyObject()); doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - deploymentFlavorManager.deleteDeploymentFlavor(VSP_ID, VERSION, DF1_ID, USER); + deploymentFlavorManager.deleteDeploymentFlavor(VSP_ID, VERSION, DF1_ID); verify(deploymentFlavorDaoMock).delete(anyObject()); } - private void testList_negative(String vspId, Version version, String componentId, String user, - String expectedErrorCode, String expectedErrorMsg) { - try { - deploymentFlavorManager.listDeploymentFlavors(vspId, version, user); - Assert.fail(); - } catch (CoreException exception) { - log.debug("",exception); - Assert.assertEquals(exception.code().id(), expectedErrorCode); - Assert.assertEquals(exception.getMessage(), expectedErrorMsg); - } - } - - private void testCreate_negative(DeploymentFlavorEntity deploymentFlavorEntity, String user, String - expectedErrorCode) { + private void testCreate_negative(DeploymentFlavorEntity deploymentFlavorEntity, + String expectedErrorCode) { try { - deploymentFlavorManager.createDeploymentFlavor(deploymentFlavorEntity, user); + deploymentFlavorManager.createDeploymentFlavor(deploymentFlavorEntity); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } private void testDelete_negative(String vspId, Version version, String deploymentFlavorId, - String user, String expectedErrorCode) { try { - deploymentFlavorManager.deleteDeploymentFlavor(vspId, version, deploymentFlavorId, user); + deploymentFlavorManager.deleteDeploymentFlavor(vspId, version, deploymentFlavorId); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } - static DeploymentFlavorEntity createDeploymentFlavor(String vspId, Version version, String deploymentFlavorId) { + private static DeploymentFlavorEntity createDeploymentFlavor(String vspId, Version version, + String deploymentFlavorId) { - DeploymentFlavorEntity deploymentFlavorEntity = new DeploymentFlavorEntity(vspId, version, deploymentFlavorId); + DeploymentFlavorEntity deploymentFlavorEntity = + new DeploymentFlavorEntity(vspId, version, deploymentFlavorId); DeploymentFlavor deploymentFlavor = new DeploymentFlavor(); deploymentFlavor.setModel(deploymentFlavorId + "name"); deploymentFlavor.setDescription(deploymentFlavorId + " desc"); @@ -397,29 +373,28 @@ public class DeploymentFlavorManagerImplTest { return deploymentFlavorEntity; } - private void testUpdate_negative(String vspId, Version version, String - deploymentFlavorId, String user, String expectedErrorCode) { + private void testUpdate_negative(String vspId, Version version, String deploymentFlavorId, + String expectedErrorCode) { try { - DeploymentFlavorEntity deploymentFlavorEntity = new DeploymentFlavorEntity(vspId, version, deploymentFlavorId); + DeploymentFlavorEntity deploymentFlavorEntity = + new DeploymentFlavorEntity(vspId, version, deploymentFlavorId); DeploymentFlavor deploymentFlavor = new DeploymentFlavor(); deploymentFlavor.setModel("Name"); deploymentFlavorEntity.setDeploymentFlavorCompositionData(deploymentFlavor); deploymentFlavorManager - .updateDeploymentFlavor(deploymentFlavorEntity, user); + .updateDeploymentFlavor(new DeploymentFlavorEntity(vspId, version, deploymentFlavorId)); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } private void testGet_negative(String vspId, Version version, String deploymentFlavorId, - String user, String expectedErrorCode) { + String expectedErrorCode) { try { - deploymentFlavorManager.getDeploymentFlavor(vspId, version, deploymentFlavorId, user); + deploymentFlavorManager.getDeploymentFlavor(vspId, version, deploymentFlavorId); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ImageManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ImageManagerImplTest.java index 9f932b9fdf..d9b4188f5e 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ImageManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ImageManagerImplTest.java @@ -1,18 +1,11 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; 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.vendorsoftwareproduct.dao.ImageDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; @@ -29,21 +22,20 @@ import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.List; -public class ImageManagerImplTest { +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); +public class ImageManagerImplTest { private static final String IMAGE_NOT_EXIST_MSG = - "Vendor Software Product Image with Id image1 does not exist for Vendor Software Product with" + - " " + - "id VSP_ID and version 0.1"; + "Vendor Software Product Image with Id image1 does not exist for Vendor Software Product with" + + " id VSP_ID and version 0.1"; - private static final String USER = "imageTestUser"; private static final String VSP_ID = "VSP_ID"; private static final Version VERSION = new Version(0, 1); private static final String COMPONENT_ID = "COMPONENT_ID"; @@ -68,7 +60,7 @@ public class ImageManagerImplTest { @Test public void testListWhenNone() { final Collection imageEntities = - imageManager.listImages(VSP_ID, VERSION, COMPONENT_ID, USER); + imageManager.listImages(VSP_ID, VERSION, COMPONENT_ID); Assert.assertEquals(imageEntities.size(), 0); } @@ -76,32 +68,32 @@ public class ImageManagerImplTest { public void testList() { doReturn(Arrays.asList( - createImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID), - createImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE2_ID))) - .when(imageDao).list(anyObject()); + createImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID), + createImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE2_ID))) + .when(imageDao).list(anyObject()); final Collection images = - imageManager.listImages(VSP_ID, VERSION, COMPONENT_ID, USER); + imageManager.listImages(VSP_ID, VERSION, COMPONENT_ID); Assert.assertEquals(images.size(), 2); for (ImageEntity image : images) { Assert.assertEquals(image.getImageCompositionData().getFileName(), - IMAGE1_ID.equals(image.getId()) ? IMAGE1_ID+"_name" : IMAGE2_ID+"_name" ); + IMAGE1_ID.equals(image.getId()) ? IMAGE1_ID + "_name" : IMAGE2_ID + "_name"); } } @Test public void testCreateOnNotManualImage_negative() { - testCreate_negative(new ImageEntity(VSP_ID, VERSION, COMPONENT_ID, null), USER, - VendorSoftwareProductErrorCodes.ADD_IMAGE_NOT_ALLOWED_IN_HEAT_ONBOARDING); + testCreate_negative(new ImageEntity(VSP_ID, VERSION, COMPONENT_ID, null), + VendorSoftwareProductErrorCodes.ADD_IMAGE_NOT_ALLOWED_IN_HEAT_ONBOARDING); } @Test public void testCreateManualImage() { ImageEntity expected = createImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID); doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - imageManager.createImage(expected, USER); + imageManager.createImage(expected); verify(compositionEntityDataManagerMock).createImage(expected); verify(compositionEntityDataManagerMock).createImage(expected); } @@ -115,14 +107,13 @@ public class ImageManagerImplTest { Image image = expectedDiffName.getImageCompositionData(); image.setFileName(IMAGE1_ID + "_Name"); expectedDiffName.setImageCompositionData(image); - List vfcImageList = new ArrayList(); + List vfcImageList = new ArrayList<>(); vfcImageList.add(expectedDiffName); doReturn(vfcImageList).when(imageDao).list(anyObject()); try { - imageManager.createImage(expected, USER); + imageManager.createImage(expected); Assert.fail(); - } - catch (CoreException ex) { + } catch (CoreException ex) { Assert.assertEquals(VendorSoftwareProductErrorCodes.DUPLICATE_IMAGE_NAME_NOT_ALLOWED, ex.code().id()); } @@ -130,18 +121,18 @@ public class ImageManagerImplTest { @Test public void testUpdateNonExistingImageId_negative() { - testUpdate_negative(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, USER, - VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); + testUpdate_negative(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, + VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @Test public void testUpdateImage() { doReturn(createImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID)) - .when(imageDao).get(anyObject()); + .when(imageDao).get(anyObject()); doReturn(new CompositionEntityValidationData(CompositionEntityType.image, IMAGE1_ID)) - .when(compositionEntityDataManagerMock) - .validateEntity(anyObject(), anyObject(), anyObject()); + .when(compositionEntityDataManagerMock) + .validateEntity(anyObject(), anyObject(), anyObject()); ImageEntity imageEntity = new ImageEntity(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID); Image imageData = new Image(); @@ -150,7 +141,7 @@ public class ImageManagerImplTest { imageEntity.setImageCompositionData(imageData); CompositionEntityValidationData validationData = - imageManager.updateImage(imageEntity, USER); + imageManager.updateImage(imageEntity); Assert.assertTrue(validationData == null || validationData.getErrors() == null); verify(imageDao).update(imageEntity); } @@ -158,16 +149,16 @@ public class ImageManagerImplTest { @Test public void testIllegalImageUpdate() { doReturn(createImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID)) - .when(imageDao).get(anyObject()); + .when(imageDao).get(anyObject()); doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); CompositionEntityValidationData toBeReturned = - new CompositionEntityValidationData(CompositionEntityType.image, IMAGE1_ID); + new CompositionEntityValidationData(CompositionEntityType.image, IMAGE1_ID); toBeReturned.setErrors(Arrays.asList("error1", "error2")); doReturn(toBeReturned) - .when(compositionEntityDataManagerMock) - .validateEntity(anyObject(), anyObject(), anyObject()); + .when(compositionEntityDataManagerMock) + .validateEntity(anyObject(), anyObject(), anyObject()); ImageEntity imageEntity = new ImageEntity(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID); Image imageData = new Image(); @@ -175,7 +166,7 @@ public class ImageManagerImplTest { imageData.setDescription(IMAGE1_ID + " desc updated"); imageEntity.setImageCompositionData(imageData); - CompositionEntityValidationData validationData = imageManager.updateImage(imageEntity, USER); + CompositionEntityValidationData validationData = imageManager.updateImage(imageEntity); Assert.assertNotNull(validationData); Assert.assertEquals(validationData.getErrors().size(), 2); @@ -185,7 +176,7 @@ public class ImageManagerImplTest { @Test public void testUpdateHEATImageFileName() throws Exception { doReturn(createImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID)) - .when(imageDao).get(anyObject()); + .when(imageDao).get(anyObject()); ImageEntity imageEntity = new ImageEntity(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID); Image imageData = new Image(); imageData.setFileName(IMAGE1_ID + " name updated"); @@ -193,10 +184,8 @@ public class ImageManagerImplTest { imageEntity.setImageCompositionData(imageData); try { - imageManager.updateImage(imageEntity, USER); - } - catch (CoreException ex) { - log.debug("",ex); + imageManager.updateImage(imageEntity); + } catch (CoreException ex) { Assert.assertEquals(ex.code().id(), VendorSoftwareProductErrorCodes.UPDATE_IMAGE_NOT_ALLOWED); } @@ -204,8 +193,8 @@ public class ImageManagerImplTest { @Test public void testGetNonExistingImageId_negative() { - testGet_negative(VSP_ID, VERSION, COMPONENT_ID, "non existing image id", USER, - VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); + testGet_negative(VSP_ID, VERSION, COMPONENT_ID, "non existing image id", + VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @Test @@ -216,12 +205,12 @@ public class ImageManagerImplTest { doReturn(compositionSchema).when(imageManager).getImageCompositionSchema(anyObject()); CompositionEntityResponse response = - imageManager.getImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, USER); + imageManager.getImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID); Assert.assertEquals(response.getId(), expected.getId()); Assert.assertEquals(response.getData().getFileName(), expected.getImageCompositionData(). - getFileName()); + getFileName()); Assert.assertEquals(response.getData().getDescription(), expected.getImageCompositionData(). - getDescription()); + getDescription()); Assert.assertEquals(response.getSchema(), compositionSchema); } @@ -229,14 +218,14 @@ public class ImageManagerImplTest { public void testDeleteOnNotManualImage() { ImageEntity expected = createImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID); doReturn(expected).when(imageDao).get(anyObject()); - testDelete_negative(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, USER, - VendorSoftwareProductErrorCodes.DELETE_IMAGE_NOT_ALLOWED); + testDelete_negative(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, + VendorSoftwareProductErrorCodes.DELETE_IMAGE_NOT_ALLOWED); } @Test public void testDeleteOnNotExistImage() { - testDelete_negative(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, USER, - VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); + testDelete_negative(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, + VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @Test @@ -244,7 +233,7 @@ public class ImageManagerImplTest { ImageEntity expected = createImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID); doReturn(expected).when(imageDao).get(anyObject()); doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); - imageManager.deleteImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, USER); + imageManager.deleteImage(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID); verify(imageDao).delete(anyObject()); } @@ -258,7 +247,7 @@ public class ImageManagerImplTest { doReturn(schema).when(imageManager).getImageQuestionnaireSchema(anyObject()); QuestionnaireResponse questionnaire = - imageManager.getImageQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, USER); + imageManager.getImageQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID); Assert.assertNotNull(questionnaire); Assert.assertEquals(questionnaire.getData(), image.getQuestionnaireData()); Assert.assertEquals(questionnaire.getSchema(), schema); @@ -270,7 +259,8 @@ public class ImageManagerImplTest { String json = "{\"md5\" :\"FFDSD33SS\"}"; doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); doReturn(new ImageEntity()).when(imageDao).get(anyObject()); - imageManager.updateImageQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, json, USER); + + imageManager.updateImageQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, json); verify(imageDao).updateQuestionnaireData(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, json); } @@ -291,10 +281,9 @@ public class ImageManagerImplTest { doReturn(imageEntities).when(imageDao).list(anyObject()); doReturn(imageEntities.get(0)).when(imageDao).getQuestionnaireData(anyObject(), anyObject(), anyObject(), anyObject()); - imageManager.updateImageQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, json, USER); + imageManager.updateImageQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, json); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), VendorSoftwareProductErrorCodes.DUPLICATE_IMAGE_VERSION_NOT_ALLOWED); } @@ -316,12 +305,9 @@ public class ImageManagerImplTest { String updJson = "{\"format\" :\"aki\"}"; try { - imageManager.updateImageQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, updJson, - USER); + imageManager.updateImageQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, updJson); Assert.fail(); - } - catch(CoreException ex) { - log.debug("",ex); + } catch (CoreException ex) { Assert.assertEquals(ex.code().id(), VendorSoftwareProductErrorCodes.UPDATE_IMAGE_NOT_ALLOWED); } } @@ -337,51 +323,34 @@ public class ImageManagerImplTest { String updJson = "{\"format\" :\"a22\"}"; try { - imageManager.updateImageQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, updJson, - USER); + imageManager.updateImageQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, IMAGE1_ID, updJson); Assert.fail(); - } - catch(CoreException ex) { - log.debug("",ex); + } catch (CoreException ex) { Assert.assertEquals(ex.code().id(), VendorSoftwareProductErrorCodes.VFC_IMAGE_INVALID_FORMAT); } } - private void testList_negative(String vspId, Version version, String componentId, String user, - String expectedErrorCode, String expectedErrorMsg) { - try { - imageManager.listImages(vspId, version, componentId, user); - Assert.fail(); - } catch (CoreException exception) { - log.debug("",exception); - Assert.assertEquals(exception.code().id(), expectedErrorCode); - Assert.assertEquals(exception.getMessage(), expectedErrorMsg); - } - } - - private void testCreate_negative(ImageEntity image, String user, String expectedErrorCode) { + private void testCreate_negative(ImageEntity image, String expectedErrorCode) { try { - imageManager.createImage(image, user); + imageManager.createImage(image); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } private void testDelete_negative(String vspId, Version version, String componentId, String nicId, - String user, String expectedErrorCode) { try { - imageManager.deleteImage(vspId, version, componentId, nicId, user); + imageManager.deleteImage(vspId, version, componentId, nicId); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } - static ImageEntity createImage(String vspId, Version version, String compId, String imageId) { + private static ImageEntity createImage(String vspId, Version version, String compId, + String imageId) { ImageEntity imageEntity = new ImageEntity(vspId, version, compId, imageId); Image imageData = new Image(); imageData.setFileName(imageId + "_name"); @@ -390,21 +359,20 @@ public class ImageManagerImplTest { return imageEntity; } - private void testUpdate_negative(String vspId, Version version, String componentId, String - imageId, String user, String expectedErrorCode) { + private void testUpdate_negative(String vspId, Version version, String componentId, + String imageId, String expectedErrorCode) { try { - imageManager.updateImage(new ImageEntity(vspId, version, componentId, imageId), user); + imageManager.updateImage(new ImageEntity(vspId, version, componentId, imageId)); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } private void testGet_negative(String vspId, Version version, String componentId, String imageId, - String user, String expectedErrorCode) { + String expectedErrorCode) { try { - imageManager.getImage(vspId, version, componentId, imageId, user); + imageManager.getImage(vspId, version, componentId, imageId); Assert.fail(); } catch (CoreException exception) { Assert.assertEquals(exception.code().id(), expectedErrorCode); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ManualVspToscaManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ManualVspToscaManagerImplTest.java index ecfe0e6372..2360dc7398 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ManualVspToscaManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ManualVspToscaManagerImplTest.java @@ -1,57 +1,10 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.openecomp.sdc.generator.util.GeneratorConstants.ALLOWED_FLAVORS_PROPERTY; -import static org.openecomp.sdc.generator.util.GeneratorConstants.IMAGES_PROPERTY; -import static org.openecomp.sdc.generator.util.GeneratorConstants.PORT_NODE_TEMPLATE_ID_SUFFIX; -import static org.openecomp.sdc.tosca.services.ToscaConstants.BINDING_REQUIREMENT_ID; -import static org.openecomp.sdc.tosca.services.ToscaConstants.COUNT_PROPERTY_NAME; -import static org.openecomp.sdc.tosca.services.ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME; -import static org.openecomp.sdc.tosca.services.ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME; -import static org.openecomp.sdc.translator.services.heattotosca.Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME; - -import org.junit.Assert; -import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; import org.mockito.Spy; -import org.openecomp.sdc.generator.core.utils.GeneratorUtils; -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.generator.datatypes.tosca.VspModelInfo; -import org.openecomp.sdc.generator.util.GeneratorConstants; -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -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.datatypes.model.CapabilityDefinition; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; -import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.datatypes.model.SubstitutionMapping; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.tosca.services.ToscaUtil; -import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; import org.openecomp.sdc.vendorsoftwareproduct.ManualVspToscaManager; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Nic; import org.openecomp.sdc.vendorsoftwareproduct.services.ManualVspDataCollectionService; -import org.openecomp.sdc.versioning.dao.types.Version; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; public class ManualVspToscaManagerImplTest { @@ -96,36 +49,27 @@ public class ManualVspToscaManagerImplTest { private ManualVspDataCollectionService manualVspDataCollectionServiceMock; /* - private static List supportedCapabilities = new ArrayList<>(); - private static List supportedRequirements = new ArrayList<>(); - - static { - //TODO : Read from configuration - supportedCapabilities.addAll(Arrays.asList("host", "os", "endpoint", "scalable")); - supportedRequirements.addAll(Arrays.asList("link")); - } - @Test public void testGatherVspInformationInvalidVsp() { MockitoAnnotations.initMocks(this); VspModelInfo expectedVspData = new VspModelInfo(); doThrow(new RuntimeException()) .when(manualVspDataCollectionServiceMock) - .getReleaseVendor(INVALID_VSP_ID, Version.valueOf(VSP_VERSION), USER); + .getReleaseVendor(INVALID_VSP_ID, Version.valueOf(VSP_VERSION)); doThrow(new RuntimeException()) .when(manualVspDataCollectionServiceMock) - .getAllowedFlavors(INVALID_VSP_ID, Version.valueOf(VSP_VERSION), USER); + .getAllowedFlavors(INVALID_VSP_ID, Version.valueOf(VSP_VERSION)); doThrow(new RuntimeException()) .when(manualVspDataCollectionServiceMock) - .getVspComponentImages(INVALID_VSP_ID, Version.valueOf(VSP_VERSION), USER); + .getVspComponentImages(INVALID_VSP_ID, Version.valueOf(VSP_VERSION)); doThrow(new RuntimeException()) .when(manualVspDataCollectionServiceMock) - .getVspComponents(INVALID_VSP_ID, Version.valueOf(VSP_VERSION), USER); + .getVspComponents(INVALID_VSP_ID, Version.valueOf(VSP_VERSION)); doThrow(new RuntimeException()) .when(manualVspDataCollectionServiceMock) - .getVspComponentNics(INVALID_VSP_ID, Version.valueOf(VSP_VERSION), USER); + .getVspComponentNics(INVALID_VSP_ID, Version.valueOf(VSP_VERSION)); VspModelInfo vspModelInfo = manualVspToscaManagerMock.gatherVspInformation(INVALID_VSP_ID, - Version.valueOf(VSP_VERSION), USER); + Version.valueOf(VSP_VERSION)); Assert.assertEquals(expectedVspData, vspModelInfo); } @@ -138,17 +82,17 @@ public class ManualVspToscaManagerImplTest { Map componentData = getComponentData(); Map> vfcImageData = getVfcImageData(); doReturn(Optional.of(RELEASE_VENDOR)).when(manualVspDataCollectionServiceMock) - .getReleaseVendor(VSP_ID, Version.valueOf(VSP_VERSION), USER); + .getReleaseVendor(VSP_ID, Version.valueOf(VSP_VERSION)); doReturn(deploymentFlavorData).when(manualVspDataCollectionServiceMock) - .getAllowedFlavors(VSP_ID, Version.valueOf(VSP_VERSION), USER); + .getAllowedFlavors(VSP_ID, Version.valueOf(VSP_VERSION)); doReturn(vfcImageData).when(manualVspDataCollectionServiceMock) - .getVspComponentImages(VSP_ID, Version.valueOf(VSP_VERSION), USER); + .getVspComponentImages(VSP_ID, Version.valueOf(VSP_VERSION)); doReturn(componentData).when(manualVspDataCollectionServiceMock) - .getVspComponents(VSP_ID, Version.valueOf(VSP_VERSION), USER); + .getVspComponents(VSP_ID, Version.valueOf(VSP_VERSION)); doReturn(componentNics).when(manualVspDataCollectionServiceMock) - .getVspComponentNics(VSP_ID, Version.valueOf(VSP_VERSION), USER); + .getVspComponentNics(VSP_ID, Version.valueOf(VSP_VERSION)); VspModelInfo vspModelInfo = manualVspToscaManagerMock.gatherVspInformation(VSP_ID, - Version.valueOf(VSP_VERSION), USER); + Version.valueOf(VSP_VERSION)); VspModelInfo expectedVspData = new VspModelInfo(); expectedVspData.setReleaseVendor(RELEASE_VENDOR); @@ -449,9 +393,9 @@ public class ManualVspToscaManagerImplTest { private void validateSubstitutionCapabilities(Map> capabilities, String componentName) { - List SupportedCapabilities = supportedCapabilities; - Assert.assertEquals(SupportedCapabilities.size(), capabilities.size()); - for (String capability : SupportedCapabilities) { + List supportedCapabilities = GeneratorUtils.supportedCapabilities; + Assert.assertEquals(supportedCapabilities.size(), capabilities.size()); + for (String capability : supportedCapabilities) { String expectedCapabilityId = capability + "_" + componentName; Assert.assertEquals(true, capabilities.containsKey(expectedCapabilityId)); List expectedCapabilityValue = new ArrayList<>(2); @@ -464,10 +408,10 @@ public class ManualVspToscaManagerImplTest { private void validateSubstitutionRequirements(Map> requirements, List nics) { - List SupportedRequirements = supportedRequirements; + List supportedRequirements = GeneratorUtils.supportedRequirements; for(Nic nic : nics) { String nicNodeTemplateId = nic.getName() + PORT_NODE_TEMPLATE_ID_SUFFIX; - for (String requirement : SupportedRequirements) { + for (String requirement : supportedRequirements) { String expectedRequirementId = requirement + "_" + nicNodeTemplateId; Assert.assertEquals(true, requirements.containsKey(expectedRequirementId)); List expectedRequirementValue = new ArrayList<>(2); @@ -508,11 +452,11 @@ public class ManualVspToscaManagerImplTest { List> requirements = deploymentFlavorNodeType.getRequirements(); - List SupportedRequirements = supportedRequirements; + List supportedRequirements = GeneratorUtils.supportedRequirements; for (Nic nic : nics) { boolean found = false; String nicNodeTemplateId = nic.getName() + PORT_NODE_TEMPLATE_ID_SUFFIX; - for (String requirementId : SupportedRequirements) { + for (String requirementId : supportedRequirements) { String expectedRequirementId = requirementId + "_" + nicNodeTemplateId; for (Map requirement : requirements) { if (requirement.containsKey(expectedRequirementId)) { @@ -525,8 +469,8 @@ public class ManualVspToscaManagerImplTest { } Map capabilities = deploymentFlavorNodeType.getCapabilities(); - List SupportedCapabilities = supportedCapabilities; - for (String capabilityId : SupportedCapabilities) { + List supportedCapabilities = GeneratorUtils.supportedCapabilities; + for (String capabilityId : supportedCapabilities) { String expectedCapabilityId = capabilityId + "_" + componentName; Assert.assertEquals (true, capabilities.containsKey(expectedCapabilityId)); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerImplTest.java index 966e1f20bf..5e735ff74e 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerImplTest.java @@ -28,10 +28,9 @@ import static org.mockito.Mockito.verify; public class MonitoringUploadsManagerImplTest { - private static final String USER1 = "ComponentsUploadTestUser"; private static final String COMPONENT_ID = "COMPONENT_ID"; private static final String VSP_ID = "vspId"; - private static final Version VERSION = new Version(0, 1); + private static final Version VERSION = new Version("version_id"); private static final String TRAP_FILE_NAME = "MMSC.zip"; private static final String POLL_FILE_NAME = "MNS OAM FW.zip"; private static final String VES_FILE_NAME = "vesTest-yml_only.zip"; @@ -54,22 +53,19 @@ public class MonitoringUploadsManagerImplTest { @Test(expectedExceptions = CoreException.class) public void testUploadEmptyZip() { processFile(ZIP_DIR + EMPTY_ZIP_FILE_NAME, inputStream -> - monitoringUploadsManager.upload(inputStream, EMPTY_ZIP_FILE_NAME, VSP_ID, VERSION, COMPONENT_ID, - MonitoringUploadType.SNMP_TRAP, USER1)); + monitoringUploadsManager + .upload(inputStream, EMPTY_ZIP_FILE_NAME, VSP_ID, VERSION, COMPONENT_ID, + MonitoringUploadType.SNMP_TRAP)); } - @Test + @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = + "Monitoring file uploaded for vendor software product with Id vspId and version version_id " + + "is invalid: Invalid zip file") public void testUploadInvalidZip() { - - try { - processFile("/notZipFile", inputStream -> + processFile("/notZipFile", inputStream -> monitoringUploadsManager .upload(inputStream, NOT_ZIP_FILE_NAME, VSP_ID, VERSION, COMPONENT_ID, - MonitoringUploadType.VES_EVENTS, USER1)); - Assert.fail(); - } catch (Exception exception) { - Assert.assertEquals(exception.getMessage(), "Invalid zip file"); - } + MonitoringUploadType.VES_EVENTS)); } @Test @@ -78,7 +74,7 @@ public class MonitoringUploadsManagerImplTest { try { processFile(ZIP_DIR + ZIP_WITH_FOLDERS_FILE_NAME, inputStream -> monitoringUploadsManager .upload(inputStream, ZIP_WITH_FOLDERS_FILE_NAME, VSP_ID, VERSION, COMPONENT_ID, - MonitoringUploadType.SNMP_TRAP, USER1)); + MonitoringUploadType.SNMP_TRAP)); Assert.fail(); } catch (Exception exception) { Assert.assertEquals(exception.getMessage(), "Zip file should not contain folders"); @@ -91,7 +87,7 @@ public class MonitoringUploadsManagerImplTest { try { processFile(ZIP_DIR + INVALID_VES_FILE_NAME, inputStream -> monitoringUploadsManager .upload(inputStream, INVALID_VES_FILE_NAME, VSP_ID, VERSION, COMPONENT_ID, - MonitoringUploadType.VES_EVENTS, USER1)); + MonitoringUploadType.VES_EVENTS)); Assert.fail(); } catch (Exception exception) { Assert.assertEquals(exception.getMessage(), @@ -122,18 +118,18 @@ public class MonitoringUploadsManagerImplTest { .when(componentArtifactDaoMock).list(anyObject()); MonitoringUploadStatus monitoringUploadStatus = - monitoringUploadsManager.listFilenames(VSP_ID, VERSION, COMPONENT_ID, USER1); + monitoringUploadsManager.listFilenames(VSP_ID, VERSION, COMPONENT_ID); Assert.assertEquals(monitoringUploadStatus.getSnmpTrap(), TRAP_FILE_NAME); Assert.assertEquals(monitoringUploadStatus.getSnmpPoll(), POLL_FILE_NAME); Assert.assertEquals(monitoringUploadStatus.getVesEvent(), VES_FILE_NAME); } - @Test (expectedExceptions = CoreException.class) + @Test(expectedExceptions = CoreException.class) public void testDeleteComponentMibWhenNone() { doReturn(Optional.empty()).when(componentArtifactDaoMock).getByType(any()); monitoringUploadsManager - .delete(VSP_ID, VERSION, COMPONENT_ID, MonitoringUploadType.SNMP_POLL, USER1); + .delete(VSP_ID, VERSION, COMPONENT_ID, MonitoringUploadType.SNMP_POLL); verify(componentArtifactDaoMock, never()).delete(anyObject()); } @@ -146,7 +142,7 @@ public class MonitoringUploadsManagerImplTest { (componentArtifactDaoMock).getByType(anyObject()); monitoringUploadsManager - .delete(VSP_ID, VERSION, COMPONENT_ID, MonitoringUploadType.SNMP_POLL, USER1); + .delete(VSP_ID, VERSION, COMPONENT_ID, MonitoringUploadType.SNMP_POLL); verify(componentArtifactDaoMock).delete(anyObject()); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NetworkManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NetworkManagerImplTest.java index ebdbc6af7d..54687dc80d 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NetworkManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NetworkManagerImplTest.java @@ -53,10 +53,8 @@ public class NetworkManagerImplTest { private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); - private static final String USER1 = "networksTestUser1"; - private static final String USER2 = "networksTestUser2"; private static final String VSP_ID = "vsp"; - private static final Version VERSION = new Version(0, 1); + private static final Version VERSION = new Version("version_id"); private static final String NETWORK1_ID = "network1"; private static final String NETWORK2_ID = "network2"; @@ -85,7 +83,7 @@ public class NetworkManagerImplTest { @Test public void testListWhenNone() { Collection networks = - networkManager.listNetworks(VSP_ID, null, USER1); + networkManager.listNetworks(VSP_ID, null); Assert.assertEquals(networks.size(), 0); } @@ -96,7 +94,7 @@ public class NetworkManagerImplTest { createNetwork(VSP_ID, VERSION, NETWORK2_ID))) .when(networkDaoMock).list(anyObject()); - Collection actual = networkManager.listNetworks(VSP_ID, VERSION, USER1); + Collection actual = networkManager.listNetworks(VSP_ID, VERSION); Assert.assertEquals(actual.size(), 2); } @@ -113,7 +111,7 @@ public class NetworkManagerImplTest { expected.setNetworkCompositionData(networkData); - NetworkEntity created = networkManager.createNetwork(expected, USER1); + NetworkEntity created = networkManager.createNetwork(expected); Assert.assertNotNull(created); expected.setId(created.getId()); expected.setVersion(VERSION01); @@ -131,12 +129,12 @@ public class NetworkManagerImplTest { networkData.setName("network1 name"); networkData.setDhcp(true); network.setNetworkCompositionData(networkData); - testCreate_negative(network, USER1, UniqueValueUtil.UNIQUE_VALUE_VIOLATION); + testCreate_negative(network, UniqueValueUtil.UNIQUE_VALUE_VIOLATION); }*/ @Test public void testCreateOnUploadVsp_negative() { - testCreate_negative(new NetworkEntity(VSP_ID, VERSION, null), USER1, + testCreate_negative(new NetworkEntity(VSP_ID, VERSION, null), VendorSoftwareProductErrorCodes.VSP_COMPOSITION_EDIT_NOT_ALLOWED); } @@ -148,7 +146,7 @@ public class NetworkManagerImplTest { @Test public void testUpdateNonExistingNetworkId_negative() { - testUpdate_negative(VSP_ID, VERSION, NETWORK1_ID, USER1, + testUpdate_negative(VSP_ID, VERSION, NETWORK1_ID, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @@ -171,7 +169,7 @@ public class NetworkManagerImplTest { networkEntity.setNetworkCompositionData(networkData); CompositionEntityValidationData validationData = - networkManager.updateNetwork(networkEntity, USER1); + networkManager.updateNetwork(networkEntity); Assert.assertNotNull(validationData); Assert.assertEquals(validationData.getErrors().size(), 2); @@ -180,7 +178,7 @@ public class NetworkManagerImplTest { @Test public void testGetNonExistingNetworkId_negative() { - testGet_negative(VSP_ID, VERSION, NETWORK1_ID, USER1, + testGet_negative(VSP_ID, VERSION, NETWORK1_ID, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @@ -192,7 +190,7 @@ public class NetworkManagerImplTest { doReturn("schema string").when(networkManager).getCompositionSchema(anyObject()); CompositionEntityResponse response = - networkManager.getNetwork(VSP_ID, VERSION, NETWORK1_ID, USER1); + networkManager.getNetwork(VSP_ID, VERSION, NETWORK1_ID); Assert.assertEquals(response.getId(), network.getId()); Assert.assertEquals(response.getData(), network.getNetworkCompositionData()); Assert.assertNotNull(response.getSchema()); @@ -206,13 +204,13 @@ public class NetworkManagerImplTest { @Test(dependsOnMethods = "testList") public void testDeleteNonExistingNetworkId_negative() { - testDelete_negative(VSP_ID, "non existing network id", USER1, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); + testDelete_negative(VSP_ID, "non existing network id", VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); }*/ /* @Test(dependsOnMethods = "testList") public void testDelete() { - networkManager.deleteNetwork(VSP_ID, NETWORK1_ID, USER1); + networkManager.deleteNetwork(VSP_ID, NETWORK1_ID); NetworkEntity actual = networkDaoMock.getNetwork(VSP_ID, VERSION01, NETWORK1_ID); Assert.assertNull(actual); } @@ -224,70 +222,69 @@ public class NetworkManagerImplTest { NetworkEntity network3 = new NetworkEntity(VSP_ID, null, null); network3.setName("network3 name"); network3.setDescription("network3 desc"); - networkManager.createNetwork(network3, USER1); + networkManager.createNetwork(network3); - networkManager.deleteNetworks(VSP_ID, USER1); + networkManager.deleteNetworks(VSP_ID); - Collection actual = networkManager.listNetworks(VSP_ID, null, USER1); + Collection actual = networkManager.listNetworks(VSP_ID, null); Assert.assertEquals(actual.size(), 0); }*/ @Test(dependsOnMethods = "testList") public void testDeleteOnUploadVsp_negative() { - testDelete_negative(VSP_ID, VERSION, NETWORK1_ID, USER1, + testDelete_negative(VSP_ID, VERSION, NETWORK1_ID, VendorSoftwareProductErrorCodes.VSP_COMPOSITION_EDIT_NOT_ALLOWED); } - private void testCreate_negative(NetworkEntity network, String user, String expectedErrorCode) { + private void testCreate_negative(NetworkEntity network, String expectedErrorCode) { try { - networkManager.createNetwork(network, user); + networkManager.createNetwork(network); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); + log.debug("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } - private void testGet_negative(String vspId, Version version, String networkId, String user, + private void testGet_negative(String vspId, Version version, String networkId, String expectedErrorCode) { try { - networkManager.getNetwork(vspId, version, networkId, user); + networkManager.getNetwork(vspId, version, networkId); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); + log.debug("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } - private void testUpdate_negative(String vspId, Version version, String networkId, String user, + private void testUpdate_negative(String vspId, Version version, String networkId, String expectedErrorCode) { try { - networkManager.updateNetwork(new NetworkEntity(vspId, version, networkId), user); + networkManager.updateNetwork(new NetworkEntity(vspId, version, networkId)); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); + log.debug("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } - private void testList_negative(String vspId, Version version, String user, - String expectedErrorCode) { + private void testList_negative(String vspId, Version version, String expectedErrorCode) { try { - networkManager.listNetworks(vspId, version, user); + networkManager.listNetworks(vspId, version); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); + log.debug("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } - private void testDelete_negative(String vspId, Version version, String networkId, String user, + private void testDelete_negative(String vspId, Version version, String networkId, String expectedErrorCode) { try { - networkManager.deleteNetwork(vspId, version, networkId, user); + networkManager.deleteNetwork(vspId, version, networkId); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); + log.debug("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NicManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NicManagerImplTest.java index ba04e91c63..959b501c19 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NicManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NicManagerImplTest.java @@ -1,10 +1,5 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -35,17 +30,21 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + public class NicManagerImplTest { private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); private static final String NIC_NOT_EXIST_MSG = "Vendor Software Product NIC with Id nic1 does not exist for Vendor Software Product with " + - "id VSP_ID and version 0.1"; + "id VSP_ID and version version_id"; - private static final String USER = "nicTestUser"; private static final String VSP_ID = "VSP_ID"; - private static final Version VERSION = new Version(0, 1); + private static final Version VERSION = new Version("version_id"); private static final String COMPONENT_ID = "COMPONENT_ID"; private static final String NIC1_ID = "nic1"; private static final String NIC2_ID = "nic2"; @@ -71,7 +70,7 @@ public class NicManagerImplTest { @Test public void testListWhenNone() { - Collection nics = nicManager.listNics(VSP_ID, VERSION, COMPONENT_ID, USER); + Collection nics = nicManager.listNics(VSP_ID, VERSION, COMPONENT_ID); Assert.assertEquals(nics.size(), 0); } @@ -85,9 +84,9 @@ public class NicManagerImplTest { NetworkEntity network1 = NetworkManagerImplTest.createNetwork(VSP_ID, VERSION, NETWORK1_ID); NetworkEntity network2 = NetworkManagerImplTest.createNetwork(VSP_ID, VERSION, NETWORK2_ID); doReturn(Arrays.asList(network1, network2)) - .when(networkManagerMock).listNetworks(VSP_ID, VERSION, USER); + .when(networkManagerMock).listNetworks(VSP_ID, VERSION); - Collection nics = nicManager.listNics(VSP_ID, VERSION, COMPONENT_ID, USER); + Collection nics = nicManager.listNics(VSP_ID, VERSION, COMPONENT_ID); Assert.assertEquals(nics.size(), 2); for (NicEntity nic : nics) { Assert.assertEquals(nic.getNicCompositionData().getNetworkName(), @@ -103,12 +102,12 @@ public class NicManagerImplTest { Nic nic = nicEntity.getNicCompositionData(); nic.setNetworkType(NetworkType.Internal); nicEntity.setNicCompositionData(nic); - doReturn(true).when(vspInfoDao).isManual(anyObject(),anyObject()); + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); Collection nicEntities = new ArrayList<>(); doReturn(nicEntities).when(nicDao).list(anyObject()); doReturn(nicEntity).when(compositionEntityDataManagerMock).createNic(anyObject()); - NicEntity created = nicManager.createNic(nicEntity,USER); + NicEntity created = nicManager.createNic(nicEntity); Assert.assertNotNull(created); } @@ -118,7 +117,7 @@ public class NicManagerImplTest { Nic nic = nicEntity.getNicCompositionData(); nic.setNetworkType(NetworkType.Internal); nicEntity.setNicCompositionData(nic); - doReturn(true).when(vspInfoDao).isManual(anyObject(),anyObject()); + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); Collection nicEntities = new ArrayList<>(); NicEntity nicEntityDiffName = createNic(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, NETWORK1_ID); @@ -130,11 +129,11 @@ public class NicManagerImplTest { doReturn(nicEntity).when(compositionEntityDataManagerMock).createNic(anyObject()); try { - NicEntity created = nicManager.createNic(nicEntity,USER); - } catch (CoreException exception) { - log.debug("",exception); - Assert.assertEquals(VendorSoftwareProductErrorCodes.NIC_NAME_FORMAT_NOT_ALLOWED, - exception.code().id()); + NicEntity created = nicManager.createNic(nicEntity); + } catch (CoreException exception) { + log.debug("", exception); + Assert.assertEquals(VendorSoftwareProductErrorCodes.NIC_NAME_FORMAT_NOT_ALLOWED, + exception.code().id()); } } @@ -144,7 +143,7 @@ public class NicManagerImplTest { Nic nic = nicEntity.getNicCompositionData(); nic.setNetworkType(NetworkType.Internal); nicEntity.setNicCompositionData(nic); - doReturn(true).when(vspInfoDao).isManual(anyObject(),anyObject()); + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); Collection nicEntities = new ArrayList<>(); NicEntity nicEntityDiffName = createNic(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, NETWORK1_ID); @@ -156,11 +155,11 @@ public class NicManagerImplTest { doReturn(nicEntity).when(compositionEntityDataManagerMock).createNic(anyObject()); try { - NicEntity created = nicManager.createNic(nicEntity,USER); - } catch (CoreException exception) { - log.debug("",exception); - Assert.assertEquals("Invalid request, NIC with name "+ nic.getName() + - " already exist for component with ID "+ nicEntity.getComponentId() +".", + NicEntity created = nicManager.createNic(nicEntity); + } catch (CoreException exception) { + log.debug("", exception); + Assert.assertEquals("Invalid request, NIC with name " + nic.getName() + + " already exist for component with ID " + nicEntity.getComponentId() + ".", exception.code().message()); Assert.assertEquals(VendorSoftwareProductErrorCodes.DUPLICATE_NIC_NAME_NOT_ALLOWED, exception.code().id()); @@ -173,19 +172,20 @@ public class NicManagerImplTest { Nic nic = nicEntity.getNicCompositionData(); nic.setNetworkType(NetworkType.External); nicEntity.setNicCompositionData(nic); - doReturn(true).when(vspInfoDao).isManual(anyObject(),anyObject()); + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); Collection nicEntities = new ArrayList<>(); doReturn(nicEntities).when(nicDao).list(anyObject()); doReturn(nicEntity).when(compositionEntityDataManagerMock).createNic(anyObject()); try { - NicEntity created = nicManager.createNic(nicEntity,USER); - } catch (CoreException exception) { - log.debug("",exception); + NicEntity created = nicManager.createNic(nicEntity); + } catch (CoreException exception) { + log.debug("", exception); Assert.assertEquals("Invalid request,NetworkId not allowed for External Networks", exception.code().message()); - Assert.assertEquals(VendorSoftwareProductErrorCodes.NETWORKID_NOT_ALLOWED_FOR_EXTERNAL_NETWORK, - exception.code().id()); + Assert + .assertEquals(VendorSoftwareProductErrorCodes.NETWORKID_NOT_ALLOWED_FOR_EXTERNAL_NETWORK, + exception.code().id()); } } @@ -196,29 +196,29 @@ public class NicManagerImplTest { nic.setNetworkType(NetworkType.Internal); nic.setNetworkDescription(NIC1_ID); nicEntity.setNicCompositionData(nic); - doReturn(true).when(vspInfoDao).isManual(anyObject(),anyObject()); + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); Collection nicEntities = new ArrayList<>(); doReturn(nicEntities).when(nicDao).list(anyObject()); doReturn(nicEntity).when(compositionEntityDataManagerMock).createNic(anyObject()); try { - NicEntity created = nicManager.createNic(nicEntity,USER); - } catch (CoreException exception) { - log.debug("",exception); + NicEntity created = nicManager.createNic(nicEntity); + } catch (CoreException exception) { + log.debug("", exception); Assert.assertEquals("Invalid request, Network Description not allowed for Internal Networks", exception.code().message()); Assert.assertEquals(VendorSoftwareProductErrorCodes - .NETWORK_DESCRIPTION_NOT_ALLOWED_FOR_INTERNAL_NETWORK,exception.code().id()); + .NETWORK_DESCRIPTION_NOT_ALLOWED_FOR_INTERNAL_NETWORK, exception.code().id()); } } @Test public void testDeleteNic() { NicEntity nicEntity = createNic(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, NETWORK1_ID); - doReturn(true).when(vspInfoDao).isManual(anyObject(),anyObject()); + doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); doReturn(nicEntity).when(nicDao).get(anyObject()); - nicManager.deleteNic(VSP_ID,new Version(0,1),COMPONENT_ID,NIC1_ID,USER); + nicManager.deleteNic(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID); } @@ -227,9 +227,12 @@ public class NicManagerImplTest { NicEntity nicEntity = createNic(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, NETWORK1_ID); doReturn(nicEntity).when(nicDao).get(anyObject()); + doReturn("{}").when(nicManager).getNicCompositionSchema(anyObject()); - nicManager.updateNicQuestionnaire(VSP_ID,new Version(0,1),COMPONENT_ID,NIC1_ID,"Ques",USER); + nicManager + .updateNicQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, "Ques"); + verify(nicDao).updateQuestionnaireData(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, "Ques"); } // @Test(dependsOnMethods = "testListWhenNone") @@ -243,7 +246,7 @@ public class NicManagerImplTest { Nic nicData = new Nic(); nicData.setName("nic1 name"); nic.setNicCompositionData(nicData); - testCreate_negative(nic, USER, UniqueValueUtil.UNIQUE_VALUE_VIOLATION); + testCreate_negative(nic, UniqueValueUtil.UNIQUE_VALUE_VIOLATION); }*/ // @Test(dependsOnMethods = {"testCreate"}) @@ -254,7 +257,7 @@ public class NicManagerImplTest { // compData12.setDescription("comp12 desc"); // component12.setComponentCompositionData(compData12); // -// String component12Id = nicManager.createComponent(component12, USER).getId(); +// String component12Id = nicManager.createComponent(component12).getId(); // testCreate(VSP_ID, component12Id, NETWORK1_ID, NETWORK1_ID.getNetworkCompositionData().getName()); // } @@ -266,7 +269,7 @@ public class NicManagerImplTest { @Test public void testCreateOnUploadVsp_negative() { - testCreate_negative(new NicEntity(VSP_ID, VERSION, COMPONENT_ID, null), USER, + testCreate_negative(new NicEntity(VSP_ID, VERSION, COMPONENT_ID, null), VendorSoftwareProductErrorCodes.ADD_NIC_NOT_ALLOWED_IN_HEAT_ONBOARDING); } @@ -274,7 +277,7 @@ public class NicManagerImplTest { public void testUpdateNonExistingNicId_negative() { doReturn(null).when(nicDao).get(anyObject()); - testUpdate_negative(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, USER, + testUpdate_negative(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @@ -295,7 +298,7 @@ public class NicManagerImplTest { nicEntity.setNicCompositionData(nicData); CompositionEntityValidationData validationData = - nicManager.updateNic(nicEntity, USER); + nicManager.updateNic(nicEntity); Assert.assertTrue(validationData == null || validationData.getErrors() == null); verify(nicDao).update(nicEntity); } @@ -319,7 +322,7 @@ public class NicManagerImplTest { nicData.setNetworkId(NETWORK1_ID); nicEntity.setNicCompositionData(nicData); - CompositionEntityValidationData validationData = nicManager.updateNic(nicEntity, USER); + CompositionEntityValidationData validationData = nicManager.updateNic(nicEntity); Assert.assertNotNull(validationData); Assert.assertEquals(validationData.getErrors().size(), 2); @@ -329,14 +332,14 @@ public class NicManagerImplTest { @Test public void testUpdateIncorrectNameFormat() { doReturn(createNic(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, NETWORK1_ID)) - .when(nicDao).get(anyObject()); + .when(nicDao).get(anyObject()); CompositionEntityValidationData toBeReturned = - new CompositionEntityValidationData(CompositionEntityType.nic, NIC1_ID); + new CompositionEntityValidationData(CompositionEntityType.nic, NIC1_ID); toBeReturned.setErrors(Arrays.asList("error1", "error2")); doReturn(toBeReturned) - .when(compositionEntityDataManagerMock) - .validateEntity(anyObject(), anyObject(), anyObject()); + .when(compositionEntityDataManagerMock) + .validateEntity(anyObject(), anyObject(), anyObject()); doReturn(true).when(vspInfoDao).isManual(anyObject(), anyObject()); NicEntity nicEntity = new NicEntity(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID); @@ -347,20 +350,19 @@ public class NicManagerImplTest { nicEntity.setNicCompositionData(nicData); try { - nicManager.updateNic(nicEntity, USER); + nicManager.updateNic(nicEntity); Assert.fail(); - } - catch (CoreException ex) { - log.debug("",ex); + } catch (CoreException ex) { + log.debug("", ex); Assert.assertEquals(VendorSoftwareProductErrorCodes.NIC_NAME_FORMAT_NOT_ALLOWED, - ex.code().id()); + ex.code().id()); } } @Test public void testGetNonExistingNicId_negative() { - testGet_negative(VSP_ID, VERSION, COMPONENT_ID, "non existing nic id", USER, + testGet_negative(VSP_ID, VERSION, COMPONENT_ID, "non existing nic id", VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @@ -373,7 +375,7 @@ public class NicManagerImplTest { doReturn(compositionSchema).when(nicManager).getNicCompositionSchema(anyObject()); CompositionEntityResponse response = - nicManager.getNic(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, USER); + nicManager.getNic(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID); Assert.assertEquals(response.getId(), expected.getId()); Assert.assertEquals(response.getData(), expected.getNicCompositionData()); Assert.assertEquals(response.getSchema(), compositionSchema); @@ -387,32 +389,32 @@ public class NicManagerImplTest { @Test public void testDeleteNonExistingNicId_negative() { - testDelete_negative(VSP_ID, COMPONENT_ID, "non existing nic id", USER, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); + testDelete_negative(VSP_ID, COMPONENT_ID, "non existing nic id", VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); } @Test(dependsOnMethods = "testList") public void testDeleteNonExistingComponentId_negative() { - testDelete_negative(VSP_ID, "non existing component id", NIC1_ID, USER, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); + testDelete_negative(VSP_ID, "non existing component id", NIC1_ID, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); }*/ /* @Test(dependsOnMethods = "testList") public void testDelete() { - nicManager.deleteNic(VSP_ID, COMPONENT_ID, NIC1_ID, USER); + nicManager.deleteNic(VSP_ID, COMPONENT_ID, NIC1_ID); NicEntity actual = vendorSoftwareProductDao.getNic(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID); Assert.assertNull(actual); }*/ @Test public void testDeleteOnUploadVsp_negative() { - testDelete_negative(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, USER, + testDelete_negative(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, VendorSoftwareProductErrorCodes.DELETE_NIC_NOT_ALLOWED); } @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = NIC_NOT_EXIST_MSG) public void testGetNonExistingNicQuestionnaire() throws Exception { - nicManager.getNicQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, USER); + nicManager.getNicQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID); } @Test @@ -425,7 +427,7 @@ public class NicManagerImplTest { doReturn(schema).when(nicManager).getNicQuestionnaireSchema(anyObject()); QuestionnaireResponse questionnaire = - nicManager.getNicQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, USER); + nicManager.getNicQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID); Assert.assertNotNull(questionnaire); Assert.assertEquals(questionnaire.getData(), nic.getQuestionnaireData()); Assert.assertEquals(questionnaire.getSchema(), schema); @@ -437,7 +439,7 @@ public class NicManagerImplTest { public void testUpdateNonExistingNicQuestionnaire() throws Exception { doReturn(null).when(nicDao).get(anyObject()); nicManager - .updateNicQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, "questionnaire data", USER); + .updateNicQuestionnaire(VSP_ID, VERSION, COMPONENT_ID, NIC1_ID, "questionnaire data"); } @Test @@ -445,46 +447,45 @@ public class NicManagerImplTest { } - private void testCreate_negative(NicEntity nic, String user, String expectedErrorCode) { + private void testCreate_negative(NicEntity nic, String expectedErrorCode) { try { - nicManager.createNic(nic, user); + nicManager.createNic(nic); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); + log.debug("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } private void testGet_negative(String vspId, Version version, String componentId, String nicId, - String user, String expectedErrorCode) { + String expectedErrorCode) { try { - nicManager.getNic(vspId, version, componentId, nicId, user); + nicManager.getNic(vspId, version, componentId, nicId); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); + log.debug("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } private void testUpdate_negative(String vspId, Version version, String componentId, String nicId, - String user, String expectedErrorCode) { + String expectedErrorCode) { try { - nicManager.updateNic(new NicEntity(vspId, version, componentId, nicId), user); + nicManager.updateNic(new NicEntity(vspId, version, componentId, nicId)); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); + log.debug("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } private void testDelete_negative(String vspId, Version version, String componentId, String nicId, - String user, String expectedErrorCode) { try { - nicManager.deleteNic(vspId, version, componentId, nicId, user); + nicManager.deleteNic(vspId, version, componentId, nicId); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); + log.debug("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImplTest.java index d1cba65182..26ec917546 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImplTest.java @@ -1,18 +1,14 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doReturn; - import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; @@ -37,10 +33,13 @@ import java.util.Iterator; import java.util.Map; import java.util.Optional; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; + public class OrchestrationTemplateCandidateManagerImplTest { - private static final String USER1 = "vspTestUser1"; private static final String VSP_ID = "vspId"; - private static final Version VERSION01 = new Version(0, 1); + private static final Version VERSION01 = new Version("versionId"); private static final String COMPONENT_ORIG_ID_1 = "Component_Pd_Server_Id_Orig"; private static final String COMPONENT_ORIG_ID_2 = "Component_Sm_Server_Id_Orig"; @@ -57,8 +56,6 @@ public class OrchestrationTemplateCandidateManagerImplTest { private static final String COMPONENT_NAME_3 = "oam_server"; private static final String COMPONENT_NAME_4 = "ps_server"; - @Mock - private VendorSoftwareProductDao vendorSoftwareProductDaoMock; @Mock private VendorSoftwareProductInfoDao vspInfoDaoMock; @Mock @@ -67,6 +64,8 @@ public class OrchestrationTemplateCandidateManagerImplTest { private OrchestrationTemplateDao orchestrationTemplateDaoMock; @Mock private ComponentDependencyModelDao componentDependencyModelDaoMock; + @Mock + private ComponentDao componentDaoMock; @InjectMocks private OrchestrationTemplateCandidateManagerImpl candidateManager; @@ -100,7 +99,7 @@ public class OrchestrationTemplateCandidateManagerImplTest { doReturn(new VspDetails(VSP_ID, VERSION01)) .when(vspInfoDaoMock).get(anyObject()); doReturn(null) - .when(orchestrationTemplateDaoMock).getValidationData(anyObject(), anyObject()); + .when(orchestrationTemplateDaoMock).getInfo(anyObject(), anyObject()); doReturn("{}").when(candidateServiceMock).createManifest(anyObject(), anyObject()); doReturn(Optional.empty()).when(candidateServiceMock) @@ -109,7 +108,7 @@ public class OrchestrationTemplateCandidateManagerImplTest { OrchestrationTemplateActionResponse response = - candidateManager.process(VSP_ID, VERSION01, USER1); + candidateManager.process(VSP_ID, VERSION01); Assert.assertNotNull(response); } @@ -118,12 +117,11 @@ public class OrchestrationTemplateCandidateManagerImplTest { public void testUpdateVspComponentDependenciesHeatReuploadMoreComponents() { Collection existingComponentsDependencies = getExistingComponentDependencies(); - doReturn(existingComponentsDependencies). - when(vendorSoftwareProductDaoMock).listComponentDependencies(anyObject(), anyObject()); + doReturn(existingComponentsDependencies).when(componentDependencyModelDaoMock) + .list(anyObject()); Collection componentListWithMoreComponentsInHeat = getComponentListWithMoreComponentsInHeat(); - doReturn(componentListWithMoreComponentsInHeat).when(vendorSoftwareProductDaoMock) - .listComponents(anyObject(), anyObject()); + doReturn(componentListWithMoreComponentsInHeat).when(componentDaoMock).list(anyObject()); Map componentIdNameInfoBeforeProcess = getVspInitComponentIdNameInfo(); orchestrationUtil.updateVspComponentDependencies(anyObject(), anyObject(), componentIdNameInfoBeforeProcess); @@ -136,14 +134,14 @@ public class OrchestrationTemplateCandidateManagerImplTest { Collection existingComponentsDependencies = getExistingComponentDependencies(); doReturn(existingComponentsDependencies). - when(vendorSoftwareProductDaoMock).listComponentDependencies(anyObject(), anyObject()); + when(componentDependencyModelDaoMock).list(anyObject()); Collection componentListWithLessComponentsInHeat = getComponentListWithLessComponentsInHeat(); - doReturn(componentListWithLessComponentsInHeat).when(vendorSoftwareProductDaoMock) - .listComponents(anyObject(), anyObject()); + doReturn(componentListWithLessComponentsInHeat).when(componentDaoMock).list(anyObject()); Map componentIdNameInfoBeforeProcess = getVspInitComponentIdNameInfo(); - orchestrationUtil.updateVspComponentDependencies(anyObject(), anyObject(), - componentIdNameInfoBeforeProcess); + orchestrationUtil + .updateVspComponentDependencies(anyObject(), anyObject(), + componentIdNameInfoBeforeProcess); Mockito.verify(componentDependencyModelDaoMock, Mockito.times(1)).update(anyObject()); Mockito.verify(componentDependencyModelDaoMock, Mockito.times(1)).delete(anyObject()); } @@ -152,12 +150,11 @@ public class OrchestrationTemplateCandidateManagerImplTest { public void testUpdateVspComponentDependenciesHeatReuploadSameComponents() { Collection existingComponentsDependencies = getExistingComponentDependencies(); - doReturn(existingComponentsDependencies). - when(vendorSoftwareProductDaoMock).listComponentDependencies(anyObject(), anyObject()); + doReturn(existingComponentsDependencies).when(componentDependencyModelDaoMock) + .list(anyObject()); Collection componentListWithSameComponentsInHeat = getComponentListWithSameComponentsInHeat(); - doReturn(componentListWithSameComponentsInHeat).when(vendorSoftwareProductDaoMock) - .listComponents(anyObject(), anyObject()); + doReturn(componentListWithSameComponentsInHeat).when(componentDaoMock).list(anyObject()); Map componentIdNameInfoBeforeProcess = getVspInitComponentIdNameInfo(); orchestrationUtil.updateVspComponentDependencies(anyObject(), anyObject(), componentIdNameInfoBeforeProcess); @@ -169,12 +166,11 @@ public class OrchestrationTemplateCandidateManagerImplTest { public void testUpdateVspComponentDependenciesHeatReuploadNoComponents() { Collection existingComponentsDependencies = getExistingComponentDependencies(); - doReturn(existingComponentsDependencies). - when(vendorSoftwareProductDaoMock).listComponentDependencies(anyObject(), anyObject()); + doReturn(existingComponentsDependencies).when(componentDependencyModelDaoMock) + .list(anyObject()); Collection componentListWithMoreComponentsInHeat = new ArrayList<>(); - doReturn(componentListWithMoreComponentsInHeat).when(vendorSoftwareProductDaoMock) - .listComponents(anyObject(), anyObject()); + doReturn(componentListWithMoreComponentsInHeat).when(componentDaoMock).list(anyObject()); Map componentIdNameInfoBeforeProcess = getVspInitComponentIdNameInfo(); orchestrationUtil.updateVspComponentDependencies(anyObject(), anyObject(), componentIdNameInfoBeforeProcess); @@ -193,8 +189,7 @@ public class OrchestrationTemplateCandidateManagerImplTest { @Test public void testVspComponentIdNameInfo() { Collection initialVspComponents = getInitialVspComponents(); - doReturn(initialVspComponents).when(vendorSoftwareProductDaoMock) - .listComponents(anyObject(), anyObject()); + doReturn(initialVspComponents).when(componentDaoMock).list(anyObject()); Map vspComponentIdNameInfo = orchestrationUtil.getVspComponentIdNameInfo(anyObject(), anyObject()); Assert.assertEquals(vspComponentIdNameInfo.size(), 3); @@ -210,8 +205,7 @@ public class OrchestrationTemplateCandidateManagerImplTest { componentEntity.setId(COMPONENT_ORIG_ID_4); initialVspComponents.add(componentEntity); - doReturn(initialVspComponents).when(vendorSoftwareProductDaoMock) - .listComponents(anyObject(), anyObject()); + doReturn(initialVspComponents).when(componentDaoMock).list(anyObject()); Map vspComponentIdNameInfo = orchestrationUtil.getVspComponentIdNameInfo(anyObject(), anyObject()); Assert.assertEquals(vspComponentIdNameInfo.size(), 3); @@ -250,7 +244,7 @@ public class OrchestrationTemplateCandidateManagerImplTest { private Collection getComponentListWithLessComponentsInHeat() { Collection vspComponents = getInitialVspComponents(); - for (Iterator iterator = vspComponents.iterator(); iterator.hasNext();) { + for (Iterator iterator = vspComponents.iterator(); iterator.hasNext(); ) { ComponentEntity componentEntity = iterator.next(); if (componentEntity.getComponentCompositionData().getName().equals(COMPONENT_NAME_1)) { iterator.remove(); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateProcessCsarHandlerTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateProcessCsarHandlerTest.java index c2a207d6d9..bc3727381b 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateProcessCsarHandlerTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateProcessCsarHandlerTest.java @@ -6,14 +6,12 @@ import org.openecomp.core.enrichment.factory.EnrichmentManagerFactory; import org.openecomp.core.factory.impl.AbstractFactoryBase; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.factory.CandidateServiceFactory; import org.openecomp.sdc.vendorsoftwareproduct.impl.mock.CandidateServiceFactoryMock; import org.openecomp.sdc.vendorsoftwareproduct.impl.mock.NoSqlDbFactoryMock; import org.openecomp.sdc.vendorsoftwareproduct.impl.mock.PackageInfoDaoFactoryImplMock; -import org.openecomp.sdc.vendorsoftwareproduct.impl.mock.VendorSoftwareProductDaoFactoryMock; import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process.OrchestrationTemplateProcessCsarHandler; import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse; import org.openecomp.sdc.versioning.dao.types.Version; @@ -21,27 +19,31 @@ import org.openecomp.sdc.versioning.dao.types.Version; import java.nio.ByteBuffer; import static org.junit.Assert.assertFalse; -public class OrchestrationTemplateProcessCsarHandlerTest { - - - @Before - public void insertMocks(){ - EnrichmentManagerFactory.getInstance(); - AbstractFactoryBase.registerFactory(NoSqlDbFactory.class, NoSqlDbFactoryMock.class); - AbstractFactoryBase.registerFactory(PackageInfoDaoFactory.class, PackageInfoDaoFactoryImplMock.class); - AbstractFactoryBase.registerFactory(PackageInfoDaoFactory.class, PackageInfoDaoFactoryImplMock.class); - AbstractFactoryBase.registerFactory(VendorSoftwareProductDaoFactory.class, VendorSoftwareProductDaoFactoryMock.class); - AbstractFactoryBase.registerFactory(CandidateServiceFactory.class, CandidateServiceFactoryMock.class); - } +public class OrchestrationTemplateProcessCsarHandlerTest { - @Test - public void validateErrorHandling(){ - VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); - OrchestrationTemplateCandidateData orchestrationTemplateCandidateData = new OrchestrationTemplateCandidateData(ByteBuffer.wrap("".getBytes()),""); - OrchestrationTemplateProcessCsarHandler handler = new OrchestrationTemplateProcessCsarHandler(); - OrchestrationTemplateActionResponse response = handler.process(vspDetails, orchestrationTemplateCandidateData, "007"); - assertFalse(response.getErrors().isEmpty()); - } + @Before + public void insertMocks() { + EnrichmentManagerFactory.getInstance(); + AbstractFactoryBase.registerFactory(NoSqlDbFactory.class, NoSqlDbFactoryMock.class); + AbstractFactoryBase + .registerFactory(PackageInfoDaoFactory.class, PackageInfoDaoFactoryImplMock.class); + AbstractFactoryBase + .registerFactory(PackageInfoDaoFactory.class, PackageInfoDaoFactoryImplMock.class); + AbstractFactoryBase + .registerFactory(CandidateServiceFactory.class, CandidateServiceFactoryMock.class); + } + + + @Test + public void validateErrorHandling() { + VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); + OrchestrationTemplateCandidateData orchestrationTemplateCandidateData = + new OrchestrationTemplateCandidateData(ByteBuffer.wrap("".getBytes()), "", "zip", "file"); + OrchestrationTemplateProcessCsarHandler handler = new OrchestrationTemplateProcessCsarHandler(); + OrchestrationTemplateActionResponse response = + handler.process(vspDetails, orchestrationTemplateCandidateData); + assertFalse(response.getErrors().isEmpty()); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerImplTest.java index 478bdfbbba..b925ab9270 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerImplTest.java @@ -1,19 +1,18 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.openecomp.sdc.activityLog.ActivityLogManager; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessType; import org.openecomp.sdc.versioning.dao.types.Version; @@ -28,12 +27,13 @@ import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collection; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.mockito.Matchers.eq; public class ProcessManagerImplTest { @@ -48,9 +48,7 @@ public class ProcessManagerImplTest { private static final String ARTIFACT_NAME = "artifact.sh"; @Mock - private VendorSoftwareProductDao vendorSoftwareProductDaoMock; - @Mock - private ActivityLogManager activityLogManagerMock; + private ProcessDao processDaoMock; @InjectMocks @Spy @@ -66,7 +64,7 @@ public class ProcessManagerImplTest { @Test public void testListWhenNone() { Collection processes = - processManager.listProcesses(VSP_ID, VERSION, COMPONENT_ID, USER1); + processManager.listProcesses(VSP_ID, VERSION, COMPONENT_ID); Assert.assertEquals(processes.size(), 0); } @@ -75,17 +73,17 @@ public class ProcessManagerImplTest { doReturn(Arrays.asList( createProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID), createProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS2_ID))) - .when(vendorSoftwareProductDaoMock).listProcesses(VSP_ID, VERSION, COMPONENT_ID); + .when(processDaoMock).list(any(ProcessEntity.class)); Collection actual = - processManager.listProcesses(VSP_ID, VERSION, COMPONENT_ID, USER1); + processManager.listProcesses(VSP_ID, VERSION, COMPONENT_ID); Assert.assertEquals(actual.size(), 2); } @Test public void testDeleteListWhenNone() { - processManager.deleteProcesses(VSP_ID, VERSION, COMPONENT_ID, USER1); - verify(vendorSoftwareProductDaoMock, never()).deleteProcesses(VSP_ID, VERSION, COMPONENT_ID); + processManager.deleteProcesses(VSP_ID, VERSION, COMPONENT_ID); + verify(processDaoMock, never()).delete(any(ProcessEntity.class)); } @Test @@ -93,15 +91,15 @@ public class ProcessManagerImplTest { ProcessEntity process1 = createProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); ProcessEntity process2 = createProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS2_ID); doReturn(Arrays.asList(process1, process2)) - .when(vendorSoftwareProductDaoMock).listProcesses(VSP_ID, VERSION, COMPONENT_ID); + .when(processDaoMock).list(any(ProcessEntity.class)); doNothing().when(processManager) .deleteUniqueValue(VSP_ID, VERSION, COMPONENT_ID, process1.getName()); doNothing().when(processManager) .deleteUniqueValue(VSP_ID, VERSION, COMPONENT_ID, process2.getName()); - processManager.deleteProcesses(VSP_ID, VERSION, COMPONENT_ID, USER1); + processManager.deleteProcesses(VSP_ID, VERSION, COMPONENT_ID); - verify(vendorSoftwareProductDaoMock).deleteProcesses(VSP_ID, VERSION, COMPONENT_ID); + verify(processDaoMock).deleteAll(eq(new ProcessEntity(VSP_ID, VERSION, COMPONENT_ID, null))); verify(processManager) .deleteUniqueValue(VSP_ID, VERSION, COMPONENT_ID, process1.getName()); verify(processManager) @@ -118,7 +116,7 @@ public class ProcessManagerImplTest { doNothing().when(processManager) .createUniqueName(VSP_ID, VERSION, COMPONENT_ID, processToCreate.getName()); - ProcessEntity process = processManager.createProcess(processToCreate, USER1); + ProcessEntity process = processManager.createProcess(processToCreate); Assert.assertNotNull(process); process.setId(process.getId()); @@ -134,13 +132,12 @@ public class ProcessManagerImplTest { new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).build())) .when(processManager).validateUniqueName(VSP_ID, VERSION, COMPONENT_ID, process.getName()); - processManager.createProcess(process, USER1); + processManager.createProcess(process); } @Test public void testUpdateNonExistingProcessId_negative() { - doReturn(null).when(vendorSoftwareProductDaoMock) - .getProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + doReturn(null).when(processDaoMock).get(any(ProcessEntity.class)); testUpdate_negative(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID, USER1, VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); @@ -149,8 +146,7 @@ public class ProcessManagerImplTest { @Test(expectedExceptions = CoreException.class) public void testUpdateWithExistingName_negative() { ProcessEntity existingProcess = createProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); - doReturn(existingProcess).when - (vendorSoftwareProductDaoMock).getProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + doReturn(existingProcess).when(processDaoMock).get(any(ProcessEntity.class)); ProcessEntity processToUpdate = createProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); doThrow(new CoreException( @@ -159,22 +155,21 @@ public class ProcessManagerImplTest { .updateUniqueName(VSP_ID, VERSION, COMPONENT_ID, existingProcess.getName(), processToUpdate.getName()); - processManager.updateProcess(processToUpdate, USER1); + processManager.updateProcess(processToUpdate); } @Test public void testUpdate() { ProcessEntity existingProcess = createProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); - doReturn(existingProcess).when - (vendorSoftwareProductDaoMock).getProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + doReturn(existingProcess).when(processDaoMock).get(any(ProcessEntity.class)); ProcessEntity processToUpdate = createProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); doNothing().when(processManager) .updateUniqueName(VSP_ID, VERSION, COMPONENT_ID, existingProcess.getName(), processToUpdate.getName()); - processManager.updateProcess(processToUpdate, USER1); - verify(vendorSoftwareProductDaoMock).updateProcess(processToUpdate); + processManager.updateProcess(processToUpdate); + verify(processDaoMock).update(processToUpdate); } @@ -187,10 +182,9 @@ public class ProcessManagerImplTest { @Test public void testGet() { ProcessEntity process = createProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); - doReturn(process).when - (vendorSoftwareProductDaoMock).getProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + doReturn(process).when(processDaoMock).get(any(ProcessEntity.class)); ProcessEntity actual = - processManager.getProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID, USER1); + processManager.getProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); Assert.assertEquals(actual, process); Assert.assertNull(actual.getArtifactName()); } @@ -199,29 +193,28 @@ public class ProcessManagerImplTest { public void testGetAfterUploadArtifact() { ProcessEntity process = createProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); process.setArtifactName(ARTIFACT_NAME); - doReturn(process).when - (vendorSoftwareProductDaoMock).getProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + doReturn(process).when(processDaoMock).get(any(ProcessEntity.class)); ProcessEntity actual = - processManager.getProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID, USER1); + processManager.getProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); Assert.assertEquals(actual, process); Assert.assertEquals(actual.getArtifactName(), ARTIFACT_NAME); } @Test(expectedExceptions = CoreException.class) public void testDeleteNonExistingProcessId_negative() { - processManager.deleteProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID, USER1); + processManager.deleteProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); } @Test public void testDelete() { ProcessEntity processToDelete = createProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); - doReturn(processToDelete).when - (vendorSoftwareProductDaoMock).getProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + doReturn(processToDelete).when(processDaoMock) + .get(any(ProcessEntity.class)); doNothing().when(processManager).deleteUniqueValue(VSP_ID, VERSION, COMPONENT_ID, processToDelete.getName()); - processManager.deleteProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID, USER1); - verify(vendorSoftwareProductDaoMock).deleteProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + processManager.deleteProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + verify(processDaoMock).delete(any(ProcessEntity.class)); verify(processManager) .deleteUniqueValue(VSP_ID, VERSION, COMPONENT_ID, processToDelete.getName()); } @@ -235,21 +228,13 @@ public class ProcessManagerImplTest { @Test public void testUploadArtifact() { ProcessEntity process = createProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); - doReturn(process).when - (vendorSoftwareProductDaoMock).getProcess(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + doReturn(process).when(processDaoMock).get(any(ProcessEntity.class)); byte[] artifactBytes = "bla bla".getBytes(); processManager .uploadProcessArtifact(new ByteArrayInputStream(artifactBytes), ARTIFACT_NAME, - VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID, USER1); - verify(vendorSoftwareProductDaoMock) - .uploadProcessArtifact(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID, artifactBytes, - ARTIFACT_NAME); - - verify(activityLogManagerMock).addActionLog(activityLogEntityArg.capture(), eq(USER1)); - ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue(); - Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION.getMajor()+1)); - Assert.assertTrue(activityLogEntity.isSuccess()); + VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + verify(processDaoMock).uploadArtifact(any(ProcessEntity.class)); } @Test @@ -269,11 +254,11 @@ public class ProcessManagerImplTest { ProcessEntity processArtifact = new ProcessEntity(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); processArtifact.setArtifact(ByteBuffer.wrap("bla bla".getBytes())); - doReturn(processArtifact).when(vendorSoftwareProductDaoMock) - .getProcessArtifact(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + doReturn(processArtifact).when(processDaoMock) + .getArtifact(any(ProcessEntity.class)); File actual = - processManager.getProcessArtifact(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID, USER1); + processManager.getProcessArtifact(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); Assert.assertNotNull(actual); } @@ -294,12 +279,12 @@ public class ProcessManagerImplTest { ProcessEntity processArtifact = new ProcessEntity(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); processArtifact.setArtifact(ByteBuffer.wrap("bla bla".getBytes())); - doReturn(processArtifact).when(vendorSoftwareProductDaoMock) - .getProcessArtifact(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + doReturn(processArtifact).when(processDaoMock) + .getArtifact(any(ProcessEntity.class)); - processManager.deleteProcessArtifact(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID, USER1); - verify(vendorSoftwareProductDaoMock) - .deleteProcessArtifact(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + processManager.deleteProcessArtifact(VSP_ID, VERSION, COMPONENT_ID, PROCESS1_ID); + verify(processDaoMock) + .deleteArtifact(any(ProcessEntity.class)); } @@ -315,10 +300,10 @@ public class ProcessManagerImplTest { private void testGet_negative(String vspId, Version version, String componentId, String processId, String user, String expectedErrorCode) { try { - processManager.getProcess(vspId, version, componentId, processId, user); + processManager.getProcess(vspId, version, componentId, processId); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); + log.debug("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } @@ -328,10 +313,10 @@ public class ProcessManagerImplTest { String expectedErrorCode) { try { processManager - .updateProcess(new ProcessEntity(vspId, version, componentId, processId), user); + .updateProcess(new ProcessEntity(vspId, version, componentId, processId)); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); + log.debug("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } @@ -339,10 +324,10 @@ public class ProcessManagerImplTest { private void testGetFile_negative(String vspId, Version version, String componentId, String processId, String user, String expectedErrorCode) { try { - processManager.getProcessArtifact(vspId, version, componentId, processId, user); + processManager.getProcessArtifact(vspId, version, componentId, processId); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); + log.debug("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } @@ -353,10 +338,10 @@ public class ProcessManagerImplTest { try { processManager .uploadProcessArtifact(new ByteArrayInputStream("bla bla".getBytes()), "artifact.sh", - vspId, version, componentId, processId, user); + vspId, version, componentId, processId); Assert.fail(); } catch (CoreException exception) { - log.error("",exception); + log.error("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } @@ -364,10 +349,10 @@ public class ProcessManagerImplTest { private void testDeleteArtifact_negative(String vspId, String componentId, String processId, String user, String expectedErrorCode) { try { - processManager.deleteProcessArtifact(vspId, VERSION, componentId, processId, user); + processManager.deleteProcessArtifact(vspId, VERSION, componentId, processId); Assert.fail(); } catch (CoreException exception) { - log.debug("",exception); + log.debug("", exception); Assert.assertEquals(exception.code().id(), expectedErrorCode); } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImplTest.java index 5199dfd365..7721817c3b 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImplTest.java @@ -33,15 +33,12 @@ import org.openecomp.core.model.dao.ServiceModelDao; import org.openecomp.core.model.types.ServiceElement; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.sdc.activityLog.ActivityLogManager; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.healing.api.HealingManager; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; @@ -53,18 +50,16 @@ import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants; import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.impl.mock.EnrichmentManagerFactoryImpl; import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.InformationArtifactGenerator; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse; -import org.openecomp.sdc.vendorsoftwareproduct.types.VersionedVendorSoftwareProductInfo; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.DeploymentFlavor; import org.openecomp.sdc.versioning.VersioningManager; import org.openecomp.sdc.versioning.dao.types.Version; @@ -94,7 +89,6 @@ import java.util.zip.ZipInputStream; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; @@ -103,13 +97,10 @@ import static org.mockito.Mockito.verify; public class VendorSoftwareProductManagerImplTest { - - private static final Logger LOG = LoggerFactory.getLogger(VendorSoftwareProductManagerImplTest.class); - private static final String INVALID_VERSION_MSG = "Invalid requested version."; - private static final String VSP_ID = "vspId"; - private static final String VERSION_ID = "versionId"; + private static String VSP_ID = "vspId"; + private static String VERSION_ID = "versionId"; public static final Version VERSION01 = new Version(0, 1); private static final Version VERSION10 = new Version(1, 0); private static final String USER1 = "vspTestUser1"; @@ -121,8 +112,6 @@ public class VendorSoftwareProductManagerImplTest { @Mock private VersioningManager versioningManagerMock; @Mock - private VendorSoftwareProductDao vendorSoftwareProductDaoMock; // todo get rid of - @Mock private OrchestrationTemplateDao orchestrationTemplateDataDaoMock; @Mock private VendorLicenseFacade vendorLicenseFacadeMock; @@ -139,8 +128,6 @@ public class VendorSoftwareProductManagerImplTest { @Mock private InformationArtifactGenerator informationArtifactGeneratorMock; @Mock - private ActivityLogManager activityLogManagerMock; - @Mock private PackageInfoDao packageInfoDao; @Mock private VendorSoftwareProductInfoDao vspInfoDaoMock; @@ -164,14 +151,14 @@ public class VendorSoftwareProductManagerImplTest { public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } - +/* @Test public void testListWhenNone() { doReturn(new HashMap<>()).when(versioningManagerMock).listEntitiesVersionInfo - (VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, USER1, - VersionableEntityAction.Read); + (VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, USER1, + VersionableEntityAction.Read); List vsps = - vendorSoftwareProductManager.listVsps(null, USER1); + vendorSoftwareProductManager.listVsps(null); Assert.assertEquals(vsps.size(), 0); } @@ -190,16 +177,16 @@ public class VendorSoftwareProductManagerImplTest { vspsTobeReturned.put(vsp2id, versionInfo2); doReturn(vspsTobeReturned).when(versioningManagerMock).listEntitiesVersionInfo - (VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, USER1, - VersionableEntityAction.Read); + (VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, USER1, + VersionableEntityAction.Read); VspDetails vsp1 = new VspDetails(vsp1id, VERSION01); vsp1.setWritetimeMicroSeconds(8L); doReturn(vsp1).when(vspInfoDaoMock) - .get(any(VspDetails.class)); + .get(any(VspDetails.class)); List vsps = - vendorSoftwareProductManager.listVsps(null, USER1); + vendorSoftwareProductManager.listVsps(null); Assert.assertEquals(vsps.size(), 2); } @@ -218,11 +205,11 @@ public class VendorSoftwareProductManagerImplTest { vspsTobeReturned.put(vsp2id, versionInfo2); doReturn(vspsTobeReturned).when(versioningManagerMock).listEntitiesVersionInfo - (VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, USER1, - VersionableEntityAction.Read); + (VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, USER1, + VersionableEntityAction.Read); List vsps = - vendorSoftwareProductManager.listVsps(VersionStatus.Final.name(), USER1); + vendorSoftwareProductManager.listVsps(VersionStatus.Certified.name()); Assert.assertEquals(vsps.size(), 0); } @@ -242,53 +229,36 @@ public class VendorSoftwareProductManagerImplTest { vspsTobeReturned.put(vsp2id, versionInfo2); doReturn(vspsTobeReturned).when(versioningManagerMock).listEntitiesVersionInfo - (VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, USER1, - VersionableEntityAction.Read); + (VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, USER1, + VersionableEntityAction.Read); VspDetails vsp2 = new VspDetails(vsp2id, VERSION10); vsp2.setWritetimeMicroSeconds(8L); doReturn(vsp2).when(vspInfoDaoMock) - .get(any(VspDetails.class)); + .get(any(VspDetails.class)); List vsps = - vendorSoftwareProductManager.listVsps(VersionStatus.Final.name(), USER1); + vendorSoftwareProductManager.listVsps(VersionStatus.Certified.name()); Assert.assertEquals(vsps.size(), 1); - } + }*/ - @Test(expectedExceptions = CoreException.class) - public void testCreateWithExistingName_negative() { - doThrow(new CoreException( - new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).build())) - .when(vendorSoftwareProductManager).validateUniqueName("Vsp1"); - VspDetails expectedVsp = - createVspDetails(null, null, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon", - "category", "subCategory", "123", null); - - vendorSoftwareProductManager.createVsp(expectedVsp, USER1); - } @Test public void testCreate() { - doNothing().when(vendorSoftwareProductManager).validateUniqueName("Vsp1"); - doNothing().when(vendorSoftwareProductManager).createUniqueName("Vsp1"); - doReturn(VERSION01).when(versioningManagerMock).create(anyObject(), anyObject(), anyObject()); + //doReturn(VERSION01).when(versioningManagerMock).create(anyObject(), anyObject(), anyObject()); doReturn("{}") - .when(vendorSoftwareProductManager).getVspQuestionnaireSchema(anyObject()); + .when(vendorSoftwareProductManager).getVspQuestionnaireSchema(anyObject()); VspDetails vspToCreate = - createVspDetails(null, null, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon", - "category", "subCategory", "123", null); + createVspDetails(null, null, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon", + "category", "subCategory", "123", null); - VspDetails vsp = vendorSoftwareProductManager.createVsp(vspToCreate, USER1); + VspDetails vsp = vendorSoftwareProductManager.createVsp(vspToCreate); Assert.assertNotNull(vsp); vspToCreate.setId(vsp.getId()); vspToCreate.setVersion(VERSION01); assertVspsEquals(vsp, vspToCreate); - verify(activityLogManagerMock).addActionLog(activityLogEntityArg.capture(), eq(USER1)); - ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue(); - Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION01.getMajor() + 1)); - Assert.assertTrue(activityLogEntity.isSuccess()); } @Test(expectedExceptions = CoreException.class) @@ -296,23 +266,23 @@ public class VendorSoftwareProductManagerImplTest { VersionInfo versionInfo = new VersionInfo(); versionInfo.setActiveVersion(VERSION01); doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, - VersionableEntityAction.Write); + VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, + VersionableEntityAction.Write); VspDetails existingVsp = - createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-existingVsp", "vendorName", "vlm1Id", - "icon", "category", "subCategory", "123", null); + createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-existingVsp", "vendorName", "vlm1Id", + "icon", "category", "subCategory", "123", null); VspDetails updatedVsp = - createVspDetails(VSP_ID, VERSION01, "Vsp1_updated", "Test-existingVsp", "vendorName", - "vlm1Id", "icon", "category", "subCategory", "123", null); + createVspDetails(VSP_ID, VERSION01, "Vsp1_updated", "Test-existingVsp", "vendorName", + "vlm1Id", "icon", "category", "subCategory", "123", null); doReturn(existingVsp).when(vspInfoDaoMock) - .get(any(VspDetails.class)); + .get(any(VspDetails.class)); doThrow(new CoreException( - new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).build())) - .when(vendorSoftwareProductManager) - .updateUniqueName(existingVsp.getName(), updatedVsp.getName()); + new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).build())) + .when(vendorSoftwareProductManager) + .updateUniqueName(existingVsp.getName(), updatedVsp.getName()); - vendorSoftwareProductManager.updateVsp(updatedVsp, USER1); + vendorSoftwareProductManager.updateVsp(updatedVsp); } @Test @@ -320,23 +290,23 @@ public class VendorSoftwareProductManagerImplTest { VersionInfo versionInfo = new VersionInfo(); versionInfo.setActiveVersion(VERSION01); doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, - VersionableEntityAction.Write); + VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, + VersionableEntityAction.Write); VspDetails existingVsp = - createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon", - "category", - "subCategory", "456", null); + createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon", + "category", + "subCategory", "456", null); VspDetails updatedVsp = - createVspDetails(VSP_ID, VERSION01, "VSP1_updated", null, "vendorName", "vlm1Id", "icon", - "category_updated", - "subCategory", "456", null); + createVspDetails(VSP_ID, VERSION01, "VSP1_updated", null, "vendorName", "vlm1Id", "icon", + "category_updated", + "subCategory", "456", null); existingVsp.setWritetimeMicroSeconds(8L); doReturn(existingVsp).when(vspInfoDaoMock) - .get(any(VspDetails.class)); + .get(any(VspDetails.class)); doNothing().when(vendorSoftwareProductManager) - .updateUniqueName(existingVsp.getName(), updatedVsp.getName()); + .updateUniqueName(existingVsp.getName(), updatedVsp.getName()); - vendorSoftwareProductManager.updateVsp(updatedVsp, USER1); + vendorSoftwareProductManager.updateVsp(updatedVsp); verify(vspInfoDaoMock).update(updatedVsp); } @@ -346,40 +316,41 @@ public class VendorSoftwareProductManagerImplTest { VersionInfo versionInfo = new VersionInfo(); versionInfo.setActiveVersion(VERSION01); doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, - VersionableEntityAction.Write); - List fgs = new ArrayList<>(); - fgs.add("fg1"); fgs.add("fg2"); + VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, + VersionableEntityAction.Write); + List fgs = new ArrayList(); + fgs.add("fg1"); + fgs.add("fg2"); VspDetails existingVsp = - createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon", - "category", - "subCategory", "456", fgs); + createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon", + "category", + "subCategory", "456", fgs); - List updFgs = new ArrayList<>(); - updFgs.add("fg2"); + List updFgs = new ArrayList(); + //updFgs.add("fg2"); VspDetails updatedVsp = - createVspDetails(VSP_ID, VERSION01, "VSP1_updated", null, "vendorName", "vlm1Id", "icon", - "category_updated", - "subCategory", "456", updFgs); + createVspDetails(VSP_ID, VERSION01, "VSP1_updated", null, "vendorName", "vlm1Id", "icon", + "category_updated", + "subCategory", "456", updFgs); existingVsp.setWritetimeMicroSeconds(8L); doReturn(existingVsp).when(vspInfoDaoMock) - .get(any(VspDetails.class)); + .get(any(VspDetails.class)); doNothing().when(vendorSoftwareProductManager) - .updateUniqueName(existingVsp.getName(), updatedVsp.getName()); + .updateUniqueName(existingVsp.getName(), updatedVsp.getName()); - DeploymentFlavorEntity dfEntity = new DeploymentFlavorEntity(VSP_ID,VERSION01,"DF_ID"); + DeploymentFlavorEntity dfEntity = new DeploymentFlavorEntity(VSP_ID, VERSION01, "DF_ID"); DeploymentFlavor flavor = new DeploymentFlavor(); flavor.setFeatureGroupId("fg1"); dfEntity.setDeploymentFlavorCompositionData(flavor); - List dfList = new ArrayList<>(); + List dfList = new ArrayList(); dfList.add(dfEntity); doReturn(dfList).when(deploymentFlavorDaoMock).list(anyObject()); - vendorSoftwareProductManager.updateVsp(updatedVsp, USER1); + vendorSoftwareProductManager.updateVsp(updatedVsp); - verify(vendorSoftwareProductDaoMock).updateDeploymentFlavor(dfEntity); + verify(deploymentFlavorDaoMock).update(dfEntity); Assert.assertNull(dfEntity.getDeploymentFlavorCompositionData().getFeatureGroupId()); @@ -389,7 +360,7 @@ public class VendorSoftwareProductManagerImplTest { public void testGetNonExistingVersion_negative() { Version notExistversion = new Version(43, 8); doReturn(null).when(vspInfoDaoMock).get(any(VspDetails.class)); - vendorSoftwareProductManager.getVsp(VSP_ID, notExistversion, USER1); + vendorSoftwareProductManager.getVsp(VSP_ID, notExistversion); } @Test @@ -399,18 +370,18 @@ public class VendorSoftwareProductManagerImplTest { versionInfo.setStatus(VersionStatus.Locked); versionInfo.setLockingUser(USER1); doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, - VersionableEntityAction.Read); + VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, + VersionableEntityAction.Read); VspDetails existingVsp = - createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon", - "category", - "subCategory", "456", null); + createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon", + "category", + "subCategory", "456", null); existingVsp.setWritetimeMicroSeconds(8L); doReturn(existingVsp).when(vspInfoDaoMock).get(any(VspDetails.class)); VspDetails actualVsp = - vendorSoftwareProductManager.getVsp(VSP_ID, VERSION01, USER1); + vendorSoftwareProductManager.getVsp(VSP_ID, VERSION01); assertVspsEquals(actualVsp, existingVsp); } @@ -423,84 +394,26 @@ public class VendorSoftwareProductManagerImplTest { versionInfo.setStatus(VersionStatus.Locked); versionInfo.setLockingUser(USER2); doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, - VersionableEntityAction.Read); + VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, + VersionableEntityAction.Read); VspDetails existingVsp = - createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon", - "category", - "subCategory", "456", null); + createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon", + "category", + "subCategory", "456", null); existingVsp.setWritetimeMicroSeconds(8L); doReturn(existingVsp) - .when(vspInfoDaoMock).get(any(VspDetails.class)); + .when(vspInfoDaoMock).get(any(VspDetails.class)); VspDetails actualVsp = - vendorSoftwareProductManager.getVsp(VSP_ID, VERSION01, USER1); + vendorSoftwareProductManager.getVsp(VSP_ID, VERSION01); VspDetails expectedVsp = - vspInfoDaoMock - .get(new VspDetails(VSP_ID, VERSION01)); + vspInfoDaoMock + .get(new VspDetails(VSP_ID, VERSION01)); assertVspsEquals(actualVsp, expectedVsp); } - @Test - public void testCheckin() { - doReturn(VERSION01).when(versioningManagerMock) - .checkin(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, - USER1, null); - Version version = vendorSoftwareProductManager.checkin(VSP_ID, USER1); - - Assert.assertEquals(version, VERSION01); - verify(versioningManagerMock) - .checkin(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, - USER1, null); - verify(activityLogManagerMock).addActionLog(activityLogEntityArg.capture(), eq(USER1)); - ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue(); - Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION01.getMajor() + 1)); - Assert.assertTrue(activityLogEntity.isSuccess()); - } - - @Test - public void testCheckout() { - doReturn(VERSION01).when(versioningManagerMock) - .checkout(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, - USER1); - Version version = vendorSoftwareProductManager.checkout(VSP_ID, USER1); - - Assert.assertEquals(version, VERSION01); - verify(versioningManagerMock) - .checkout(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, - USER1); - - verify(activityLogManagerMock).addActionLog(activityLogEntityArg.capture(), eq(USER1)); - ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue(); - Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION01.getMajor() + 1)); - Assert.assertTrue(activityLogEntity.isSuccess()); - } - - - @Test - public void testUndoCheckout() { - Version existingVersion = new Version(0, 2); - VersionInfo versionInfo = new VersionInfo(); - versionInfo.setActiveVersion(existingVersion); - doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, - VSP_ID, USER1, VersionableEntityAction.Read); - - doReturn(VERSION01).when(versioningManagerMock).undoCheckout(VendorSoftwareProductConstants - .VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1); - - VspDetails vsp = new VspDetails(VSP_ID, existingVersion); - vsp.setName("ExistingName"); - doReturn(vsp).when(vspInfoDaoMock).get(anyObject()); - doNothing().when(vendorSoftwareProductManager).updateUniqueName(vsp.getName(), vsp.getName()); - - Version undoCheckoutVersion = vendorSoftwareProductManager.undoCheckout(VSP_ID, USER1); - - Assert.assertEquals(undoCheckoutVersion, VERSION01); - } - /* @Test public void testSubmitWithMissingData() throws IOException { @@ -551,35 +464,33 @@ public class VendorSoftwareProductManagerImplTest { VersionInfo versionInfo = new VersionInfo(); versionInfo.setActiveVersion(VERSION01); doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, - VSP_ID, USER1, VersionableEntityAction.Read); + VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, + VSP_ID, USER1, VersionableEntityAction.Read); VspDetails vsp = - createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon", - "category", "subCategory", "licenseAgreementId", - Collections.singletonList("featureGroupId")); + createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon", + "category", "subCategory", "licenseAgreementId", + Collections.singletonList("featureGroupId")); doReturn(vsp).when(vspInfoDaoMock).get(anyObject()); - UploadDataEntity uploadData = new UploadDataEntity(VSP_ID, VERSION01); + OrchestrationTemplateEntity uploadData = new OrchestrationTemplateEntity(VSP_ID, VERSION01); uploadData.setContentData( - ByteBuffer.wrap(getBytes("/emptyComposition"))); + ByteBuffer.wrap(FileUtils.toByteArray(getFileInputStream("/emptyComposition")))); doReturn(uploadData).when(orchestrationTemplateDataDaoMock) - .getOrchestrationTemplate(anyObject(), anyObject()); + .get(anyObject(), anyObject()); doReturn(new ToscaServiceModel(new FileContentHandler(), new HashMap<>(), - "MainServiceTemplate.yaml")) - .when(serviceModelDaoMock).getServiceModel(VSP_ID, VERSION01); + "MainServiceTemplate.yaml")) + .when(serviceModelDaoMock).getServiceModel(VSP_ID, VERSION01); - ValidationResponse validationResponse = vendorSoftwareProductManager.submit(VSP_ID, USER1); + ValidationResponse validationResponse = + vendorSoftwareProductManager.validate(VSP_ID, VERSION01); Assert.assertNotNull(validationResponse); Assert.assertFalse(validationResponse.isValid()); Assert.assertNull(validationResponse.getVspErrors()); - Assert.assertEquals(validationResponse.getLicensingDataErrors(), 1); + Assert.assertEquals(validationResponse.getLicensingDataErrors().size(), 1); verify(versioningManagerMock, never()) - .submit(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, - USER1, null); - - //TODO - check.. - verify(activityLogManagerMock, never()).addActionLog(any(ActivityLogEntity.class), eq(USER1)); + .submit(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, + USER1, null); } // TODO: 3/15/2017 fix and enable @@ -589,40 +500,32 @@ public class VendorSoftwareProductManagerImplTest { EnrichmentManagerFactory.getInstance(); AbstractFactoryBase - .registerFactory(EnrichmentManagerFactory.class, EnrichmentManagerFactoryImpl.class); + .registerFactory(EnrichmentManagerFactory.class, EnrichmentManagerFactoryImpl.class); VspDetails vsp = - createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon", - "category", "subCategory", "123", Collections.singletonList("fg1")); + createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon", + "category", "subCategory", "123", Collections.singletonList("fg1")); doReturn(vsp).when(vspInfoDaoMock).get(anyObject()); - UploadDataEntity uploadData = new UploadDataEntity(VSP_ID, VERSION01); + OrchestrationTemplateEntity uploadData = new OrchestrationTemplateEntity(VSP_ID, VERSION01); uploadData.setContentData( - ByteBuffer.wrap(getBytes("/emptyComposition"))); + ByteBuffer.wrap(FileUtils.toByteArray(getFileInputStream("/emptyComposition")))); doReturn(uploadData).when(orchestrationTemplateDataDaoMock) - .getOrchestrationTemplate(anyObject(), anyObject()); + .get(anyObject(), anyObject()); doReturn(new ToscaServiceModel(new FileContentHandler(), new HashMap<>(), - "MainServiceTemplate.yaml")) - .when(serviceModelDaoMock).getServiceModel(VSP_ID, VERSION01); + "MainServiceTemplate.yaml")) + .when(serviceModelDaoMock).getServiceModel(VSP_ID, VERSION01); - ValidationResponse validationResponse = vendorSoftwareProductManager.submit(VSP_ID, USER1); + ValidationResponse validationResponse = + vendorSoftwareProductManager.validate(VSP_ID, VERSION01); Assert.assertTrue(validationResponse.isValid()); -/* Assert.assertEquals(vsp2.getVersionInfo().getActiveVersion(), VERSION10); - Assert.assertEquals(vsp2.getVersionInfo().getStatus(), VersionStatus.Final); +/* Assert.assertEquals(vsp2.getVersionInfo().getVersion(), VERSION10); + Assert.assertEquals(vsp2.getVersionInfo().getStatus(), VersionStatus.Certified); Assert.assertNull(vsp2.getVersionInfo().getLockingUser());*/ verify(versioningManagerMock) - .submit(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, - USER1, null); - verify(activityLogManagerMock).addActionLog(activityLogEntityArg.capture(), eq(USER1)); - ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue(); - Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION10.getMajor())); - Assert.assertTrue(activityLogEntity.isSuccess()); - } - - @Test(expectedExceptions = CoreException.class) - public void testCreatePackageOnNonFinalVersion_negative() throws IOException { - vendorSoftwareProductManager.createPackage(VSP_ID, VERSION01, USER1); + .submit(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, + USER1, null); } @Test @@ -632,11 +535,11 @@ public class VendorSoftwareProductManagerImplTest { VersionInfo versionInfo = new VersionInfo(); versionInfo.setActiveVersion(VERSION10); doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, - VersionableEntityAction.Read); + VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, + VersionableEntityAction.Read); doReturn(new ToscaServiceModel(new FileContentHandler(), new HashMap<>(), "")).when - (enrichedServiceModelDaoMock).getServiceModel(VSP_ID, VERSION10); + (enrichedServiceModelDaoMock).getServiceModel(VSP_ID, VERSION10); VspDetails vsp = new VspDetails(VSP_ID, VERSION10); vsp.setVendorId("vendorId"); @@ -645,20 +548,20 @@ public class VendorSoftwareProductManagerImplTest { doReturn(vsp).when(vspInfoDaoMock).get(any(VspDetails.class)); doReturn(new FileContentHandler()).when(licenseArtifactsServiceMock) - .createLicenseArtifacts(VSP_ID, vsp.getVendorId(), VERSION10, vsp.getFeatureGroups(), - USER1); + .createLicenseArtifacts(VSP_ID, vsp.getVendorId(), VERSION10, vsp.getFeatureGroups() + ); - PackageInfo packageInfo = vendorSoftwareProductManager.createPackage(VSP_ID, VERSION10, USER1); + PackageInfo packageInfo = vendorSoftwareProductManager.createPackage(VSP_ID, VERSION10); Assert.assertNotNull(packageInfo.getVspId()); } // TODO: 3/15/2017 fix and enable //@Test(dependsOnMethods = {"testListFinals"}) public void testUploadFileMissingFile() throws IOException { + try (InputStream zis = getFileInputStream("/vspmanager/zips/missingYml.zip")) { - try (InputStream zis = this.getClass().getResourceAsStream("/vspmanager/zips/missingYml.zip")) { UploadFileResponse uploadFileResponse = - candidateManager.upload(VSP_ID, VERSION01, zis, USER1, "zip", "missingYml"); + candidateManager.upload(VSP_ID, VERSION01, zis, "zip", "file"); Assert.assertEquals(uploadFileResponse.getErrors().size(), 0); } @@ -667,38 +570,130 @@ public class VendorSoftwareProductManagerImplTest { // TODO: 3/15/2017 fix and enable //@Test(dependsOnMethods = {"testUploadFileMissingFile"}) public void testUploadNotZipFile() throws IOException { - URL url = this.getClass().getResource("/notZipFile"); - try (InputStream inputStream = url.openStream()) { - candidateManager - .upload(VSP_ID, VERSION01, - inputStream, USER1, "zip", "notZipFile"); - candidateManager.process(VSP_ID, VERSION01, USER1); + try { + candidateManager.upload(VSP_ID, VERSION01, url.openStream(), "zip", "file"); + candidateManager.process(VSP_ID, VERSION01); } catch (Exception ce) { Assert.assertEquals(ce.getMessage(), Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()); } + } +/* + @Test + public void testEnrichModelInSubmit() { + UniqueValueUtil + .deleteUniqueValue(VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME, + "VSP_syb"); + VspDetails vspDetails = vendorSoftwareProductManager.createVsp( + createVspDetails(null, null, "VSP_syb", "Test-vsp_syb", "vendorName", "vlm1Id", "icon", + "category", "subCategory", "456", null), USER1); + String id = vspDetails.getId(); + + //upload file + InputStream zis = getFileInputStream("/vspmanager/zips/fullComposition.zip"); + candidateManager.upload(id, VERSION01, zis, USER1); + OrchestrationTemplateActionResponse uploadFileResponse = + candidateManager.process(id, VERSION01, USER1); + + //check in + vendorSoftwareProductManager.checkin(id, USER1); + //submit + try { + ValidationResponse result = vendorSoftwareProductManager.submit(id, USER1); + } catch (IOException exception) { + Assert.fail(); + } + VersionedVendorSoftwareProductInfo details = + vendorSoftwareProductManager.getVsp(id, null, USER1); + Collection components =vendorSoftwareProductManager + .listComponents(id, details.getVersionInfo().getVersion(), USER1); + + ToscaServiceModel model = + (ToscaServiceModel) EnrichedServiceModelDaoFactory.getInstance().createInterface() + .getServiceModel(id, details.getVersionInfo().getVersion()); + + Map capabilities = new HashMap<>(); + for (ComponentEntity component : components) { + model.getServiceTemplates(). + entrySet(). + stream(). + filter(entryValue -> entryValue.getValue() != null && + entryValue.getValue().getNode_types() != null && + entryValue.getValue(). + getNode_types(). + containsKey(component.getComponentCompositionData().getName())). + forEach(entryValue -> entryValue.getValue().getNode_types(). + values(). + stream(). + filter(type -> MapUtils.isNotEmpty(type.getCapabilities())). + forEach(type -> type.getCapabilities(). + entrySet(). + forEach(entry -> addCapability(entryValue.getKey(), capabilities, entry.getKey(), + entry.getValue())))); + + } + + Assert.assertNotNull(capabilities); + } + + @Test(dependsOnMethods = {"testCreatePackage"}) + public void testEnrichedFilesDeletedOnNewUpload() throws IOException { + Version activeVersion; + + createPackageFromUpload(VSP_ID, USER1, "/fullComposition"); + activeVersion = vendorSoftwareProductManager.getVsp(VSP_ID, null, USER1).getVersionInfo() + .getVersion(); + + List firstExternalArtifacts = enrichedServiceModelDaoMock + .getExternalArtifacts(VSP_ID, activeVersion); + ToscaServiceModel firstServiceModel = enrichedServiceModelDaoMock.getServiceModel(VSP_ID, + activeVersion); + + createPackageFromUpload(VSP_ID, USER1, "/emptyComposition"); + activeVersion = vendorSoftwareProductManager.getVsp(VSP_ID, null, USER1).getVersionInfo() + .getVersion(); + + List secondExternalArtifacts = enrichedServiceModelDaoMock + .getExternalArtifacts(VSP_ID, activeVersion); + ToscaServiceModel secondServiceModel = enrichedServiceModelDaoMock.getServiceModel(VSP_ID, + activeVersion); + + Assert.assertNotEquals(firstExternalArtifacts, secondExternalArtifacts); + Assert.assertNotEquals(firstServiceModel, secondServiceModel); - verify(activityLogManagerMock, never()).addActionLog(any(ActivityLogEntity.class), eq(USER1)); } + @Test(dependsOnMethods = {"testMibsDeletedInCsar"}) + public void testServiceTemplatesAreDeletedInCsarOnNewUpload() throws IOException { + String nestedPath = "Definitions" + File.separator + "nested"; + + uploadFileAndProcess(VSP_ID, USER1, "/vspmanager/zips/fullCompositionNested.zip"); + checkinSubmitCreatePackage(VSP_ID, USER1); + List nestedFileNamesServiceTemplates = + getWantedFileNamesFromCsar(nestedPath); + + uploadFileAndProcess(VSP_ID, USER1, "/vspmanager/zips/fullComposition.zip"); + checkinSubmitCreatePackage(VSP_ID, USER1); + List emptyNestedNamesList = getWantedFileNamesFromCsar(nestedPath); + + Assert.assertEquals(emptyNestedNamesList.size(), 0); + Assert.assertNotEquals(emptyNestedNamesList.size(), nestedFileNamesServiceTemplates.size()); + }*/ private List getWantedFileNamesFromCsar(String pathInCsar) - throws IOException { - File translatedFile = vendorSoftwareProductManager.getTranslatedFile(VSP_ID, VERSION10, USER1); + throws IOException { + File translatedFile = vendorSoftwareProductManager.getTranslatedFile(VSP_ID, VERSION10); return getFileNamesFromFolderInCsar(translatedFile, - pathInCsar); + pathInCsar); } private List getFileNamesFromFolderInCsar(File csar, String folderName) - throws IOException { - + throws IOException { List fileNames = new ArrayList<>(); - try (FileInputStream fileInputStream = new FileInputStream(csar); - ZipInputStream zip = new ZipInputStream(fileInputStream)) { - + try (ZipInputStream zip = new ZipInputStream(new FileInputStream(csar))) { ZipEntry ze; while ((ze = zip.getNextEntry()) != null) { @@ -711,28 +706,26 @@ public class VendorSoftwareProductManagerImplTest { return fileNames; } - - private void createPackageFromUpload(String vspId, String user, String filePath) - throws IOException { - uploadFileAndProcess(vspId, user, filePath); - checkinSubmitCreatePackage(vspId, user); - } - - private void uploadFileAndProcess(String vspId, String user, String filePath) throws IOException { - vendorSoftwareProductManager.checkout(vspId, user); - - try (InputStream inputStream = this.getClass().getResourceAsStream(filePath)) { - candidateManager.upload(vspId, VERSION01, inputStream, user, "zip", "file"); - candidateManager.process(vspId, VERSION01, user); - } - } - - private void checkinSubmitCreatePackage(String vspId, String user) throws IOException { - vendorSoftwareProductManager.checkin(vspId, user); - ValidationResponse submitResponse = vendorSoftwareProductManager.submit(vspId, user); - Assert.assertTrue(submitResponse.isValid()); - vendorSoftwareProductManager.createPackage(vspId, VERSION10, user); - } + /* + //Disabled for sonar null pointer issue for componentEntities + private Pair uploadMib(String vspId, String user, String filePath, + String fileName) { + List componentEntities = null; + //(List) vendorSoftwareProductManager.listComponents(vspId, null, user); + monitoringUploadsManager.upload(getFileInputStream(filePath), + fileName, vspId, +<<<<<<< HEAD + VERSION01, componentEntities.get(0).getId(), ArtifactType.SNMP_POLL); + //TODO: add validate of logActivity() func call +======= + VERSION01, componentEntities.get(0).getId(), MonitoringUploadType.SNMP_POLL, user); + //TODO: add validate of addActionLog() func call +>>>>>>> feature/Amdocs-ASDC-1710 + + return new ImmutablePair<>(componentEntities.get(0).getId(), + componentEntities.get(0).getComponentCompositionData() + .getDisplayName()); + }*/ // TODO: 3/15/2017 fix and enable /* @@ -781,11 +774,11 @@ public class VendorSoftwareProductManagerImplTest { */ private void testLegalUpload(String vspId, Version version, InputStream upload, String user) { - candidateManager.upload(vspId, VERSION01, upload, USER1, "zip", "file"); - candidateManager.process(vspId, VERSION01, user); + candidateManager.upload(vspId, VERSION01, upload, "zip", "file"); + candidateManager.process(vspId, VERSION01); - UploadDataEntity uploadData = - orchestrationTemplateDataDaoMock.getOrchestrationTemplate(vspId, version); + OrchestrationTemplateEntity uploadData = + orchestrationTemplateDataDaoMock.get(vspId, version); Assert.assertNotNull(uploadData); } @@ -795,20 +788,40 @@ public class VendorSoftwareProductManagerImplTest { capabilities.put(entryValueKey + "_" + key, value); } - private byte[] getBytes(String fileName) throws IOException { + public InputStream getFileInputStream(String fileName) { URL url = this.getClass().getResource(fileName); - try (InputStream inputStream = url.openStream()) { - return FileUtils.toByteArray(inputStream); + try { + return url.openStream(); + } catch (IOException exception) { + exception.printStackTrace(); + return null; } } - private void assertVSPInWantedLocationInVSPList(String vspId, int location, String user) { +/* private void assertVSPInWantedLocationInVSPList(String vspId, int location, String user) { List vspList = - vendorSoftwareProductManager.listVsps(null, user); + vendorSoftwareProductManager.listVsps(null); Assert.assertEquals(vspList.get(location).getVspDetails().getId(), vspId); - } - - + }*/ + + + // private void assertInfoArtifactIsInRightPathInCsar(String vspId, String zipFileName) +// throws IOException { +// ZipInputStream inputZipStream = new ZipInputStream(new FileInputStream(new File(zipFileName))); +// boolean isInfoArtifactInZip = false; +// +// ZipEntry zipEntry; +// while ((zipEntry = inputZipStream.getNextEntry()) != null) { +// String currentEntryName = zipEntry.getName(); +// if(currentEntryName.equals("Artifacts\\Informative\\Guide\\VSP_" + +// vspId + "_Information.txt")){ +// isInfoArtifactInZip = true; +// break; +// } +// } +// +// Assert.assertTrue(isInfoArtifactInZip); +// } static VspDetails createVspDetails(String id, Version version, String name, String desc, String vendorName, String vlm, String icon, String category, String subCategory, @@ -842,30 +855,68 @@ public class VendorSoftwareProductManagerImplTest { Assert.assertEquals(actual.getFeatureGroups(), expected.getFeatureGroups()); } - // todo ********************** move to common ************************************** + +// @Test +// public void testDownloadFile() throws IOException { +// VspDetails expectedVsp = VSPCommon.createVspDetails(null, null, String.format("VSP-test-%s", vlm1Id), "Test-vsp", "vendorName", "vlm1Id", "icon", "category", "subCategory", "123", null); +// VspDetails createdVsp = vendorSoftwareProductManager.createVsp(expectedVsp, USER1); +// +// id005 = createdVsp.getId(); +// Assert.assertNotNull(id005); +// Assert.assertNotNull(createdVsp.getVersion()); +// +// try (InputStream zipInputStream = new ZipFileUtils().getZipInputStream("/legalUploadWithWarning")) { +// +// UploadFileResponse uploadFileResponse = vendorSoftwareProductManager.upload(id005, zipInputStream, USER1); +// vendorSoftwareProductManager.process(id005, USER1); +// Optional fileCandidate = vendorSoftwareProductManager.get(id005, USER1); +// +// File latestHeatPackage = fileCandidate.get(); +// +// zipInputStream.reset(); +// byte[] uploaded = IOUtils.toByteArray(zipInputStream); +// +// Optional zipContentMap = vendorSoftwareProductManager.getZipContentMap(uploadFileResponse, uploaded); +// FileContentHandler fileContentHandler = new FileContentHandler(); +// if(zipContentMap.isPresent()){ +// fileContentHandler = zipContentMap.get(); +// } +// +// uploaded = IOUtils.toByteArray(fileContentHandler.getFiles().values()); +// +// byte[] downloaded; +// try (BufferedInputStream fileStream = new BufferedInputStream(new FileInputStream(latestHeatPackage))) { +// downloaded = IOUtils.toByteArray(fileStream); +// } +// +// Assert.assertTrue(Arrays.equals(uploaded, downloaded)); +// } +// } + + // todo ********************** move to common ************************************** private void mockVersioning(VersionableEntityAction action) { VersionInfo versionInfo = new VersionInfo(); versionInfo.setActiveVersion(VERSION01); doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, - action); + VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, + action); } private void mockVersioningEntityNotExist(VersionableEntityAction action, String vspId) { doThrow(new CoreException(new EntityNotExistErrorBuilder( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, vspId).build())) - .when(versioningManagerMock).getEntityVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, vspId, USER1, - action); + VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, vspId).build())) + .when(versioningManagerMock).getEntityVersionInfo( + VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, vspId, USER1, + action); } private void MockVersioningEntityLocked(VersionableEntityAction action) { doThrow(new CoreException(new EditOnEntityLockedByOtherErrorBuilder( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1) - .build())) - .when(versioningManagerMock).getEntityVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER2, - action); + VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1) + .build())) + .when(versioningManagerMock).getEntityVersionInfo( + VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER2, + action); } } \ No newline at end of file diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/mock/VendorSoftwareProductDaoFactoryMock.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/mock/VendorSoftwareProductDaoFactoryMock.java deleted file mode 100644 index ede8620cf9..0000000000 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/mock/VendorSoftwareProductDaoFactoryMock.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.openecomp.sdc.vendorsoftwareproduct.impl.mock; - -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; - -public class VendorSoftwareProductDaoFactoryMock extends VendorSoftwareProductDaoFactory { - - @Override - public VendorSoftwareProductDao createInterface() { - return null; - } -} diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/CandidateServiceImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/CandidateServiceImplTest.java index 3d98ab76c6..1c9d61b51b 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/CandidateServiceImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/CandidateServiceImplTest.java @@ -30,7 +30,6 @@ import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; import org.openecomp.sdc.heat.datatypes.structure.HeatStructureTree; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.ManifestCreator; import org.openecomp.sdc.vendorsoftwareproduct.services.impl.filedatastructuremodule.CandidateServiceImpl; @@ -57,8 +56,6 @@ import static org.testng.Assert.assertTrue; public class CandidateServiceImplTest { @Mock private ManifestCreator manifestCreatorMock; - @Mock - private VendorSoftwareProductDao vendorSoftwareProductDaoMock; @InjectMocks private CandidateServiceImpl candidateService; @@ -95,7 +92,8 @@ public class CandidateServiceImplTest { //vspDetails.setOnboardingMethod(VSPCommon.OnboardingMethod.HEAT.name()); vspDetails.setOnboardingMethod("HEAT"); - FilesDataStructure structure = JsonUtil.json2Object(getExpectedJson(), FilesDataStructure.class); + FilesDataStructure structure = + JsonUtil.json2Object(getExpectedJson(), FilesDataStructure.class); Optional expectedManifest = getExpectedManifestJson(); doReturn(expectedManifest) @@ -191,7 +189,8 @@ public class CandidateServiceImplTest { fileData = createFileData("file1.yaml", true, FileData.Type.HEAT, null); mockFileData.add(fileData); fileData = createFileData("file1_vol.yaml", null, FileData.Type.HEAT_VOL, fileData); - fileData = createFileData("file1.env", null, FileData.Type.HEAT_ENV, mockFileData.get(1).getData().get(0)); + fileData = createFileData("file1.env", null, FileData.Type.HEAT_ENV, + mockFileData.get(1).getData().get(0)); mockFileData.add(createFileData("file2.sh", null, FileData.Type.OTHER, null)); mockFileData.add(createFileData("file3.yml", null, FileData.Type.OTHER, null)); mock.setData(mockFileData); @@ -202,7 +201,7 @@ public class CandidateServiceImplTest { FileData fileDataToAddTo) { FileData fileData = new FileData(); fileData.setFile(fileName); - if(isBase != null) { + if (isBase != null) { fileData.setBase(isBase); } fileData.setType(fileType); @@ -211,11 +210,9 @@ public class CandidateServiceImplTest { } private void addFileDataToList(FileData fileDataToAddTo, FileData fileData) { - if(fileDataToAddTo != null) - { + if (fileDataToAddTo != null) { List list = fileDataToAddTo.getData(); - if(CollectionUtils.isEmpty(list)) - { + if (CollectionUtils.isEmpty(list)) { list = new ArrayList<>(); } list.add(fileData); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionDataExtractorImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionDataExtractorImplTest.java index 2f85f30dc5..9385d4a10c 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionDataExtractorImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionDataExtractorImplTest.java @@ -27,8 +27,8 @@ import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; +import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Component; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionData; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Network; @@ -110,11 +110,12 @@ public class CompositionDataExtractorImplTest { try (InputStream yamlFile = new FileInputStream(file)) { ServiceTemplate serviceTemplateFromYaml = toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); - serviceTemplates.put(ToscaUtil.getServiceTemplateFileName(serviceTemplateFromYaml), serviceTemplateFromYaml); + serviceTemplates.put(ToscaUtil.getServiceTemplateFileName(serviceTemplateFromYaml), + serviceTemplateFromYaml); try { yamlFile.close(); } catch (IOException ignore) { - log.debug("",ignore); + log.debug("", ignore); } } catch (FileNotFoundException exception) { throw exception; diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionEntityDataManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionEntityDataManagerImplTest.java index 1acd58d157..0d9245d779 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionEntityDataManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionEntityDataManagerImplTest.java @@ -22,12 +22,10 @@ package org.openecomp.sdc.vendorsoftwareproduct.services.impl.composition; import org.apache.commons.collections.CollectionUtils; import org.mockito.InjectMocks; -import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; @@ -43,6 +41,7 @@ import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; @@ -90,8 +89,6 @@ public class CompositionEntityDataManagerImplTest { "}"; private Map> errorsById; - @Mock - private VendorSoftwareProductDao vendorSoftwareProductDaoMock; @InjectMocks @Spy private CompositionEntityDataManagerImpl compositionEntityDataManager; @@ -248,7 +245,7 @@ public class CompositionEntityDataManagerImplTest { Map> errorsById = compositionEntityDataManager.validateEntitiesQuestionnaire(); - Assert.assertEquals(errorsById.size(), 0); + Assert.assertEquals(errorsById.size(), 1); } @Test(dependsOnMethods = "testNicAndComponentValidQuestionnaire") @@ -259,9 +256,9 @@ public class CompositionEntityDataManagerImplTest { Map> errorsById = compositionEntityDataManager.validateEntitiesQuestionnaire(); - Assert.assertEquals(errorsById.size(), 1); + Assert.assertEquals(errorsById.size(), 2); - CompositionEntityId component = errorsById.keySet().iterator().next(); + CompositionEntityId component = new ArrayList<>(errorsById.keySet()).get(1); List errors = (List) errorsById.get(component); Assert.assertEquals(errors.size(), 1); Assert.assertEquals(errors.get(0), diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/schemagenerator/SchemaGeneratorTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/schemagenerator/SchemaGeneratorTest.java index acd76a151b..237e9cce8f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/schemagenerator/SchemaGeneratorTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/services/schemagenerator/SchemaGeneratorTest.java @@ -20,27 +20,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.services.schemagenerator; -import org.everit.json.schema.EmptySchema; -import org.everit.json.schema.loader.SchemaLoader; -import org.json.JSONObject; -import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.vendorsoftwareproduct.services.schemagenerator.SchemaGenerator; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentData; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityType; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Network; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.NetworkType; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Nic; -import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.ComponentCompositionSchemaInput; -import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.ComponentQuestionnaireSchemaInput; -import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.NetworkCompositionSchemaInput; -import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.NicCompositionSchemaInput; -import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateContext; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.Arrays; -import java.util.Map; - public class SchemaGeneratorTest { /* diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/tree/UploadFileTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/tree/UploadFileTest.java index df386b12cd..2a475fe895 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/tree/UploadFileTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/tree/UploadFileTest.java @@ -21,9 +21,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.tree; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doReturn; - import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -32,13 +29,10 @@ import org.openecomp.core.model.dao.ServiceModelDao; import org.openecomp.core.model.types.ServiceElement; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.sdc.healing.api.HealingManager; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.impl.OrchestrationTemplateCandidateManagerImpl; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor; @@ -50,7 +44,11 @@ import org.openecomp.sdc.versioning.dao.types.Version; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.io.*; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; import java.net.URL; import java.util.zip.ZipOutputStream; @@ -59,70 +57,69 @@ import static org.mockito.Mockito.doReturn; import static org.testng.Assert.assertEquals; public class UploadFileTest { - private static final String USER1 = "vspTestUser1"; - - public static final Version VERSION01 = new Version(0, 1); - @Mock - private VendorSoftwareProductDao vendorSoftwareProductDaoMock; - @Mock - private OrchestrationTemplateDao orchestrationTemplateDataDaoMock; - @Spy - private CandidateServiceImpl candidateService; - @Mock - private HealingManager healingManagerMock; - @Mock - private CompositionDataExtractor compositionDataExtractorMock; - @Mock - private ServiceModelDao serviceModelDaoMock; - @Mock - private CompositionEntityDataManager compositionEntityDataManagerMock; - @Mock - private VendorSoftwareProductInfoDao vspInfoDaoMock; - - @InjectMocks - private OrchestrationTemplateCandidateManagerImpl candidateManager; - - private static String vlm1Id; - public static String id001 = null; - public static String id002 = null; - - public static Version activeVersion002 = null; - - - @BeforeMethod - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testUploadFile() { - VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); - doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); - candidateManager.upload(id001, activeVersion002, getZipInputStream("/legalUpload"), USER1, OnboardingTypesEnum.ZIP.toString(), "legalUpload"); - } - - - private void testLegalUpload(String vspId, Version version, InputStream upload, String user) { - UploadFileResponse uploadFileResponse = candidateManager.upload(vspId, activeVersion002, - upload, user, OnboardingTypesEnum.ZIP.toString(),"file" ); - assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.ZIP); - UploadDataEntity uploadData = - orchestrationTemplateDataDaoMock.getOrchestrationTemplate(vspId, version); - - } - - public InputStream getZipInputStream(String name) { - URL url = this.getClass().getResource(name); - File templateDir = new File(url.getFile()); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try (ZipOutputStream zos = new ZipOutputStream(baos)) { - VSPCommon.zipDir(templateDir, "", zos, true); - } catch (IOException e) { - e.printStackTrace(); - } - return new ByteArrayInputStream(baos.toByteArray()); + private static final String USER1 = "vspTestUser1"; + + public static final Version VERSION01 = new Version(0, 1); + + @Mock + private OrchestrationTemplateDao orchestrationTemplateDataDaoMock; + @Spy + private CandidateServiceImpl candidateService; + @Mock + private HealingManager healingManagerMock; + @Mock + private CompositionDataExtractor compositionDataExtractorMock; + @Mock + private ServiceModelDao serviceModelDaoMock; + @Mock + private CompositionEntityDataManager compositionEntityDataManagerMock; + @Mock + private VendorSoftwareProductInfoDao vspInfoDaoMock; + + @InjectMocks + private OrchestrationTemplateCandidateManagerImpl candidateManager; + + private static String vlm1Id; + public static String id001 = null; + public static String id002 = null; + + public static Version activeVersion002 = null; + + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testUploadFile() { + VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); + doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); + candidateManager.upload(id001, activeVersion002, getZipInputStream("/legalUpload"), + OnboardingTypesEnum.ZIP.toString(), "legalUpload"); + } + + + private void testLegalUpload(String vspId, Version version, InputStream upload, String user) { + UploadFileResponse uploadFileResponse = candidateManager.upload(vspId, activeVersion002, + upload, OnboardingTypesEnum.ZIP.toString(), "file"); + assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.ZIP); + OrchestrationTemplateEntity uploadData = orchestrationTemplateDataDaoMock.get(vspId, version); + + } + + public InputStream getZipInputStream(String name) { + URL url = this.getClass().getResource(name); + File templateDir = new File(url.getFile()); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ZipOutputStream zos = new ZipOutputStream(baos)) { + VSPCommon.zipDir(templateDir, "", zos, true); + } catch (IOException e) { + e.printStackTrace(); } + return new ByteArrayInputStream(baos.toByteArray()); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/upload/HeatCleanup/HeatCleanupOnNewUploadTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/upload/HeatCleanup/HeatCleanupOnNewUploadTest.java index 4d925c00cd..13f3859c0c 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/upload/HeatCleanup/HeatCleanupOnNewUploadTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/upload/HeatCleanup/HeatCleanupOnNewUploadTest.java @@ -38,7 +38,7 @@ public class HeatCleanupOnNewUploadTest {/* UploadDataEntity uploadDataEntity = vendorSoftwareProductDao.getUploadData(new UploadDataEntity(vspId, vspActiveVersion)); Assert.assertTrue((uploadDataEntity.getContentData() != null) == exist); - Assert.assertTrue((uploadDataEntity.getValidationData() != null) == exist); + Assert.assertTrue((uploadDataEntity.getInfo() != null) == exist); Assert.assertTrue((uploadDataEntity.getPackageName() != null) == exist); Assert.assertTrue((uploadDataEntity.getPackageVersion() != null) == exist); //TODO: talio - delete enrich data on new upload diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/upload/csar/ManifestParsingTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/upload/csar/ManifestParsingTest.java index 3332e81e36..ee451e0a3c 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/upload/csar/ManifestParsingTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/upload/csar/ManifestParsingTest.java @@ -7,52 +7,55 @@ import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.Onboardin import java.io.IOException; import java.io.InputStream; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class ManifestParsingTest { - @Test - public void testSuccessfulParsing() throws IOException { - try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/manifest/ValidTosca.mf")) { - OnboardingManifest onboardingManifest = new OnboardingManifest(is); - assertTrue(onboardingManifest.isValid()); - assertEquals(onboardingManifest.getMetadata().size(), 4); - assertEquals(onboardingManifest.getSources().size(), 5); - } + @Test + public void testSuccessfulParsing() throws IOException { + try (InputStream is = getClass() + .getResourceAsStream("/vspmanager.csar/manifest/ValidTosca.mf")) { + OnboardingManifest onboardingManifest = new OnboardingManifest(is); + assertTrue(onboardingManifest.isValid()); + assertEquals(onboardingManifest.getMetadata().size(), 4); + assertEquals(onboardingManifest.getSources().size(), 5); } - - @Test - public void testNoMetadataParsing() throws IOException { - try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/manifest/InvalidTosca1.mf")) { - OnboardingManifest onboardingManifest = new OnboardingManifest(is); - assertFalse(onboardingManifest.isValid()); - assertTrue(onboardingManifest.getErrors().stream(). - filter(error -> error.contains(Messages.MANIFEST_INVALID_LINE.getErrorMessage().substring(0, 10))) - .findAny().isPresent()); - } + } + + @Test + public void testNoMetadataParsing() throws IOException { + try (InputStream is = getClass() + .getResourceAsStream("/vspmanager.csar/manifest/InvalidTosca1.mf")) { + OnboardingManifest onboardingManifest = new OnboardingManifest(is); + assertFalse(onboardingManifest.isValid()); + assertTrue(onboardingManifest.getErrors().stream().anyMatch(error -> error + .contains(Messages.MANIFEST_INVALID_LINE.getErrorMessage().substring(0, 10)))); } - - @Test - public void testBrokenMDParsing() throws IOException { - try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/manifest/InvalidTosca2.mf")) { - OnboardingManifest onboardingManifest = new OnboardingManifest(is); - assertFalse(onboardingManifest.isValid()); - assertTrue(onboardingManifest.getErrors().stream(). - filter(error -> error.contains(Messages.MANIFEST_INVALID_LINE.getErrorMessage().substring(0, 10))) - .findAny().isPresent()); - } + } + + @Test + public void testBrokenMDParsing() throws IOException { + try (InputStream is = getClass() + .getResourceAsStream("/vspmanager.csar/manifest/InvalidTosca2.mf")) { + OnboardingManifest onboardingManifest = new OnboardingManifest(is); + assertFalse(onboardingManifest.isValid()); + assertTrue(onboardingManifest.getErrors().stream().anyMatch(error -> error + .contains(Messages.MANIFEST_INVALID_LINE.getErrorMessage().substring(0, 10)))); } - - @Test - public void testNoMetaParsing() throws IOException { - try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/manifest/InvalidTosca4.mf")) { - OnboardingManifest onboardingManifest = new OnboardingManifest(is); - assertFalse(onboardingManifest.isValid()); - assertTrue(onboardingManifest.getErrors().stream(). - filter(error -> error.contains(Messages.MANIFEST_NO_METADATA.getErrorMessage().substring(0, 10))) - .findAny().isPresent()); - } + } + + @Test + public void testNoMetaParsing() throws IOException { + try (InputStream is = getClass() + .getResourceAsStream("/vspmanager.csar/manifest/InvalidTosca4.mf")) { + OnboardingManifest onboardingManifest = new OnboardingManifest(is); + assertFalse(onboardingManifest.isValid()); + assertTrue(onboardingManifest.getErrors().stream().anyMatch(error -> error + .contains(Messages.MANIFEST_NO_METADATA.getErrorMessage().substring(0, 10)))); } + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/upload/csar/UploadCSARFileTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/upload/csar/UploadCSARFileTest.java index a7fc0e1ba0..d574c9ee74 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/upload/csar/UploadCSARFileTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/upload/csar/UploadCSARFileTest.java @@ -33,7 +33,6 @@ import org.openecomp.sdc.healing.api.HealingManager; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.impl.OrchestrationTemplateCandidateManagerImpl; @@ -51,171 +50,163 @@ import java.io.InputStream; import java.util.List; import java.util.function.Predicate; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; public class UploadCSARFileTest { - private static final String USER1 = "vspTestUser1"; - - public static final Version VERSION01 = new Version(0, 1); - - @Mock - private VendorSoftwareProductDao vendorSoftwareProductDaoMock; - @Mock - private OrchestrationTemplateDao orchestrationTemplateDataDaoMock; - - @Spy - private CandidateServiceImpl candidateService; - @Mock - private HealingManager healingManagerMock; - @Mock - private CompositionDataExtractor compositionDataExtractorMock; - @Mock - private ServiceModelDao serviceModelDaoMock; - @Mock - private CompositionEntityDataManager compositionEntityDataManagerMock; - @Mock - private VendorSoftwareProductInfoDao vspInfoDaoMock; - @Mock - private OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDao; - @Mock - private ManifestCreatorNamingConventionImpl manifestCreator; - - private OrchestrationTemplateCandidateManagerImpl candidateManager; - - - public static String id001 = null; - - public static Version activeVersion002 = null; - - - @BeforeMethod - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - candidateService = new CandidateServiceImpl(manifestCreator,orchestrationTemplateCandidateDao); - candidateManager = new OrchestrationTemplateCandidateManagerImpl( vendorSoftwareProductDaoMock, - vspInfoDaoMock, - orchestrationTemplateDataDaoMock, - candidateService, healingManagerMock, - compositionDataExtractorMock, - serviceModelDaoMock, - compositionEntityDataManagerMock, - null, - null, - null, - null, - null); - } - - @Test - public void testSuccessfulUploadFile() throws Exception { - VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); - doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); - - try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/SDCmock.csar")) { - UploadFileResponse uploadFileResponse = candidateManager.upload(id001, activeVersion002, is, USER1, "csar", "SDCmock"); - assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); - assertEquals(0, uploadFileResponse.getErrors().size()); - assertTrue(uploadFileResponse.getErrors().isEmpty()); - } - } - - @Test - public void testFail1UploadFile() throws Exception { - VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); - doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); - - try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/SDCmockFail1.csar")) { - UploadFileResponse uploadFileResponse = candidateManager.upload(id001, activeVersion002, is, USER1, - "csar", "SDCmockFail1"); - assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); - assertEquals(1, uploadFileResponse.getErrors().size()); - assertTrue( uploadFileResponse.getErrors().values().stream() - .filter(getListPredicate(Messages.CSAR_FILES_NOT_ALLOWED - .getErrorMessage().substring(0, 7))).findAny().isPresent()); - } - } - private Predicate> getListPredicate(String substring) { - return error -> isEquals(substring, error); + public static final Version VERSION01 = new Version("0.1"); + + @Mock + private OrchestrationTemplateDao orchestrationTemplateDataDaoMock; + @Spy + private CandidateServiceImpl candidateService; + @Mock + private HealingManager healingManagerMock; + @Mock + private CompositionDataExtractor compositionDataExtractorMock; + @Mock + private ServiceModelDao serviceModelDaoMock; + @Mock + private CompositionEntityDataManager compositionEntityDataManagerMock; + @Mock + private VendorSoftwareProductInfoDao vspInfoDaoMock; + @Mock + private OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDao; + @Mock + private ManifestCreatorNamingConventionImpl manifestCreator; + + private OrchestrationTemplateCandidateManagerImpl candidateManager; + + + public static String id001 = null; + + public static Version activeVersion002 = null; + + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + candidateService = new CandidateServiceImpl(manifestCreator, orchestrationTemplateCandidateDao); + candidateManager = new OrchestrationTemplateCandidateManagerImpl(vspInfoDaoMock, + candidateService, healingManagerMock); + } + + @Test + public void testSuccessfulUploadFile() throws Exception { + VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); + doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); + + try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/SDCmock.csar")) { + UploadFileResponse uploadFileResponse = + candidateManager.upload(id001, activeVersion002, is, "csar", "SDCmock"); + assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); + assertEquals(0, uploadFileResponse.getErrors().size()); + assertTrue(uploadFileResponse.getErrors().isEmpty()); } - - private boolean isEquals(String substring, List error) { - return error.iterator().next().getMessage().contains(substring); + } + + @Test + public void testFail1UploadFile() throws Exception { + VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); + doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); + + try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/SDCmockFail1.csar")) { + UploadFileResponse uploadFileResponse = + candidateManager.upload(id001, activeVersion002, is, + "csar", "SDCmockFail1"); + assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); + assertEquals(1, uploadFileResponse.getErrors().size()); + assertTrue(uploadFileResponse.getErrors().values().stream().anyMatch( + getListPredicate(Messages.CSAR_FILES_NOT_ALLOWED.getErrorMessage().substring(0, 7)))); } - - @Test - public void testFail2UploadFile() throws Exception { - VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); - doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); - - try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/SDCmockFail2.csar")) { - UploadFileResponse uploadFileResponse = candidateManager.upload(id001, activeVersion002, is, USER1, - "csar", "SDCmockFail2"); - assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); - assertEquals(1, uploadFileResponse.getErrors().size()); - assertTrue( uploadFileResponse.getErrors().values().stream() - .filter(getListPredicate(Messages.CSAR_FILE_NOT_FOUND - .getErrorMessage().substring(0,7))).findAny().isPresent()); - } + } + + private Predicate> getListPredicate(String substring) { + return error -> isEquals(substring, error); + } + + private boolean isEquals(String substring, List error) { + return error.iterator().next().getMessage().contains(substring); + } + + @Test + public void testFail2UploadFile() throws Exception { + VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); + doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); + + try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/SDCmockFail2.csar")) { + UploadFileResponse uploadFileResponse = + candidateManager.upload(id001, activeVersion002, is, + "csar", "SDCmockFail2"); + assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); + assertEquals(1, uploadFileResponse.getErrors().size()); + assertTrue(uploadFileResponse.getErrors().values().stream().anyMatch( + getListPredicate(Messages.CSAR_FILE_NOT_FOUND.getErrorMessage().substring(0, 7)))); } - @Test - public void testFail3UploadFile() throws Exception { - VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); - doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); - - try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/SDCmockFail3.csar")) { - UploadFileResponse uploadFileResponse = candidateManager.upload(id001, activeVersion002, is, USER1, - "csar", "SDCmockFail3"); - assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); - assertEquals(1, uploadFileResponse.getErrors().size()); - } + } + + @Test + public void testFail3UploadFile() throws Exception { + VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); + doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); + + try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/SDCmockFail3.csar")) { + UploadFileResponse uploadFileResponse = + candidateManager.upload(id001, activeVersion002, is, + "csar", "SDCmockFail3"); + assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); + assertEquals(1, uploadFileResponse.getErrors().size()); } - - @Test - public void testUploadFileIsNotZip() throws Exception { - VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); - doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); - - try (InputStream is = new ByteArrayInputStream( "Thia is not a zip file".getBytes() );) { - UploadFileResponse uploadFileResponse = candidateManager.upload(id001, activeVersion002, is, USER1, - "csar", "file"); - assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); - assertFalse(uploadFileResponse.getErrors().isEmpty()); - assertTrue( uploadFileResponse.getErrors().values().stream() - .filter(getListPredicate(Messages.CSAR_FILE_NOT_FOUND - .getErrorMessage().substring(0,7))).findAny().isPresent()); - } + } + + @Test + public void testUploadFileIsNotZip() throws Exception { + VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); + doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); + + try (InputStream is = new ByteArrayInputStream("Thia is not a zip file".getBytes());) { + UploadFileResponse uploadFileResponse = + candidateManager.upload(id001, activeVersion002, is, + "csar", "file"); + assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); + assertFalse(uploadFileResponse.getErrors().isEmpty()); + assertTrue(uploadFileResponse.getErrors().values().stream().anyMatch( + getListPredicate(Messages.CSAR_FILE_NOT_FOUND.getErrorMessage().substring(0, 7)))); } - @Test - public void testUploadFileIsEmpty() throws Exception { - VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); - doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); - - try (InputStream is = new ByteArrayInputStream( new byte[]{} )) { - UploadFileResponse uploadFileResponse = candidateManager.upload(id001, - activeVersion002, is, USER1, "csar", "file"); - assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); - assertEquals(1, uploadFileResponse.getErrors().size()); - } + } + + @Test + public void testUploadFileIsEmpty() throws Exception { + VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); + doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); + + try (InputStream is = new ByteArrayInputStream(new byte[]{})) { + UploadFileResponse uploadFileResponse = candidateManager.upload(id001, + activeVersion002, is, "csar", "file"); + assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); + assertEquals(1, uploadFileResponse.getErrors().size()); } + } - @Test - public void testMFError() throws Exception { - VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); - doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); + @Test + public void testMFError() throws Exception { + VspDetails vspDetails = new VspDetails("dummyId", new Version(1, 0)); + doReturn(vspDetails).when(vspInfoDaoMock).get(any(VspDetails.class)); - try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/SDCmockBrokenMF.csar")) { - UploadFileResponse uploadFileResponse = candidateManager.upload(id001, activeVersion002, is, USER1, "csar", "SDCmockBrokenMF"); - assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); - assertEquals(1, uploadFileResponse.getErrors().size()); - assertTrue( uploadFileResponse.getErrors() - .values().stream() - .filter(getListPredicate(Messages.MANIFEST_NO_METADATA.getErrorMessage())).findAny().isPresent()); + try (InputStream is = getClass().getResourceAsStream("/vspmanager.csar/SDCmockBrokenMF.csar")) { + UploadFileResponse uploadFileResponse = + candidateManager.upload(id001, activeVersion002, is, "csar", "SDCmockBrokenMF"); + assertEquals(uploadFileResponse.getOnboardingType(), OnboardingTypesEnum.CSAR); + assertEquals(1, uploadFileResponse.getErrors().size()); + assertTrue(uploadFileResponse.getErrors().values().stream() + .anyMatch(getListPredicate(Messages.MANIFEST_NO_METADATA.getErrorMessage()))); - } } + } } diff --git a/openecomp-be/backend/pom.xml b/openecomp-be/backend/pom.xml index a627ed0e7f..2d98aa5342 100644 --- a/openecomp-be/backend/pom.xml +++ b/openecomp-be/backend/pom.xml @@ -23,6 +23,8 @@ openecomp-sdc-application-config-manager openecomp-sdc-activity-log-manager openecomp-sdc-healthcheck-manager + openecomp-sdc-conflict-manager + openecomp-sdc-item-permissions-manager 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 de33804dff..565e60e427 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 @@ -39,6 +39,8 @@ public enum Messages { 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."), + 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" + @@ -148,7 +150,11 @@ public enum Messages { + "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"); + + "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"); private String errorMessage; 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 new file mode 100644 index 0000000000..6e41d5888d --- /dev/null +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/SdcRuntimeException.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.errors; + +public class SdcRuntimeException extends RuntimeException { + public SdcRuntimeException() { + } + + public SdcRuntimeException(String message) { + super(message); + } + + public SdcRuntimeException(String message, Throwable cause) { + super(message, cause); + } + + public SdcRuntimeException(Throwable cause) { + super(cause); + } + + public SdcRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} 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 24da8363c1..9de0e7b0e1 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 @@ -33,6 +33,7 @@ public class SdcCommon { 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/pom.xml b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/pom.xml new file mode 100644 index 0000000000..413cae7933 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + + + + org.openecomp.sdc + openecomp-conflict-lib + 1.2.0-SNAPSHOT + .. + + + openecomp-conflict-api + + + + + org.openecomp.sdc.core + openecomp-facade-core + ${project.version} + + + org.openecomp.sdc.core + openecomp-facade-api + ${project.version} + + + org.openecomp.sdc + openecomp-sdc-versioning-api + ${project.version} + + + + + + \ No newline at end of file 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 new file mode 100644 index 0000000000..189e4cedd9 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandler.java @@ -0,0 +1,27 @@ +package org.openecomp.conflicts; + +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); + + void finalizeMerge(String itemId, Version version); + + void postListConflicts(String itemId, Version version, ItemVersionConflict conflicts); + + Optional getConflict(String itemId, Version version, String conflictId); + + void postGetConflict(String itemId, Version version, Conflict conflict); + + void preResolveConflict(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 new file mode 100644 index 0000000000..8fb0a48870 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.conflicts; + +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 static ItemMergeHandlerFactory getInstance() { + return AbstractFactory.getInstance(ItemMergeHandlerFactory.class); + } + + public abstract Optional createInterface(String itemId); +} \ No newline at end of file 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 new file mode 100644 index 0000000000..273233a12c --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDao.java @@ -0,0 +1,18 @@ +package org.openecomp.conflicts.dao; + +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; + +public interface ConflictsDao { + + boolean isConflicted(String itemId, Version version); + + ItemVersionConflict getConflict(String itemId, Version version); + + Conflict getConflict(String itemId, Version version, String conflictId); + + 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 new file mode 100644 index 0000000000..e4c88d6279 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDaoFactory.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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 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 new file mode 100644 index 0000000000..bc324af1dd --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Conflict.java @@ -0,0 +1,30 @@ +package org.openecomp.conflicts.types; + +import org.openecomp.sdc.datatypes.model.ElementType; + +public class Conflict extends ConflictInfo { + private T yours; + private T theirs; + + public Conflict(String id, ElementType type, String name) { + super(id, type, name); + } + + public T getYours() { + return yours; + } + + 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 new file mode 100644 index 0000000000..ff58f00121 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictInfo.java @@ -0,0 +1,39 @@ +package org.openecomp.conflicts.types; + +import org.openecomp.sdc.datatypes.model.ElementType; + +public class ConflictInfo { + private String id; + private ElementType type; + private String name; + + public ConflictInfo(String id, ElementType type, String name) { + this.id = id; + this.type = type; + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public ElementType getType() { + return type; + } + + public void setType(ElementType type) { + this.type = type; + } + + public String getName() { + return 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 new file mode 100644 index 0000000000..961f9080d9 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictResolution.java @@ -0,0 +1,32 @@ +package org.openecomp.conflicts.types; + +import java.util.Map; + +public class ConflictResolution { + private Resolution resolution; + // sits in lower level... + private Map otherResolution; + + public ConflictResolution() { + } + + public ConflictResolution(Resolution resolution) { + this.resolution = resolution; + } + + public Resolution getResolution() { + return resolution; + } + + public void setResolution(Resolution resolution) { + this.resolution = resolution; + } + + public Map getOtherResolution() { + return 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 new file mode 100644 index 0000000000..a4749f3990 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ItemVersionConflict.java @@ -0,0 +1,31 @@ +package org.openecomp.conflicts.types; + +import org.openecomp.sdc.versioning.dao.types.Version; + +import java.util.ArrayList; +import java.util.Collection; + +public class ItemVersionConflict { + private Conflict versionConflict; + private Collection elementConflicts = new ArrayList<>(); + + public Conflict getVersionConflict() { + return versionConflict; + } + + public void setVersionConflict(Conflict versionConflict) { + this.versionConflict = versionConflict; + } + + public Collection getElementConflicts() { + return elementConflicts; + } + + public void setElementConflicts(Collection elementConflicts) { + this.elementConflicts = elementConflicts; + } + + 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 new file mode 100644 index 0000000000..2222f81c70 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Resolution.java @@ -0,0 +1,5 @@ +package org.openecomp.conflicts.types; + +public enum Resolution { + THEIRS,YOURS,OTHER +} diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/pom.xml b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/pom.xml new file mode 100644 index 0000000000..ddeb03df53 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/pom.xml @@ -0,0 +1,36 @@ + + + 4.0.0 + + org.openecomp.sdc + openecomp-conflict-lib + 1.2.0-SNAPSHOT + .. + + + openecomp-conflict-core + + + org.openecomp.sdc + openecomp-conflict-api + ${project.version} + + + org.openecomp.sdc.core + openecomp-zusammen-api + ${project.version} + + + org.openecomp.sdc + openecomp-sdc-vendor-software-product-core + ${project.version} + + + org.openecomp.sdc + openecomp-sdc-vendor-license-core + ${project.version} + + + \ No newline at end of file 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 new file mode 100644 index 0000000000..4c981acee4 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactoryImpl.java @@ -0,0 +1,40 @@ +package org.openecomp.conflicts; + +import org.openecomp.conflicts.dao.ConflictsDaoFactory; +import org.openecomp.conflicts.impl.VspMergeHandler; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.datatypes.model.ItemType; +import org.openecomp.sdc.vendorsoftwareproduct.dao.VspMergeDaoFactory; +import org.openecomp.sdc.versioning.ItemManagerFactory; +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())); + } + + @Override + public Optional createInterface(String itemId) { + Item item = ItemManagerFactory.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 new file mode 100644 index 0000000000..7cb3598b9d --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoFactoryImpl.java @@ -0,0 +1,17 @@ +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; + +public class ConflictsDaoFactoryImpl extends ConflictsDaoFactory { + + private static final ConflictsDao INSTANCE = new + ConflictsDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @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 new file mode 100644 index 0000000000..eac1be3b8e --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoImpl.java @@ -0,0 +1,175 @@ +package org.openecomp.conflicts.dao.impl.zusammen; + +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.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.Item; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import com.amdocs.zusammen.datatypes.item.Resolution; +import org.openecomp.conflicts.dao.ConflictsDao; +import org.openecomp.conflicts.types.Conflict; +import org.openecomp.conflicts.types.ConflictResolution; +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.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; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + +public class ConflictsDaoImpl implements ConflictsDao { + private final ZusammenAdaptor zusammenAdaptor; + + public ConflictsDaoImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } + + @Override + public boolean isConflicted(String itemId, Version version) { + com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict itemVersionConflict = + zusammenAdaptor + .getVersionConflict(createSessionContext(), 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(createSessionContext(), new Id(itemId), new Id(version.getId()))); + } + + @Override + public Conflict getConflict(String itemId, Version version, String conflictId) { + return zusammenAdaptor.getElementConflict(createSessionContext(), + 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 = createSessionContext(); + 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 new file mode 100644 index 0000000000..4dffaf8231 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ItemVersionConflictConvertorFromZusammen.java @@ -0,0 +1,73 @@ +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; +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 org.openecomp.conflicts.types.Conflict; +import org.openecomp.conflicts.types.ConflictInfo; +import org.openecomp.sdc.datatypes.model.ElementType; +import org.openecomp.sdc.versioning.dao.impl.zusammen.convertor.ItemVersionToVersionConvertor; +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; + } + + 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; + } + 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(); + + 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 new file mode 100644 index 0000000000..f7d0bca392 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/impl/VspMergeHandler.java @@ -0,0 +1,204 @@ +package org.openecomp.conflicts.impl; + +import org.openecomp.conflicts.ItemMergeHandler; +import org.openecomp.conflicts.dao.ConflictsDao; +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; +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.ArrayList; +import java.util.Collection; +import java.util.Collections; +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 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; + +public class VspMergeHandler implements ItemMergeHandler { + + 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 HashMap<>(); + + 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.isVspModelConflicted(itemId, version); + } + + @Override + public void finalizeMerge(String itemId, Version version) { + if (!conflictsDao.isConflicted(itemId, version)) { + vspMergeDao.applyVspModelConflictResolution(itemId, version); + } + } + + @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.isVspModelConflicted(itemId, version)) { + elementConflicts + .add(new ConflictInfo(VSP_MODEL_CONFLICT_ID, NetworkPackage, NetworkPackage.name())); + } + + 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 void preResolveConflict(String itemId, Version version, String conflictId, + ConflictResolution resolution) { + if (VSP_MODEL_CONFLICT_ID.equals(conflictId)) { + return; + } + 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.updateVspModelConflictResolution(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.updateVspModelConflictResolution(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; + } + + 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)); + } + + 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()); + } +} diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..ec9f3703d1 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/resources/factoryConfiguration.json @@ -0,0 +1,4 @@ +{ + "org.openecomp.conflicts.ItemMergeHandlerFactory": "org.openecomp.conflicts.ItemMergeHandlerFactoryImpl", + "org.openecomp.conflicts.dao.ConflictsDaoFactory": "org.openecomp.conflicts.dao.impl.zusammen.ConflictsDaoFactoryImpl" +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-conflict-lib/pom.xml b/openecomp-be/lib/openecomp-conflict-lib/pom.xml new file mode 100644 index 0000000000..de6bcd6fef --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + + + org.openecomp.sdc + openecomp-sdc-lib + 1.2.0-SNAPSHOT + .. + + + openecomp-conflict-lib + pom + + openecomp-conflict-api + openecomp-conflict-core + + \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/java/org/openecomp/sdc/applicationconfig/dao/ApplicationConfigImplDaoTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/java/org/openecomp/sdc/applicationconfig/dao/ApplicationConfigImplDaoTest.java index 6b5c5f94c4..e3d87656ad 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/java/org/openecomp/sdc/applicationconfig/dao/ApplicationConfigImplDaoTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/java/org/openecomp/sdc/applicationconfig/dao/ApplicationConfigImplDaoTest.java @@ -20,23 +20,6 @@ package org.openecomp.sdc.applicationconfig.dao; -import org.openecomp.core.utilities.applicationconfig.ApplicationConfig; -import org.openecomp.core.utilities.applicationconfig.ApplicationConfigFactory; -import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDao; -import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDaoFactory; -import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; -import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; -import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.common.errors.ErrorCategory; -import org.openecomp.sdc.common.errors.ErrorCode; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - - public class ApplicationConfigImplDaoTest { /* 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 9353de662b..7b53f3416a 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 @@ -21,9 +21,6 @@ package org.openecomp.core.factory.impl; -import static org.openecomp.core.utilities.CommonMethods.isEmpty; -import static org.openecomp.core.utilities.CommonMethods.newInstance; - import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; @@ -32,6 +29,9 @@ import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import static org.openecomp.core.utilities.CommonMethods.isEmpty; +import static org.openecomp.core.utilities.CommonMethods.newInstance; + public abstract class AbstractFactoryBase { /** 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 dce34a1c96..15e9ceeee7 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 @@ -32,7 +32,7 @@ import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import java.util.Optional; public class UniqueValueUtil { - public static final String UNIQUE_VALUE_VIOLATION = "UNIQUE_VALUE_VIOLATION"; + 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 UniqueValueDao uniqueValueDao = @@ -46,9 +46,7 @@ public class UniqueValueUtil { * @param uniqueCombination the unique combination */ public static void createUniqueValue(String type, String... uniqueCombination) { - - - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); Optional value = formatValue(uniqueCombination); if (!value.isPresent()) { @@ -57,7 +55,7 @@ public class UniqueValueUtil { validateUniqueValue(type, value.get(), uniqueCombination); uniqueValueDao.create(new UniqueValueEntity(type, value.get())); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } /** @@ -69,7 +67,7 @@ public class UniqueValueUtil { public static void deleteUniqueValue(String type, String... uniqueCombination) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); Optional value = formatValue(uniqueCombination); if (!value.isPresent()) { @@ -77,7 +75,7 @@ public class UniqueValueUtil { } uniqueValueDao.delete(new UniqueValueEntity(type, value.get())); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } /** @@ -92,17 +90,14 @@ public class UniqueValueUtil { String... uniqueContext) { - mdcDataDebugMessage.debugEntryMessage(null, null); - - boolean nonEqual = (newValue != null) && (oldValue != null) - && !newValue.toLowerCase().equals(oldValue.toLowerCase()); + mdcDataDebugMessage.debugEntryMessage(null); - if (nonEqual || newValue == null || oldValue == null) { + if (newValue == null || oldValue == null || !newValue.equalsIgnoreCase(oldValue)) { createUniqueValue(type, CommonMethods.concat(uniqueContext, new String[]{newValue})); deleteUniqueValue(type, CommonMethods.concat(uniqueContext, new String[]{oldValue})); } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } /** @@ -112,7 +107,7 @@ public class UniqueValueUtil { * @param uniqueCombination the unique combination */ public static void validateUniqueValue(String type, String... uniqueCombination) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); Optional value = formatValue(uniqueCombination); if (!value.isPresent()) { @@ -120,11 +115,11 @@ public class UniqueValueUtil { } validateUniqueValue(type, value.get(), uniqueCombination); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } private static void validateUniqueValue(String type, String value, String... uniqueCombination) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); if (uniqueValueDao.get(new UniqueValueEntity(type, value)) != null) { throw new CoreException(new ErrorCode.ErrorCodeBuilder() @@ -134,13 +129,13 @@ public class UniqueValueUtil { uniqueCombination[uniqueCombination.length - 1])).build()); } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } private static Optional formatValue(String[] uniqueCombination) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); if (uniqueCombination == null || uniqueCombination.length == 0 || uniqueCombination[uniqueCombination.length - 1] == null) { @@ -150,7 +145,7 @@ public class UniqueValueUtil { uniqueCombination[uniqueCombination.length - 1] = uniqueCombination[uniqueCombination.length - 1].toLowerCase(); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); return Optional.of(CommonMethods.arrayToSeparatedString(uniqueCombination, '_')); } } 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 93410bc581..2172e1bc2f 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 @@ -20,7 +20,11 @@ package org.openecomp.core.nosqldb.impl.cassandra; -import com.datastax.driver.core.*; +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 org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.util.CassandraUtils; diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/NoSqlDbTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/NoSqlDbTest.java index 5c4f951a7b..2bab7e0d67 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/NoSqlDbTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/NoSqlDbTest.java @@ -20,14 +20,7 @@ package org.openecomp.core.nosqldb; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; import org.openecomp.core.nosqldb.api.NoSqlDb; -import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.List; public class NoSqlDbTest { diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/util/ConfigurationManagerTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/util/ConfigurationManagerTest.java index f8d5d2dce7..7a6343d15c 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/util/ConfigurationManagerTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/util/ConfigurationManagerTest.java @@ -7,7 +7,7 @@ import java.io.Closeable; import java.io.IOException; import java.lang.reflect.Field; -import static org.testng.Assert.*; +import static org.testng.Assert.assertNotNull; /** * @author EVITALIY diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/pom.xml new file mode 100644 index 0000000000..c0618ba503 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + + + org.openecomp.sdc.core + openecomp-core-lib + 1.2.0-SNAPSHOT + + + openecomp-session-lib + + + + + org.openecomp.sdc.core + openecomp-facade-api + ${project.version} + + + org.openecomp.sdc.core + openecomp-facade-core + ${project.version} + + + + + \ No newline at end of file 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 new file mode 100644 index 0000000000..a1b410c90c --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContext.java @@ -0,0 +1,8 @@ +package org.openecomp.sdc.common.session; + +public interface SessionContext { + + User getUser(); + + String getTenant(); +} 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 new file mode 100644 index 0000000000..8efbbd10eb --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProvider.java @@ -0,0 +1,10 @@ +package org.openecomp.sdc.common.session; + +public interface SessionContextProvider { + + void create(String user); + + SessionContext get(); + + void close(); +} 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 new file mode 100644 index 0000000000..cfa6a346c9 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProviderFactory.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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 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 new file mode 100644 index 0000000000..5319a0bf56 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/User.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.common.session; + +public class User { + private final String userId; + + public User(String userId) { + this.userId = userId; + } + + public String getUserId() { + return userId; + } +} 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 new file mode 100644 index 0000000000..53a40a163f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/AsdcSessionContextProvider.java @@ -0,0 +1,50 @@ +package org.openecomp.sdc.common.session.impl; + +import org.openecomp.sdc.common.session.SessionContext; +import org.openecomp.sdc.common.session.SessionContextProvider; +import org.openecomp.sdc.common.session.User; + +public class AsdcSessionContextProvider implements SessionContextProvider { + + private static final ThreadLocal threadUserId = new ThreadLocal<>(); + + @Override + public void create(String userId) { + threadUserId.set(userId); + } + + @Override + public SessionContext get() { + if (threadUserId.get() == null) { + throw new RuntimeException("UserId was not set for this thread"); + } + + return new AsdcSessionContext(new User(threadUserId.get()), "dox"); + } + + @Override + public void close() { + threadUserId.remove(); + } + + private static class AsdcSessionContext implements SessionContext { + + private final User user; + private final String tenant; + + private AsdcSessionContext(User user, String tenant) { + this.user = user; + this.tenant = tenant; + } + + @Override + public User getUser() { + return user; + } + + @Override + public String getTenant() { + return tenant; + } + } +} 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 new file mode 100644 index 0000000000..635aa5b6ed --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/SessionContextProviderFactoryImpl.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.session.impl; + +import org.openecomp.sdc.common.session.SessionContextProvider; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; + +public class SessionContextProviderFactoryImpl extends SessionContextProviderFactory { + private static final SessionContextProvider INSTANCE = new AsdcSessionContextProvider(); + + @Override + public SessionContextProvider createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..cd1637a80e --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/resources/factoryConfiguration.json @@ -0,0 +1,3 @@ +{ + "org.openecomp.sdc.common.session.SessionContextProviderFactory": "org.openecomp.sdc.common.session.impl.SessionContextProviderFactoryImpl" +} \ No newline at end of file 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 6ab3f8b049..5a8a2db2f2 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 @@ -23,12 +23,9 @@ package org.openecomp.core.utilities.file; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.services.YamlUtil; import java.io.ByteArrayInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java index 527ba22c1d..be0686ef5a 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java @@ -6,7 +6,9 @@ import java.io.IOException; import java.util.Arrays; import java.util.Optional; -import static org.testng.Assert.*; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; /** * @author EVITALIY diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/pom.xml index 538a7fb42a..ee59b5bf77 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/pom.xml +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/pom.xml @@ -18,6 +18,16 @@ openecomp-sdc-logging-core ${project.version} + + org.openecomp.sdc.core + openecomp-session-lib + ${project.version} + + + org.openecomp.sdc + openecomp-sdc-versioning-api + ${project.version} + org.openecomp.sdc.core openecomp-facade-api @@ -43,6 +53,11 @@ commons-lang3 3.4 + + com.amdocs.zusammen + zusammen-datatypes + ${zusammen.version} + 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 new file mode 100644 index 0000000000..68c709826f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/convertor/ElementConvertor.java @@ -0,0 +1,37 @@ +package org.openecomp.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.Item; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import org.openecomp.sdc.datatypes.model.ElementType; +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 String getElementName(Element element) { + return element.getInfo().getName(); + } + + + abstract public T convert(Element element); + + 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( 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 2ba447fd6a..35c07cbee0 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 @@ -1,7 +1,9 @@ package org.openecomp.core.zusammen.api; 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; @@ -11,31 +13,53 @@ 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.Tag; +import org.openecomp.sdc.versioning.dao.types.Revision; import java.util.Collection; +import java.util.List; import java.util.Optional; public interface ZusammenAdaptor { Collection listItems(SessionContext context); + Item getItem(SessionContext context, Id itemId); + Id createItem(SessionContext context, Info info); void updateItem(SessionContext context, Id itemId, Info info); - // TODO: 4/4/2017 fix this workaround when versionId will be recieved from UI + // TODO: 4/4/2017 remove this workaround when versionId will be recieved from UI Optional getFirstVersion(SessionContext context, Id itemId); + Collection listPublicVersions(SessionContext context, Id itemId); + + ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId); + Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData itemVersionData); void updateVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData); + ItemVersion getVersion(SessionContext context, Id itemId, Id versionId); + + ItemVersionStatus getVersionStatus(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 resetVersionHistory(SessionContext context, Id itemId, Id versionId, String changeRef); + void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String version); + + void publishVersion(SessionContext context, Id itemId, Id versionId, String message); + + void syncVersion(SessionContext context, Id itemId, Id versionId); + + void forceSyncVersion(SessionContext context, Id itemId, Id versionId); Optional getElementInfo(SessionContext context, ElementContext elementContext, Id elementId); @@ -43,38 +67,39 @@ public interface ZusammenAdaptor { 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, + Collection listElements(SessionContext context, ElementContext elementContext, Id parentElementId); - Collection listElementData(SessionContext context, - ElementContext elementContext, + Collection listElementData(SessionContext context, ElementContext elementContext, Id parentElementId); /** - * Lists the sub elements of the element named which is a sub element of - * @param context - * @param elementContext - * @param parentElementId - * @param elementName - * @return + * 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); + 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 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); Collection checkHealth(SessionContext context); - String getVersion(SessionContext sessionContext); + String getVersion(SessionContext context); + + void revert(SessionContext sessionContext, String itemId, String versionId, String revisionId); + + List listRevisions(SessionContext sessionContext, String itemId, String versionId); } 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 3df6151fae..623f958ceb 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 @@ -1,40 +1,40 @@ package org.openecomp.core.zusammen.api; 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.UserInfo; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.datatypes.model.ElementType; +import org.openecomp.types.ElementPropertyName; public class ZusammenUtil { - // TODO: 3/19/2017 add user and tenant args + public static SessionContext createSessionContext() { + org.openecomp.sdc.common.session.SessionContext asdcSessionContext = + SessionContextProviderFactory.getInstance().createInterface().get(); + SessionContext sessionContext = new SessionContext(); - sessionContext.setUser(new UserInfo("GLOBAL_USER")); - sessionContext.setTenant("dox"); + sessionContext.setUser(new UserInfo(asdcSessionContext.getUser().getUserId())); + sessionContext.setTenant(asdcSessionContext.getTenant()); return sessionContext; } - public static ZusammenElement buildStructuralElement(String structureElementName, - Action action) { - ZusammenElement element = new ZusammenElement(); + public static ZusammenElement buildStructuralElement(ElementType elementType, Action action) { + ZusammenElement element = buildElement(null, action); Info info = new Info(); - info.setName(structureElementName); + info.setName(elementType.name()); + info.addProperty(ElementPropertyName.elementType.name(), elementType.name()); element.setInfo(info); - if (action != null) { - element.setAction(action); - } return element; } - // TODO: 4/24/2017 remove upon working with more than one single version - public static ItemVersionData createFirstVersionData() { - Info info = new Info(); - info.setName("main version"); - ItemVersionData itemVersionData = new ItemVersionData(); - itemVersionData.setInfo(info); - return itemVersionData; + 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 new file mode 100644 index 0000000000..ae9c1fcd44 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/AsdcElement.java @@ -0,0 +1,131 @@ +package org.openecomp.types; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.datatypes.Id; +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; +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; + } +} 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 new file mode 100644 index 0000000000..ddbef7d8a4 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/ElementPropertyName.java @@ -0,0 +1,6 @@ +package org.openecomp.types; + +public enum ElementPropertyName { + 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 6381b2efd2..9005bb84c3 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 @@ -1,7 +1,9 @@ package org.openecomp.core.zusammen.db; 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; @@ -11,22 +13,31 @@ 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 com.amdocs.zusammen.datatypes.response.Response; import java.util.Collection; -import java.util.Optional; public interface ZusammenConnector { + Collection checkHealth(SessionContext sessionContext); + + String getVersion(SessionContext sessionContext); + Collection listItems(SessionContext context); + Item getItem(SessionContext context, Id itemId); + Id createItem(SessionContext context, Info info); void updateItem(SessionContext context, Id itemId, Info info); - Collection listVersions(SessionContext context, Id itemId); + Collection listPublicVersions(SessionContext context, Id itemId); + + ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId); Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData itemVersionData); @@ -34,23 +45,42 @@ public interface ZusammenConnector { void updateVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData); + ItemVersion getVersion(SessionContext context, Id itemId, Id versionId); + + ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId); + void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag); - void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String changeRef); + void resetVersionRevision(SessionContext context, Id itemId, Id versionId, Id revisionId); + + void revertVersionRevision(SessionContext context, Id itemId, Id versionId, Id revisionId); + + ItemVersionRevisions listVersionRevisions(SessionContext context, Id itemId, Id versionId); + + void publishVersion(SessionContext context, Id itemId, Id versionId, String message); + + void syncVersion(SessionContext context, Id itemId, Id versionId); + + void forceSyncVersion(SessionContext context, Id itemId, Id versionId); + + ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId); Collection listElements(SessionContext context, ElementContext elementContext, Id parentElementId); - Response getElementInfo(SessionContext context, ElementContext elementContext, Id - elementId); + ElementInfo getElementInfo(SessionContext context, ElementContext elementContext, Id elementId); - Response getElement(SessionContext context, ElementContext elementContext, Id elementId); + Element getElement(SessionContext context, ElementContext elementContext, Id elementId); - Optional saveElement(SessionContext context, ElementContext elementContext, - ZusammenElement element, String message); + ElementConflict getElementConflict(SessionContext context, ElementContext elementContext, + Id elementId); - Collection checkHealth(SessionContext sessionContext); + Element saveElement(SessionContext context, ElementContext elementContext, + ZusammenElement element, String message); - String getVersion(SessionContext sessionContext); + void resolveElementConflict(SessionContext context, ElementContext elementContext, + ZusammenElement element, Resolution resolution); + + 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/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 deb5ffde35..1d387b939f 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 @@ -1,11 +1,14 @@ package org.openecomp.core.zusammen.db.impl; +import com.amdocs.zusammen.adaptor.inbound.api.health.HealthAdaptorFactory; import com.amdocs.zusammen.adaptor.inbound.api.item.ElementAdaptorFactory; import com.amdocs.zusammen.adaptor.inbound.api.item.ItemAdaptorFactory; import com.amdocs.zusammen.adaptor.inbound.api.item.ItemVersionAdaptorFactory; -import com.amdocs.zusammen.adaptor.inbound.api.health.HealthAdaptorFactory; 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.MergeResult; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.commons.health.data.HealthInfo; import com.amdocs.zusammen.datatypes.Id; @@ -16,6 +19,9 @@ 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 com.amdocs.zusammen.datatypes.response.Response; import com.amdocs.zusammen.datatypes.response.ReturnCode; @@ -28,14 +34,18 @@ import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; import java.util.Collection; -import java.util.Optional; 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 ItemAdaptorFactory itemAdaptorFactory; private ItemVersionAdaptorFactory versionAdaptorFactory; private ElementAdaptorFactory elementAdaptorFactory; private HealthAdaptorFactory healthAdaptorFactory; + public ZusammenConnectorImpl( ItemAdaptorFactory itemAdaptorFactory, ItemVersionAdaptorFactory versionAdaptorFactory, @@ -68,15 +78,24 @@ public class ZusammenConnectorImpl implements ZusammenConnector { return response.getValue(); } + @Override + public Item getItem(SessionContext context, Id itemId) { + Response response = itemAdaptorFactory.createInterface(context).get(context, itemId); + if (!response.isSuccessful()) { + throw new RuntimeException( + "Failed to get Item. message:" + response.getReturnCode().toString()); + } + return response.getValue(); + } + @Override public Id createItem(SessionContext context, Info info) { Response response = itemAdaptorFactory.createInterface(context).create(context, info); - if (response.isSuccessful()) { - return response.getValue(); - } else { + if (!response.isSuccessful()) { throw new RuntimeException( - "failed to create Item. message:" + response.getReturnCode().toString()); + "Failed to create Item. message:" + response.getReturnCode().toString()); } + return response.getValue(); } @Override @@ -91,17 +110,29 @@ public class ZusammenConnectorImpl implements ZusammenConnector { } @Override - public Collection listVersions(SessionContext context, Id itemId) { + public Collection listPublicVersions(SessionContext context, Id itemId) { Response> versions = - versionAdaptorFactory.createInterface(context).list(context, Space.PRIVATE, itemId); + versionAdaptorFactory.createInterface(context).list(context, Space.PUBLIC, itemId); if (!versions.isSuccessful()) { logErrorMessageToMdc(ItemElementLoggerTargetServiceName.ITEM_VERSION_RETRIEVAL, versions .getReturnCode()); - throw new RuntimeException(versions.getReturnCode().toString()); // TODO: 3/26/2017 + throw new RuntimeException(versions.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 RuntimeException( + 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 Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData itemVersionData) { @@ -110,10 +141,9 @@ public class ZusammenConnectorImpl implements ZusammenConnector { if (response.isSuccessful()) { return response.getValue(); } else { - throw new RuntimeException("failed to create Item Version. ItemId:" + itemId + " based " + - "on:" + baseVersionId + - " message:" + response - .getReturnCode().toString()); + throw new RuntimeException(String.format( + "failed to create Item Version. ItemId: %s, base versionId: %s, message: %s", + itemId.getValue(), baseVersionId.getValue(), response.getReturnCode().toString())); } } @@ -124,9 +154,33 @@ public class ZusammenConnectorImpl implements ZusammenConnector { .update(context, itemId, versionId, itemVersionData); if (!response.isSuccessful()) { throw new RuntimeException( - String.format("failed to create Item Version. ItemId: %s, versionId: %s, message: %s", + String.format("failed to update Item Version. ItemId: %s, versionId: %s, message: %s", + 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 RuntimeException( + 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 ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId) { + Response response = + versionAdaptorFactory.createInterface(context).getStatus(context, itemId, versionId); + if (!response.isSuccessful()) { + throw new RuntimeException( + 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 @@ -136,65 +190,197 @@ public class ZusammenConnectorImpl implements ZusammenConnector { if (!response.isSuccessful()) { throw new RuntimeException(String.format( "failed to tag Item Version with tag %s. ItemId: %s, versionId: %s, message: %s", - tag.getName(), itemId.getValue(), versionId.getValue(), response.getReturnCode() - .getMessage())); + tag.getName(), itemId.getValue(), versionId.getValue(), + response.getReturnCode().toString())); } } @Override - public void resetVersionHistory(SessionContext context, Id itemId, Id versionId, - String changeRef) { + public void resetVersionRevision(SessionContext context, Id itemId, Id versionId, + Id revisionId) { Response response = versionAdaptorFactory.createInterface(context) - .resetHistory(context, itemId, versionId, changeRef); + .resetRevision(context, itemId, versionId, revisionId); if (!response.isSuccessful()) { throw new RuntimeException(String.format( - "failed to reset Item Version back to %s. ItemId: %s, versionId: %s, message: %s", - changeRef, itemId.getValue(), versionId.getValue(), + "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 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 RuntimeException(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 ItemVersionRevisions listVersionRevisions(SessionContext context, Id itemId, + Id versionId) { + Response response = + versionAdaptorFactory.createInterface(context) + .listRevisions(context, itemId, versionId); + if (!response.isSuccessful()) { + throw new RuntimeException(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 publishVersion(SessionContext context, Id itemId, Id versionId, String message) { + Response response = + versionAdaptorFactory.createInterface(context).publish(context, itemId, versionId, message); + if (!response.isSuccessful()) { + throw new RuntimeException(String.format( + "failed to publish 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 RuntimeException(String.format( + "failed to sync item Version. 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 RuntimeException(String.format( + "failed to force 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 RuntimeException(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> elementInfosResponse = elementAdaptorFactory + Response> response = elementAdaptorFactory .createInterface(context).list(context, elementContext, parentElementId); - if (elementInfosResponse.isSuccessful()) { - return elementInfosResponse.getValue(); + if (response.isSuccessful()) { + return response.getValue(); } else { logErrorMessageToMdc(ItemElementLoggerTargetServiceName.ELEMENT_GET_BY_PROPERTY, - elementInfosResponse.getReturnCode()); - throw new RuntimeException(elementInfosResponse.getReturnCode().toString()); + response.getReturnCode()); + throw new RuntimeException(response.getReturnCode().toString()); } } + @Override - public Response getElementInfo(SessionContext context, ElementContext elementContext, - Id elementId) { - return elementAdaptorFactory.createInterface(context) - .getInfo(context, elementContext, elementId); + 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(); + } @Override - public Response getElement(SessionContext context, ElementContext elementContext, - Id elementId) { - return elementAdaptorFactory.createInterface(context).get(context, elementContext, elementId); + public ElementConflict getElementConflict(SessionContext context, ElementContext elementContext, + Id elementId) { + Response response = elementAdaptorFactory.createInterface(context) + .getConflict(context, elementContext, elementId); + if (!response.isSuccessful()) { + throw new RuntimeException(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(); } @Override - public Optional saveElement(SessionContext context, ElementContext elementContext, - ZusammenElement element, String message) { + public Element saveElement(SessionContext context, ElementContext elementContext, + ZusammenElement element, String message) { Response response = elementAdaptorFactory.createInterface(context) .save(context, elementContext, element, message); if (!response.isSuccessful()) { throw new RuntimeException(String - .format("Failed to save element %s. ItemId: %s, versionId: %s, message: %s", + .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 Optional.of(response.getValue()); + return response.getValue(); + } + + @Override + public void resolveElementConflict(SessionContext context, ElementContext elementContext, + ZusammenElement element, + Resolution resolution) { + Response response = elementAdaptorFactory.createInterface(context) + .resolveConflict(context, elementContext, element, resolution); + if (!response.isSuccessful()) { + throw new RuntimeException( + "Failed to resolve conflict. message:" + response.getReturnCode().toString()); + } + } + + @Override + public void resetVersionHistory(SessionContext context, Id itemId, Id versionId, + String revision_id) { + + } + + private RuntimeException buildGetElementException(ElementContext elementContext, Id elementId, + String zusammenErrorMessage) { + if (elementContext.getRevisionId() == null) { + return new RuntimeException(String.format(GET_ELEMENT_ERR_MSG, + elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), + elementId.getValue(), zusammenErrorMessage)); + } + return new RuntimeException(String.format(GET_ELEMENT_IN_REV_ERR_MSG, + elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue(), + elementId.getValue(), zusammenErrorMessage)); } private void logErrorMessageToMdc(ItemElementLoggerTargetServiceName 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 41ce0283a1..9bdbfd681c 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 @@ -1,24 +1,30 @@ package org.openecomp.core.zusammen.impl; 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.Action; +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 com.amdocs.zusammen.datatypes.response.Response; -import com.amdocs.zusammen.datatypes.response.ReturnCode; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.db.ZusammenConnector; -import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; -import org.openecomp.sdc.logging.types.LoggerConstants; -import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.versioning.dao.types.Revision; import java.util.ArrayList; import java.util.Collection; +import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.function.Predicate; @@ -32,31 +38,16 @@ public class ZusammenAdaptorImpl implements ZusammenAdaptor { this.connector = connector; } - @Override - public Optional getFirstVersion(SessionContext context, Id itemId) { - Collection versions = connector.listVersions(context, itemId); - if(versions == null || versions.size()==0) { - return Optional.empty(); - } - List itemVersions = new ArrayList<>(versions); - sortItemVersionListByModificationTimeDescOrder(itemVersions); - ItemVersion itemVersion = itemVersions.iterator().next(); - - return Optional.ofNullable(itemVersion); - } - @Override public Optional getElementInfo(SessionContext context, ElementContext elementContext, Id elementId) { - Response response = connector.getElementInfo(context, elementContext, elementId); - return response.isSuccessful() ? Optional.ofNullable(response.getValue()) : Optional.empty(); + return Optional.ofNullable(connector.getElementInfo(context, elementContext, elementId)); } @Override public Optional getElement(SessionContext context, ElementContext elementContext, String elementId) { - Response response = connector.getElement(context, elementContext, new Id(elementId)); - return response.isSuccessful() ? Optional.ofNullable(response.getValue()) : Optional.empty(); + return Optional.ofNullable(connector.getElement(context, elementContext, new Id(elementId))); } @Override @@ -82,16 +73,14 @@ public class ZusammenAdaptorImpl implements ZusammenAdaptor { public Collection listElementData(SessionContext context, ElementContext elementContext, Id parentElementId) { - Collection elementInfoList = connector.listElements(context, elementContext, parentElementId); - if (elementInfoList != null) { - return elementInfoList.stream().map(elementInfo -> connector.getElement(context, - elementContext, elementInfo.getId()).getValue()).collect(Collectors.toList()); - } - - return new ArrayList<>(); + return elementInfoList == null + ? new ArrayList<>() + : elementInfoList.stream() + .map(elementInfo -> connector.getElement(context, elementContext, elementInfo.getId())) + .collect(Collectors.toList()); } @@ -119,12 +108,24 @@ public class ZusammenAdaptorImpl implements ZusammenAdaptor { } @Override - public Optional saveElement(SessionContext context, ElementContext elementContext, - ZusammenElement element, String message) { + 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) { @@ -160,20 +161,14 @@ public class ZusammenAdaptorImpl implements ZusammenAdaptor { .findFirst(); } - private void logErrorMessageToMdc(ItemElementLoggerTargetServiceName - itemElementLoggerTargetServiceName, - ReturnCode returnCode) { - logErrorMessageToMdc(itemElementLoggerTargetServiceName, returnCode.toString()); + @Override + public Collection listItems(SessionContext context) { + return connector.listItems(context); } - private void logErrorMessageToMdc(ItemElementLoggerTargetServiceName - itemElementLoggerTargetServiceName, - String message) { - MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - itemElementLoggerTargetServiceName.getDescription(), - ErrorLevel.ERROR.name(), - LoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode(), - message); + @Override + public Item getItem(SessionContext context, Id itemId) { + return connector.getItem(context, itemId); } @Override @@ -182,15 +177,52 @@ public class ZusammenAdaptorImpl implements ZusammenAdaptor { } @Override - public Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData - itemVersionData) { - return connector.createVersion(context, itemId, baseVersionId, itemVersionData); + public void updateItem(SessionContext context, Id itemId, Info info) { + connector.updateItem(context, itemId, info); + } + @Override + public Optional getFirstVersion(SessionContext context, Id itemId) { + Collection versions = connector.listPublicVersions(context, itemId); + if (versions == null || versions.size() == 0) { + return Optional.empty(); + } + List itemVersions = new ArrayList<>(versions); + sortItemVersionListByModificationTimeDescOrder(itemVersions); + ItemVersion itemVersion = itemVersions.iterator().next(); + + return Optional.ofNullable(itemVersion); } @Override - public Collection listItems(SessionContext context) { - return connector.listItems(context); + 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 @@ -210,25 +242,96 @@ public class ZusammenAdaptorImpl implements ZusammenAdaptor { connector.resetVersionHistory(context, itemId, versionId, changeRef); } + /*@Override + public void revertVersionToRevision(SessionContext context, Id itemId, Id versionId, + Id revisionId) { + connector.resetVersionRevision(context, itemId, versionId, revisionId); + }*/ + + /*@Override + public ItemVersionRevisions listVersionRevisions(SessionContext context, Id itemId, Id + versionId) { + return connector.listVersionRevisions(context, itemId, versionId); + }*/ + @Override - public void updateItem(SessionContext context, Id itemId, Info info) { - connector.updateItem(context, itemId, info); + 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 Collection checkHealth(SessionContext context) { return connector.checkHealth(context); } - private static void sortItemVersionListByModificationTimeDescOrder( - List itemVersions) { - itemVersions.sort((o1, o2) -> ((Integer)o2.getId().getValue().length()) - .compareTo( (o1.getId().getValue().length()))); - } - @Override public String getVersion(SessionContext sessionContext) { return connector.getVersion(sessionContext); } + + @Override + public void revert(SessionContext sessionContext, String itemId, String versionId, + String revisionId) { + connector.revertVersionRevision(sessionContext, new Id(itemId), new Id(versionId), + new Id(revisionId)); + } + + @Override + public List listRevisions(SessionContext sessionContext, String itemId, + String versionId) { + List revisions = new ArrayList<>(); + ItemVersionRevisions itemVersionRevisions = + connector.listVersionRevisions(sessionContext, new Id(itemId), new Id + (versionId)); + if(itemVersionRevisions == null || itemVersionRevisions.getItemVersionRevisions()==null || + itemVersionRevisions.getItemVersionRevisions().size()==0) { + return revisions; + } + else{ + revisions = itemVersionRevisions.getItemVersionRevisions().stream().map + (revision -> { + Revision rev = new Revision(); + rev.setId(revision.getRevisionId().getValue()); + rev.setTime(revision.getTime()); + rev.setUser(revision.getUser()); + rev.setMessage(revision.getMessage()); + return rev; + }).collect(Collectors.toList()); + revisions.sort(new Comparator() { + @Override + public int compare(Revision o1, Revision o2) { + if(o1.getTime().before(o2.getTime())) return 1; + else return -1; + } + }); + // when creating a new item an initial version is created with + // invalid data. this revision is not an applicable revision. + //the logic of identifying this revision is: + //1- only the first version of item has this issue + //2- only in the first item version there are 2 revisions created + //3- the second revision is in format "Initial {vlm/vsp}: {name of the vlm/vsp} + //4- only if a revision in this format exists we remove the first revision. + if(revisions.size()>1 && revisions.get(revisions.size()-2).getMessage().matches("Initial " + + ".*:.*")){ + revisions.remove(revisions.size()-1); + } + return revisions; + } + } + + private static void sortItemVersionListByModificationTimeDescOrder( + List itemVersions) { + itemVersions.sort((o1, o2) -> ((Integer) o2.getId().getValue().length()) + .compareTo((o1.getId().getValue().length()))); + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/pom.xml index fba7d568e3..f8cfcfdc9b 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/pom.xml +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/pom.xml @@ -33,5 +33,32 @@ zusammen-state-store-cassandra-plugin ${zusammen-state-store.version} + + org.testng + testng + ${testng.version} + test + + + org.mockito + mockito-all + ${mockito.all.version} + test + + + com.amdocs.zusammen + zusammen-commons-utils + ${zusammen.version} + + + org.openecomp.sdc.core + openecomp-facade-api + ${project.version} + + + org.openecomp.sdc.core + openecomp-session-lib + ${project.version} + diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/ZusammenPluginUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/ZusammenPluginUtil.java index 59afa70e9a..a973590eb5 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/ZusammenPluginUtil.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/ZusammenPluginUtil.java @@ -19,13 +19,30 @@ package org.openecomp.core.zusammen.plugin; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.Space; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import com.amdocs.zusammen.datatypes.item.ItemVersionChange; +import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import com.amdocs.zusammen.datatypes.item.ItemVersionDataConflict; import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElementChange; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElementConflict; +import com.amdocs.zusammen.sdk.state.types.StateElement; +import com.amdocs.zusammen.sdk.types.ElementDescriptor; import com.amdocs.zusammen.utils.fileutils.FileUtils; +import com.amdocs.zusammen.utils.fileutils.json.JsonUtil; import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.Date; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; public class ZusammenPluginUtil { @@ -34,7 +51,7 @@ public class ZusammenPluginUtil { case PUBLIC: return ZusammenPluginConstants.PUBLIC_SPACE; case PRIVATE: - return ZusammenPluginUtil.getPrivateSpaceName(context); + return getPrivateSpaceName(context); default: throw new IllegalArgumentException(String.format("Space %s is not supported.", space)); } @@ -44,14 +61,54 @@ public class ZusammenPluginUtil { return context.getUser().getUserName(); } - public static ElementEntity getElementEntity(CollaborationElement element) { + public static ElementContext getPrivateElementContext(ElementContext elementContext) { + return new ElementContext(elementContext.getItemId(),elementContext.getVersionId(),Id.ZERO); + } + + + public static VersionEntity convertToVersionEntity(Id versionId, Id baseVersionId, + Date creationTime, + Date modificationTime) { + + return convertToVersionEntity(versionId, null, baseVersionId, + creationTime, modificationTime); + } + + public static VersionEntity convertToVersionEntity(Id versionId, Id revisionId, Id baseVersionId, + Date creationTime, + Date modificationTime) { + VersionEntity version = new VersionEntity(versionId); + version.setBaseId(baseVersionId); + version.setCreationTime(creationTime); + version.setModificationTime(modificationTime); + return version; + } + + public static ItemVersion convertToItemVersion(VersionEntity versionEntity, + ItemVersionData itemVersionData) { + ItemVersion itemVersion = new ItemVersion(); + itemVersion.setId(versionEntity.getId()); + + itemVersion.setBaseId(versionEntity.getBaseId()); + itemVersion.setCreationTime(versionEntity.getCreationTime()); + itemVersion.setModificationTime(versionEntity.getModificationTime()); + itemVersion.setData(itemVersionData); + return itemVersion; + } + + public static ElementEntity convertToElementEntity(CollaborationElement element) { + ElementEntity elementEntity = new ElementEntity(element.getId()); elementEntity.setNamespace(element.getNamespace()); elementEntity.setParentId(element.getParentId() == null - ? ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID + ? ROOT_ELEMENTS_PARENT_ID : element.getParentId()); + + elementEntity.setInfo(element.getInfo()); + elementEntity.setRelations(element.getRelations()); + if (element.getData() != null) { elementEntity.setData(ByteBuffer.wrap(FileUtils.toByteArray(element.getData()))); } @@ -63,21 +120,29 @@ public class ZusammenPluginUtil { elementEntity.setVisualization( ByteBuffer.wrap(FileUtils.toByteArray(element.getVisualization()))); } + elementEntity.setElementHash(new Id(calculateElementHash(elementEntity))); + return elementEntity; } - public static CollaborationElement getCollaborationElement( - ElementEntityContext elementEntityContext, ElementEntity elementEntity) { - Id parentId = - ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID.equals(elementEntity.getParentId()) - ? null - : elementEntity.getParentId(); - CollaborationElement element = new CollaborationElement(elementEntityContext.getItemId(), - elementEntityContext.getVersionId(), elementEntity.getNamespace(), elementEntity.getId()); + public static ElementDescriptor convertToElementDescriptor( + ElementContext elementContext, ElementEntity elementEntity) { + if (elementEntity == null) { + return null; + } + ElementDescriptor element = new ElementDescriptor(elementContext.getItemId(), + elementContext.getVersionId(), elementEntity.getNamespace(), elementEntity.getId()); - element.setParentId(parentId); - element.setInfo(elementEntity.getInfo()); - element.setRelations(elementEntity.getRelations()); + mapElementEntityToDescriptor(elementEntity, element); + return element; + } + + public static CollaborationElement convertToCollaborationElement( + ElementContext elementContext, ElementEntity elementEntity) { + CollaborationElement element = new CollaborationElement(elementContext.getItemId(), + elementContext.getVersionId(), elementEntity.getNamespace(), elementEntity.getId()); + + mapElementEntityToDescriptor(elementEntity, element); if (elementEntity.getData() != null) { element.setData(new ByteArrayInputStream(elementEntity.getData().array())); @@ -89,7 +154,134 @@ public class ZusammenPluginUtil { if (elementEntity.getVisualization() != null) { element.setVisualization(new ByteArrayInputStream(elementEntity.getVisualization().array())); } + return element; + } + + public static CollaborationElementChange convertToElementChange( + ElementContext changedElementContext, ElementEntity changedElement, Action action) { + CollaborationElementChange elementChange = new CollaborationElementChange(); + elementChange.setElement(convertToCollaborationElement(changedElementContext, changedElement)); + elementChange.setAction(action); + return elementChange; + } + + public static ItemVersionChange convertToVersionChange(ElementContext elementContext, + ElementEntity versionDataElement, + Action action) { + ItemVersionChange versionChange = new ItemVersionChange(); + + ItemVersion itemVersion = new ItemVersion(); + itemVersion.setId(elementContext.getVersionId()); + + itemVersion.setData(convertToVersionData(versionDataElement)); + + versionChange.setItemVersion(itemVersion); + versionChange.setAction(action); + return versionChange; + } + + public static ItemVersionDataConflict getVersionConflict(ElementEntity localVesionData, + ElementEntity remoteVersionData) { + ItemVersionDataConflict versionConflict = new ItemVersionDataConflict(); + versionConflict.setLocalData(convertToVersionData(localVesionData)); + versionConflict.setRemoteData(convertToVersionData(remoteVersionData)); + return versionConflict; + } + + public static CollaborationElementConflict getElementConflict(ElementContext elementContext, + ElementEntity localElement, + ElementEntity remoteElement) { + CollaborationElementConflict elementConflict = new CollaborationElementConflict(); + elementConflict + .setLocalElement(convertToCollaborationElement(elementContext, localElement)); + elementConflict.setRemoteElement( + convertToCollaborationElement(elementContext, remoteElement)); + return elementConflict; + } + + public static ItemVersionData convertToVersionData(ElementEntity versionDataElement) { + ItemVersionData versionData = new ItemVersionData(); + versionData.setInfo(versionDataElement.getInfo()); + versionData.setRelations(versionDataElement.getRelations()); + return versionData; + } + + private static void mapElementEntityToDescriptor(ElementEntity elementEntity, + ElementDescriptor elementDescriptor) { + Id parentId = ROOT_ELEMENTS_PARENT_ID.equals(elementEntity.getParentId()) + ? null + : elementEntity.getParentId(); + + elementDescriptor.setParentId(parentId); + elementDescriptor.setInfo(elementEntity.getInfo()); + elementDescriptor.setRelations(elementEntity.getRelations()); + elementDescriptor.setSubElements(elementEntity.getSubElementIds()); + } + + public static String calculateElementHash(ElementEntity elementEntity) { + StringBuffer elementHash = new StringBuffer(); + if (elementEntity.getData() != null) { + elementHash.append(calculateSHA1(elementEntity.getData().array())); + } else { + elementHash.append("0"); + } + elementHash.append("_"); + if (elementEntity.getVisualization() != null) { + elementHash.append(calculateSHA1(elementEntity.getVisualization().array())); + } else { + elementHash.append("0"); + } + elementHash.append("_"); + + if (elementEntity.getSearchableData() != null) { + elementHash.append(calculateSHA1(elementEntity.getSearchableData().array())); + } else { + elementHash.append("0"); + } + elementHash.append("_"); + + if (elementEntity.getInfo() != null) { + elementHash.append(calculateSHA1(JsonUtil.object2Json(elementEntity.getInfo()).getBytes())); + } else { + elementHash.append("0"); + } + elementHash.append("_"); + + if (elementEntity.getRelations() != null) { + elementHash + .append(calculateSHA1(JsonUtil.object2Json(elementEntity.getRelations()).getBytes())); + } else { + elementHash.append("0"); + } + + return elementHash.toString(); + } + + private static String calculateSHA1(byte[] content2Convert) { + MessageDigest md = null; + try { + md = MessageDigest.getInstance("SHA-1"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return Base64.getEncoder().encodeToString(md.digest(content2Convert)); + } + + + public static StateElement getStateElement(ElementContext elementContext, ElementEntity + elementEntity) { + Id parentId = ROOT_ELEMENTS_PARENT_ID.equals(elementEntity.getParentId()) + ? null + : elementEntity.getParentId(); + StateElement element = new StateElement(elementContext.getItemId(), + elementContext.getVersionId(), elementEntity.getNamespace(), elementEntity.getId()); + + element.setParentId(parentId); + element.setInfo(elementEntity.getInfo()); + element.setRelations(elementEntity.getRelations()); element.setSubElements(elementEntity.getSubElementIds()); return element; } + + } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/CommitStagingService.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/CommitStagingService.java new file mode 100644 index 0000000000..45d5769e9c --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/CommitStagingService.java @@ -0,0 +1,100 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Collection; +import java.util.Optional; + +public class CommitStagingService { + + private VersionPrivateStore versionPrivateStore; + private VersionStageStore versionStageStore; + private ElementPrivateStore elementPrivateStore; + private ElementStageStore elementStageStore; + + public CommitStagingService(VersionPrivateStore versionPrivateStore, + VersionStageStore versionStageStore, + ElementPrivateStore elementPrivateStore, + ElementStageStore elementStageStore) { + this.versionPrivateStore = versionPrivateStore; + this.versionStageStore = versionStageStore; + this.elementPrivateStore = elementPrivateStore; + this.elementStageStore = elementStageStore; + } + + public void commitStaging(SessionContext context, Id itemId, Id versionId) { + Optional> versionStage = + versionStageStore.get(context, itemId, new VersionEntity(versionId)); + + final ElementContext elementContext = new ElementContext(itemId, versionId, Id.ZERO); + Collection stagedElementIds = elementStageStore.listIds(context, elementContext); + + if ((!versionStage.isPresent() && stagedElementIds.isEmpty()) || + elementStageStore.hasConflicts(context, elementContext)) { + return; + } + + versionStage.ifPresent(verStage -> commitVersionStage(context, itemId, verStage)); + commitElementsStage(context, elementContext, stagedElementIds); + } + + private void commitVersionStage(SessionContext context, Id itemId, + StageEntity versionStage) { + switch (versionStage.getAction()) { + case CREATE: + versionPrivateStore.commitStagedCreate(context, itemId, versionStage.getEntity(), + versionStage.getPublishTime()); + break; + case UPDATE: + versionPrivateStore.commitStagedUpdate(context, itemId, versionStage.getEntity(), + versionStage.getPublishTime()); + break; + case IGNORE: + versionPrivateStore.commitStagedIgnore(context, itemId, versionStage.getEntity(), + versionStage.getPublishTime()); + break; + default: + throw new UnsupportedOperationException( + "Version change other then Create/Update/Ignore is not supported"); + } + + versionStageStore.delete(context, itemId, versionStage.getEntity()); + } + + private void commitElementsStage(SessionContext context, ElementContext elementContext, + Collection stagedElementIds) { + for (ElementEntity stagedElementId : stagedElementIds) { + StageEntity stagedElement = + elementStageStore.get(context, elementContext, stagedElementId) + .orElseThrow( + () -> new IllegalStateException("Element id returned by list must exist")); + switch (stagedElement.getAction()) { + case CREATE: + elementPrivateStore.commitStagedCreate(context, elementContext, stagedElement.getEntity(), + stagedElement.getPublishTime()); + break; + case UPDATE: + elementPrivateStore.commitStagedUpdate(context, elementContext, stagedElement.getEntity(), + stagedElement.getPublishTime()); + break; + case DELETE: + elementPrivateStore + .commitStagedDelete(context, elementContext, stagedElement.getEntity()); + break; + case IGNORE: + elementPrivateStore.commitStagedIgnore(context, elementContext, stagedElement.getEntity(), + stagedElement.getPublishTime()); + break; + default: + throw new UnsupportedOperationException( + "Element change other then Create/Update/Delete/Ignore is not supported"); + } + elementStageStore.delete(context, elementContext, stagedElement.getEntity()); + } + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementCollaborationStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementCollaborationStore.java deleted file mode 100644 index ac103c0fbf..0000000000 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementCollaborationStore.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.openecomp.core.zusammen.plugin.collaboration; - -import com.amdocs.zusammen.datatypes.Id; -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.zusammen.plugin.ZusammenPluginConstants; -import org.openecomp.core.zusammen.plugin.ZusammenPluginUtil; -import org.openecomp.core.zusammen.plugin.dao.ElementRepository; -import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; -import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Optional; - -import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getCollaborationElement; -import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getSpaceName; - - -public class ElementCollaborationStore { - - private static final String SUB_ELEMENT_NOT_EXIST_ERROR_MSG = - "List sub elements error: item %s, version %s - " + - "element %s, which appears as sub element of element %s, does not exist"; - - public Collection listElements(SessionContext context, - ElementContext elementContext, - Id elementId) { - ElementEntityContext elementEntityContext = - new ElementEntityContext(ZusammenPluginUtil.getPrivateSpaceName(context), elementContext); - - if (elementId == null) { - elementId = ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; - } - - ElementRepository elementRepository = getElementRepository(context); - String elementIdValue = elementId.getValue(); - String versionIdValue = elementContext.getChangeRef() == null - ? elementContext.getVersionId().getValue() - : elementContext.getChangeRef(); - Collection subElements = new ArrayList<>(); - - Optional element = - elementRepository.get(context, elementEntityContext, new ElementEntity(elementId)); - if (element.isPresent() && element.get().getSubElementIds() != null) { - for (Id subElementId : element.get().getSubElementIds()) { - ElementEntity subElement = - elementRepository.get(context, elementEntityContext, new ElementEntity(subElementId)) - .orElseThrow( - () -> new IllegalStateException(String.format(SUB_ELEMENT_NOT_EXIST_ERROR_MSG, - elementContext.getItemId().getValue(), versionIdValue, - subElementId.getValue(), elementIdValue))); - subElements.add(getCollaborationElement(elementEntityContext, subElement)); - } - } - return subElements; - } - - public CollaborationElement getElement(SessionContext context, ElementContext elementContext, - Id elementId) { - ElementEntityContext elementEntityContext = - new ElementEntityContext(ZusammenPluginUtil.getPrivateSpaceName(context), elementContext); - return getElementRepository(context) - .get(context, elementEntityContext, new ElementEntity(elementId)) - .map(elementEntity -> getCollaborationElement(elementEntityContext, elementEntity)) - .orElse(null); - } - - public void createElement(SessionContext context, CollaborationElement element) { - getElementRepository(context) - .create(context, - new ElementEntityContext(getSpaceName(context, element.getSpace()), - element.getItemId(), element.getVersionId()), - ZusammenPluginUtil.getElementEntity(element)); - } - - public void updateElement(SessionContext context, CollaborationElement element) { - getElementRepository(context) - .update(context, - new ElementEntityContext(getSpaceName(context, element.getSpace()), - element.getItemId(), element.getVersionId()), - ZusammenPluginUtil.getElementEntity(element)); - } - - public void deleteElement(SessionContext context, CollaborationElement element) { - deleteElementHierarchy(getElementRepository(context), - context, - new ElementEntityContext(getSpaceName(context, element.getSpace()), - element.getItemId(), element.getVersionId()), - ZusammenPluginUtil.getElementEntity(element)); - } - - public boolean checkHealth(SessionContext sessionContext) { - return getElementRepository(sessionContext).checkHealth(sessionContext); - } - - private void deleteElementHierarchy(ElementRepository elementRepository, SessionContext context, - ElementEntityContext elementEntityContext, - ElementEntity elementEntity) { - Optional retrieved = - elementRepository.get(context, elementEntityContext, elementEntity); - if (!retrieved.isPresent()) { - return; - } - retrieved.get().getSubElementIds().stream() - .map(ElementEntity::new) - .forEach(subElementEntity -> deleteElementHierarchy( - elementRepository, context, elementEntityContext, subElementEntity)); - - // only for the first one the parentId will populated (so it'll be removed from its parent) - elementRepository.delete(context, elementEntityContext, elementEntity); - } - - protected ElementRepository getElementRepository(SessionContext context) { - return ElementRepositoryFactory.getInstance().createInterface(context); - } -} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPrivateStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPrivateStore.java new file mode 100644 index 0000000000..045def2561 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPrivateStore.java @@ -0,0 +1,48 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Collection; +import java.util.Date; +import java.util.Map; +import java.util.Optional; + +public interface ElementPrivateStore extends ElementStore { + + Map listIds(SessionContext context, ElementContext elementContext); + + Collection listSubs(SessionContext context, ElementContext elementContext, + Id elementId); + + Optional getSynchronizationState(SessionContext context, + ElementContext elementContext, + Id elementId); + + void create(SessionContext context, ElementContext elementContext, ElementEntity element); + + boolean update(SessionContext context, ElementContext elementContext, ElementEntity element); + + void delete(SessionContext context, ElementContext elementContext, ElementEntity element); + + void markAsPublished(SessionContext context, ElementContext elementContext, Id elementId, + Date publishTime); + + void markDeletionAsPublished(SessionContext context, ElementContext elementContext, Id elementId, + Date publishTime); + + void commitStagedCreate(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime); + + void commitStagedUpdate(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime); + + void commitStagedDelete(SessionContext context, ElementContext elementContext, + ElementEntity element); + + void commitStagedIgnore(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPublicStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPublicStore.java new file mode 100644 index 0000000000..0f1790a1bf --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPublicStore.java @@ -0,0 +1,23 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; + +import java.util.Date; +import java.util.Map; + +public interface ElementPublicStore extends ElementStore { + + void create(SessionContext context, ElementContext elementContext, ElementEntity element, + Date publishTime); + + void update(SessionContext context, ElementContext elementContext, ElementEntity element, + Date publishTime); + + void delete(SessionContext context, ElementContext elementContext, ElementEntity element, + Date publishTime); + + Map listIds(SessionContext context, ElementContext elementContext); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStageStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStageStore.java new file mode 100644 index 0000000000..a9236247f9 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStageStore.java @@ -0,0 +1,35 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.Resolution; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; + +import java.util.Collection; +import java.util.Optional; + +public interface ElementStageStore { + + Collection listIds(SessionContext context, ElementContext elementContext); + + boolean hasConflicts(SessionContext context, ElementContext elementContext); + + Collection> listConflictedDescriptors(SessionContext context, + ElementContext elementContext); + + Optional> get(SessionContext context, ElementContext elementContext, + ElementEntity element); + + Optional> getConflicted(SessionContext context, + ElementContext elementContext, + ElementEntity element); + + void create(SessionContext context, ElementContext elementContext, + StageEntity elementStage); + + void delete(SessionContext context, ElementContext elementContext, ElementEntity element); + + void resolveConflict(SessionContext context, ElementContext elementContext, ElementEntity element, + Resolution resolution); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStore.java new file mode 100644 index 0000000000..1c26a817ae --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStore.java @@ -0,0 +1,20 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Collection; +import java.util.Optional; + +public interface ElementStore { + Optional get(SessionContext context, ElementContext elementContext, Id elementId); + + Optional getDescriptor(SessionContext context, ElementContext elementContext, + Id elementId); + + Collection listSynchronizationStates(SessionContext context, + ElementContext elementContext); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ErrorCode.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ErrorCode.java new file mode 100644 index 0000000000..3d0910072c --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ErrorCode.java @@ -0,0 +1,5 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +public class ErrorCode { + public static final int NO_CHANGES_TO_PUBLISH = 60000; +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/Message.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/Message.java new file mode 100644 index 0000000000..2816974307 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/Message.java @@ -0,0 +1,6 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +public class Message { + public static final String NO_CHANGES_TO_PUBLISH = + "Item Id %s, version Id %s: There are no changes to publish."; +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/PublishService.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/PublishService.java new file mode 100644 index 0000000000..7b043c830f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/PublishService.java @@ -0,0 +1,201 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +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 com.amdocs.zusammen.datatypes.response.ReturnCode; +import com.amdocs.zusammen.datatypes.response.ZusammenException; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeChange; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationPublishResult; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Collection; +import java.util.Date; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +import static com.amdocs.zusammen.datatypes.response.Module.ZCSP; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToElementChange; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToVersionChange; +import static org.openecomp.core.zusammen.plugin.collaboration.ErrorCode.NO_CHANGES_TO_PUBLISH; + +public class PublishService { + // TODO: 6/29/2017 throw ZusammenException with ReturnCode when needed. + private static final String PUSH_NON_EXISTING_VERSION = + "Item Id %s, version Id %s: Non existing version cannot be pushed."; + + private VersionPublicStore versionPublicStore; + private VersionPrivateStore versionPrivateStore; + private ElementPublicStore elementPublicStore; + private ElementPrivateStore elementPrivateStore; + + public PublishService(VersionPublicStore versionPublicStore, + VersionPrivateStore versionPrivateStore, + ElementPublicStore elementPublicStore, + ElementPrivateStore elementPrivateStore) { + this.versionPublicStore = versionPublicStore; + this.versionPrivateStore = versionPrivateStore; + this.elementPublicStore = elementPublicStore; + this.elementPrivateStore = elementPrivateStore; + } + + public CollaborationPublishResult publish(SessionContext context, Id itemId, Id versionId, + String message) { + CollaborationPublishResult result = new CollaborationPublishResult(); + result.setChange(new CollaborationMergeChange()); + + Date publishTime = new Date(); + Id revisionId = new Id(UUID.randomUUID().toString()); + boolean versionFirstPublication = publishVersion(context, itemId, versionId, revisionId, + publishTime,message); + if (versionFirstPublication) { + publishAllElements(context, new ElementContext(itemId, versionId, revisionId), publishTime, + result); + } else { + publishDirtyElements(context, new ElementContext(itemId, versionId, revisionId), publishTime, + result); + } + return result; + } + + private boolean publishVersion(SessionContext context, Id itemId, Id versionId, Id revisionId, + Date publishTime, String message) { + SynchronizationStateEntity privateVersionSyncState = + versionPrivateStore.getSynchronizationState(context, itemId, versionId) + .orElseThrow(() -> new IllegalArgumentException( + String.format(PUSH_NON_EXISTING_VERSION, itemId.toString(), versionId.toString()))); + + if (!privateVersionSyncState.isDirty()) { + throw new ZusammenException(new ReturnCode(NO_CHANGES_TO_PUBLISH, ZCSP, + String.format(Message.NO_CHANGES_TO_PUBLISH, itemId, versionId), null)); + } + + Optional publicVersionSyncState = + versionPublicStore.getSynchronizationState(context, itemId, versionId); + + // private must be synced with public (if public exists) + if (publicVersionSyncState.isPresent() && + !privateVersionSyncState.getPublishTime() + .equals(publicVersionSyncState.get().getPublishTime())) { + // should not happen as it is validated in zusammen-core + throw new UnsupportedOperationException("Out of sync item version can not be publish"); + } + + boolean versionFirstPublication; + Map versionElementIds = + elementPublicStore.listIds(context, new ElementContext(itemId, + versionId)); + if (publicVersionSyncState.isPresent()) { + versionPublicStore.update(context, itemId, new VersionEntity(versionId), revisionId, + versionElementIds,publishTime,message); + versionFirstPublication = false; + } else { + VersionEntity privateVersion = versionPrivateStore.get(context, itemId, versionId) + .orElseThrow(() -> new IllegalArgumentException( + String.format(PUSH_NON_EXISTING_VERSION, itemId.toString(), versionId.toString()))); + versionPublicStore.create(context, itemId, privateVersion, revisionId,versionElementIds, + publishTime,message); + versionFirstPublication = true; + } + versionPrivateStore.markAsPublished(context, itemId, versionId, publishTime); + return versionFirstPublication; + } + + private void publishAllElements(SessionContext context, ElementContext elementContext, + Date publishTime, CollaborationPublishResult result) { + Collection privateElementSyncStates = + elementPrivateStore.listSynchronizationStates(context, elementContext); + + for (SynchronizationStateEntity privateElementSyncState : privateElementSyncStates) { + Optional privateElement = + elementPrivateStore.get(context, elementContext, privateElementSyncState.getId()); + + if (!privateElement.isPresent()) { + continue; + } + ElementEntity elementToPublish = privateElement.get(); + + elementPublicStore.create(context, elementContext, elementToPublish, + privateElementSyncState.isDirty() ? publishTime + : privateElementSyncState.getPublishTime()); + + if (privateElementSyncState.isDirty()) { + elementPrivateStore + .markAsPublished(context, elementContext, privateElementSyncState.getId(), publishTime); + } + updateResult(elementContext, elementToPublish, Action.CREATE, + ROOT_ELEMENTS_PARENT_ID.equals(privateElementSyncState.getId()), result); + } + } + + private void publishDirtyElements(SessionContext context, ElementContext elementContext, + Date publishTime, CollaborationPublishResult result) { + + Id revisionId = elementContext.getRevisionId(); + elementContext.setRevisionId(revisionId); + ElementContext privateElementContext = new ElementContext(elementContext.getItemId(), + elementContext.getVersionId(),Id.ZERO); + Collection privateElementSyncStates = + elementPrivateStore.listSynchronizationStates(context, elementContext); + + Collection publicElementSyncStates = + elementPublicStore.listSynchronizationStates(context, elementContext); + + for (SynchronizationStateEntity privateElementSyncState : privateElementSyncStates) { + if (!privateElementSyncState.isDirty()) { + continue; + } + + Optional privateElement = + elementPrivateStore.get(context, privateElementContext, privateElementSyncState.getId()); + + ElementEntity elementToPublish; + Action actionOnPublic; + if (privateElement.isPresent()) { + elementToPublish = privateElement.get(); + + if (publicElementSyncStates.contains(privateElementSyncState)) { + + elementPublicStore.update(context, elementContext, elementToPublish, publishTime); + actionOnPublic = Action.UPDATE; + } else { + elementPublicStore.create(context, elementContext, elementToPublish, publishTime); + actionOnPublic = Action.CREATE; + } + + elementPrivateStore + .markAsPublished(context, privateElementContext, privateElementSyncState.getId(), publishTime); + } else { + elementToPublish = + elementPublicStore.get(context, elementContext, privateElementSyncState.getId()) + .orElseThrow(() -> new IllegalStateException( + "Element that should be deleted from public must exist there")); + elementPublicStore.delete(context, elementContext, elementToPublish, publishTime); + actionOnPublic = Action.DELETE; + + elementPrivateStore + .markDeletionAsPublished(context, privateElementContext, privateElementSyncState.getId(), + publishTime); + } + + updateResult(elementContext, elementToPublish, actionOnPublic, + ROOT_ELEMENTS_PARENT_ID.equals(privateElementSyncState.getId()), result); + } + } + + private void updateResult(ElementContext elementContext, ElementEntity element, + Action action, boolean versionDataElement, + CollaborationPublishResult result) { + if (versionDataElement) { + result.getChange().setChangedVersion(convertToVersionChange(elementContext, element, action)); + } else { + result.getChange().getChangedElements() + .add(convertToElementChange(elementContext, element, action)); + } + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/RevertService.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/RevertService.java new file mode 100644 index 0000000000..0d2ea2c0d8 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/RevertService.java @@ -0,0 +1,161 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public class RevertService { + + private ElementPublicStore elementPublicStore; + private ElementPrivateStore elementPrivateStore; + + public RevertService(ElementPublicStore elementPublicStore, + ElementPrivateStore elementPrivateStore) { + this.elementPublicStore = elementPublicStore; + this.elementPrivateStore = elementPrivateStore; + } + + public void revert(SessionContext context, Id itemId, Id versionId, Id revisionId) { + ElementContext targetContext = new ElementContext(itemId, versionId); + ElementContext sourceContext = new ElementContext(itemId, versionId, revisionId); + copyElementsFromPublic(context, sourceContext, targetContext); + } + + private void copyElementsFromPublic(SessionContext context, ElementContext sourceContext, + ElementContext targetContext) { + Collection revertElementActions = + evaluateRevertElementActions(context, sourceContext, targetContext); + + revertElementActions.forEach(revertElementAction -> revertElementAction.run(context)); + } + + private Collection evaluateRevertElementActions(SessionContext context, + ElementContext sourceContext, + ElementContext targetContext) { + + Map sourceElements = elementPublicStore.listIds(context, sourceContext); + Map targetPublicElements = elementPublicStore.listIds(context, targetContext); + Collection synchronizationStateEntities = + elementPrivateStore.listSynchronizationStates(context, targetContext); + + Map targetElements = + evaluateTargetElements(targetPublicElements, synchronizationStateEntities); + + + Collection revertElementActions = new ArrayList<>(); + + sourceElements.entrySet().forEach(entry -> { + Id sourceElementId = entry.getKey(); + Id sourceElementRevisionId = entry.getValue(); + + if (!targetElements.containsKey(sourceElementId)) { + revertElementActions + .add(new RevertElementAction(sourceContext, sourceElementId, commands[CREATE])); + } else if (!targetElements.get(sourceElementId).equals(sourceElementRevisionId)) { + revertElementActions + .add(new RevertElementAction(sourceContext, sourceElementId, commands[UPDATE])); + } + }); + + targetElements.entrySet().forEach(entry -> { + Id targetElementId = entry.getKey(); + if (!sourceElements.containsKey(targetElementId)) { + revertElementActions + .add(new RevertElementAction(targetContext, targetElementId, commands[DELETE])); + } + }); + + return revertElementActions; + } + + private Map evaluateTargetElements(Map targetPublicElements, + Collection syncStates) { + Map targetElements = new HashMap<>(targetPublicElements); + syncStates.stream() + .filter(SynchronizationStateEntity::isDirty) + .forEach(syncState -> targetElements.put(syncState.getId(), Id.ZERO)); + return targetElements; + } + + private static class RevertElementAction { + private ElementContext elementContext; + private Id elementId; + private ActionCommand command; + + private RevertElementAction(ElementContext elementContext, Id elementId, + ActionCommand command) { + this.elementContext = elementContext; + this.elementId = elementId; + this.command = command; + } + + public ElementContext getElementContext() { + return elementContext; + } + + public Id getElementId() { + return elementId; + } + + public void run(SessionContext context) { + command.run(context, elementContext, elementId); + } + } + + private interface ActionCommand { + void run(SessionContext context, ElementContext elementContext, Id elementId); + } + + private static int CREATE = 0; + private static int UPDATE = 1; + private static int DELETE = 2; + + private ActionCommand[] commands = {new ActionCommand() { + @Override + public void run(SessionContext context, ElementContext elementContext, Id elementId) { + //create + Optional element = elementPublicStore.get(context, elementContext, elementId); + if (!element.isPresent()) { + throw getMissingElementException(elementContext, elementId); + } + elementPrivateStore.create(context, elementContext, element.get()); + } + }, new ActionCommand() { + @Override + public void run(SessionContext context, ElementContext elementContext, Id elementId) { + //update + Optional element = elementPublicStore.get(context, elementContext, elementId); + if (!element.isPresent()) { + throw getMissingElementException(elementContext, elementId); + } + elementPrivateStore.update(context, elementContext, element.get()); + } + }, new ActionCommand() { + @Override + public void run(SessionContext context, ElementContext elementContext, Id elementId) { + //delete + Optional element = elementPrivateStore.get(context, elementContext, elementId); + if (!element.isPresent()) { + return; // deleted by parent when hierarchy was deleted + } + elementPrivateStore.delete(context, elementContext, element.get()); + } + }}; + + private RuntimeException getMissingElementException(ElementContext elementContext, + Id elementId) { + return new IllegalStateException( + String.format("Item Id %s, version Id %s, revision Id %s: Missing element with Id %s", + elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue(), elementId.getValue()) + ); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/SyncService.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/SyncService.java new file mode 100644 index 0000000000..04a7e9ffb1 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/SyncService.java @@ -0,0 +1,384 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +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 com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeChange; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeConflict; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeResult; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; + +public class SyncService { + private static final String PULL_NON_EXISTING_VERSION = + "Item Id %s, version Id %s: Non existing version cannot be synced."; + private static final String PUBLIC_SYNC_STATE_EXISTS_WITHOUT_ELEMENT = + "Item Id %s, version Id %s: Sync state of element with Id %s " + + "exists in public space while the element does not"; + private static final String PRIVATE_UNPUBLISHED_SYNC_STATE_EXISTS_WITHOUT_ELEMENT = + "Item Id %s, version Id %s: Sync state of unpublished element with Id %s " + + "exists in private space while the element does not"; + + private VersionPublicStore versionPublicStore; + private VersionPrivateStore versionPrivateStore; + private VersionStageStore versionStageStore; + private ElementPublicStore elementPublicStore; + private ElementPrivateStore elementPrivateStore; + private ElementStageStore elementStageStore; + + public SyncService(VersionPublicStore versionPublicStore, + VersionPrivateStore versionPrivateStore, + VersionStageStore versionStageStore, + ElementPublicStore elementPublicStore, + ElementPrivateStore elementPrivateStore, + ElementStageStore elementStageStore) { + this.versionPublicStore = versionPublicStore; + this.versionPrivateStore = versionPrivateStore; + this.versionStageStore = versionStageStore; + this.elementPublicStore = elementPublicStore; + this.elementPrivateStore = elementPrivateStore; + this.elementStageStore = elementStageStore; + } + + public CollaborationMergeResult sync(SessionContext context, Id itemId, Id versionId, + boolean force) { + SynchronizationStateEntity publicVersionSyncState = + versionPublicStore.getSynchronizationState(context, itemId, versionId) + .orElseThrow(() -> new IllegalStateException( + String.format(PULL_NON_EXISTING_VERSION, itemId.toString(), versionId.toString()))); + + Date publishTime = publicVersionSyncState.getPublishTime(); + + Optional privateVersionSyncState = + versionPrivateStore.getSynchronizationState(context, itemId, versionId); + + if (force || !privateVersionSyncState.isPresent() || + !publishTime.equals(privateVersionSyncState.get().getPublishTime())) { + ElementContext elementContext = + new ElementContext(itemId, versionId, publicVersionSyncState.getRevisionId()); + + Collection publicSyncStates = + elementPublicStore.listSynchronizationStates(context, elementContext); + Collection privateSyncStates = + elementPrivateStore.listSynchronizationStates(context, elementContext); + Map publicSyncStateById = toMapById(publicSyncStates); + + Set syncedElements = new HashSet<>(); + if (force) { + List dirtyPrivateSyncStates = privateSyncStates.stream() + .filter(SynchronizationStateEntity::isDirty) + .collect(Collectors.toList()); + + forceSyncDirtyElements(context, elementContext, dirtyPrivateSyncStates, publicSyncStateById, + syncedElements); + } + + if (!privateVersionSyncState.isPresent() || + !publishTime.equals(privateVersionSyncState.get().getPublishTime())) { + syncVersion(context, itemId, versionId, publishTime, privateVersionSyncState.isPresent()); + syncElements(context, elementContext, + privateVersionSyncState.map(SynchronizationStateEntity::getPublishTime).orElse(null), + publicSyncStates, privateSyncStates, publicSyncStateById, syncedElements); + } + } + + return createResult(); + } + + private CollaborationMergeResult createResult() { + CollaborationMergeResult result = new CollaborationMergeResult(); + result.setChange(new CollaborationMergeChange()); + result.setConflict(new CollaborationMergeConflict()); + return result; + } + + private void syncVersion(SessionContext context, Id itemId, Id versionId, Date publishTime, + boolean versionExistOnPrivate) { + if (versionExistOnPrivate) { + stageVersion(context, itemId, new VersionEntity(versionId), Action.UPDATE, publishTime); + } else { + stageVersion(context, itemId, versionPublicStore.get(context, itemId, versionId) + .orElseThrow(() -> new IllegalArgumentException(String + .format(PULL_NON_EXISTING_VERSION, itemId.toString(), versionId.toString()))), + Action.CREATE, publishTime); + } + } + + private void syncElements(SessionContext context, ElementContext elementContext, + Date previousSyncedPublishTime, + Collection publicSyncStates, + Collection privateSyncStates, + Map publicSyncStateById, + Set syncedElements) { + Map privateSyncStateById = toMapById(privateSyncStates); + + Collection updatedPublicSyncStates = + previousSyncedPublishTime == null + ? publicSyncStates + : publicSyncStates.stream() + .filter(syncState -> syncState.getPublishTime().after(previousSyncedPublishTime)) + .collect(Collectors.toList()); + + syncPublicUpdatedElements(context, elementContext, updatedPublicSyncStates, + publicSyncStateById, privateSyncStateById, syncedElements); + + List onlyOnPrivatePublishedSyncStates = + privateSyncStates.stream() + .filter(syncState -> !publicSyncStateById.containsKey(syncState.getId()) && + syncState.getPublishTime() != null) + .collect(Collectors.toList()); + + syncPublicDeletedElements(context, elementContext, onlyOnPrivatePublishedSyncStates, + publicSyncStateById, privateSyncStateById, syncedElements); + } + + private void syncPublicUpdatedElements(SessionContext context, ElementContext elementContext, + Collection updatedPublicSyncStates, + Map publicSyncStateById, + Map privateSyncStateById, + Set syncedElements) { + for (SynchronizationStateEntity publicSyncState : updatedPublicSyncStates) { + if (syncedElements.contains(publicSyncState.getId())) { + continue; + } + + ElementEntity publicElement = + elementPublicStore.get(context, elementContext, publicSyncState.getId()).orElseThrow( + () -> new IllegalStateException(String + .format(PUBLIC_SYNC_STATE_EXISTS_WITHOUT_ELEMENT, + elementContext.getItemId().getValue(), + elementContext.getVersionId().getValue(), + publicSyncState.getId().getValue()))); + + SynchronizationStateEntity privateSyncState = + privateSyncStateById.get(publicSyncState.getId()); + + if (privateSyncState != null) { + if (!privateSyncState.isDirty()) { + // not changed on private + stageElement(context, elementContext, publicElement, + publicSyncState.getPublishTime(), + Action.UPDATE, false, null); + syncedElements.add(publicSyncState.getId()); + } else { + Optional privateElement = + elementPrivateStore.get(context, elementContext, publicSyncState.getId()); + + if (privateElement.isPresent()) { + // updated on private - conflict if it has different hash + stageElement(context, elementContext, publicElement, + publicSyncState.getPublishTime(), Action.UPDATE, + !publicElement.getElementHash().equals(privateElement.get().getElementHash()), + null); + + syncedElements.add(publicSyncState.getId()); + } else { + // deleted on private - conflict tree + Set changeTreeElementIds = + stagePublicElementTree(context, elementContext, publicElement, publicSyncStateById, + (treeElementIds) -> true); + syncedElements.addAll(changeTreeElementIds); + } + } + } else { + // not existing on private - new creation on public + Set changeTreeElementIds = + stagePublicElementTree(context, elementContext, publicElement, publicSyncStateById, + (treeElementIds) -> containsDirty(treeElementIds, privateSyncStateById)); + syncedElements.addAll(changeTreeElementIds); + } + } + } + + private void syncPublicDeletedElements( + SessionContext context, ElementContext elementContext, + Collection onlyOnPrivatePublishedSyncStates, + Map publicSyncStateById, + Map privateSyncStateById, + Set syncedElements) { + for (SynchronizationStateEntity privateSyncState : onlyOnPrivatePublishedSyncStates) { + if (syncedElements.contains(privateSyncState.getId())) { + continue; + } + + Optional privateElement = + elementPrivateStore.get(context, elementContext, privateSyncState.getId()); + + if (!privateElement.isPresent()) { + // deleted on private as well + stageElement(context, elementContext, new ElementEntity(privateSyncState.getId()), + null, Action.DELETE, false, null); + syncedElements.add(privateSyncState.getId()); + } else { + Set changeTreeElementIds = + stageElementTree(context, elementContext, privateElement.get(), + elementPrivateStore, publicSyncStateById::containsKey, + (treeElementIds) -> containsDirty(treeElementIds, privateSyncStateById), + (elementId) -> null, Action.DELETE); + syncedElements.addAll(changeTreeElementIds); + } + } + } + + private void forceSyncDirtyElements(SessionContext context, ElementContext elementContext, + List dirtyPrivateSyncStates, + Map publicSyncStateById, + Set syncedElements) { + for (SynchronizationStateEntity privateSyncState : dirtyPrivateSyncStates) { + Optional privateElement = + elementPrivateStore.get(context, elementContext, privateSyncState.getId()); + if (privateSyncState.getPublishTime() == null) { + stageElement(context, elementContext, + privateElement.orElseThrow(() -> new IllegalStateException( + String.format(PRIVATE_UNPUBLISHED_SYNC_STATE_EXISTS_WITHOUT_ELEMENT, + elementContext.getItemId().getValue(), + elementContext.getVersionId().getValue(), + privateSyncState.getId().getValue()))), + null, Action.DELETE, false, null); + } else { + SynchronizationStateEntity publicSyncState = + publicSyncStateById.get(privateSyncState.getId()); + if (publicSyncState != null) { + ElementEntity publicElement = + elementPublicStore.get(context, elementContext, privateSyncState.getId()).orElseThrow( + () -> new IllegalStateException(String + .format(PUBLIC_SYNC_STATE_EXISTS_WITHOUT_ELEMENT, + elementContext.getItemId().getValue(), + elementContext.getVersionId().getValue(), + privateSyncState.getId().getValue()))); + + stageElement(context, elementContext, publicElement, publicSyncState.getPublishTime(), + privateElement.isPresent() ? Action.UPDATE : Action.CREATE, false, null); + } else { + stageElement(context, elementContext, privateElement.isPresent() + ? privateElement.get() + : new ElementEntity(privateSyncState.getId()), + null, Action.DELETE, false, null); + } + } + syncedElements.add(privateSyncState.getId()); + } + } + + private Set stagePublicElementTree(SessionContext context, + ElementContext elementContext, + ElementEntity publicElement, + Map publicSyncStateById, + Predicate> isElementTreeConflicted) { + + + return stageElementTree(context, elementContext, publicElement, + elementPublicStore, + (elementId) -> elementPrivateStore.getDescriptor(context, elementContext, elementId) + .isPresent(), + isElementTreeConflicted, + (elementId) -> publicSyncStateById.get(elementId).getPublishTime(), + Action.CREATE); + } + + private Set stageElementTree(SessionContext context, ElementContext elementContext, + ElementEntity element, + ElementStore elementStore, + Predicate isElementExist, + Predicate> isElementTreeConflicted, + Function stagePublishTimeGetter, + Action stageAction) { + ElementEntity elementTreeRoot = findRootElementOfChange(context, elementContext, + elementStore, isElementExist, element); + + Set elementTreeIds = new HashSet<>(); + elementTreeIds.add(elementTreeRoot.getId()); + + Set subElementIds = stageElementSubs(context, elementContext, elementStore, elementTreeRoot, + stagePublishTimeGetter, stageAction); + elementTreeIds.addAll(subElementIds); + + boolean conflicted = isElementTreeConflicted.test(elementTreeIds); + stageElement(context, elementContext, elementTreeRoot, + stagePublishTimeGetter.apply(elementTreeRoot.getId()), stageAction, conflicted, + conflicted ? subElementIds : null); + return elementTreeIds; + } + + private ElementEntity findRootElementOfChange(SessionContext context, + ElementContext elementContext, + ElementStore elementStore, + Predicate isElementExistOnOppositeStore, + ElementEntity element) { + return element.getId().equals(ROOT_ELEMENTS_PARENT_ID) || + isElementExistOnOppositeStore.test(element.getParentId()) + ? element + : findRootElementOfChange(context, elementContext, elementStore, + isElementExistOnOppositeStore, + elementStore.get(context, elementContext, element.getParentId()) + .orElseThrow(() -> new IllegalStateException( + String.format("Element %s exists while its parent element %s does not", + element.getId(), element.getParentId())))); + } + + private boolean containsDirty(Set elementIds, + Map syncStateById) { + return elementIds.stream().anyMatch(elementId -> { + SynchronizationStateEntity privateSyncState = syncStateById.get(elementId); + return privateSyncState != null && privateSyncState.isDirty(); + }); + } + + private Set stageElementSubs(SessionContext context, ElementContext elementContext, + ElementStore elementStore, ElementEntity parentElement, + Function stagePublishTimeGetter, Action stageAction) { + Set elementTreeIds = new HashSet<>(); + for (Id elementId : parentElement.getSubElementIds()) { + ElementEntity element = elementStore.get(context, elementContext, elementId).get(); + + stageElement(context, elementContext, element, stagePublishTimeGetter.apply(elementId), + stageAction, false, null); + + elementTreeIds.add(elementId); + elementTreeIds.addAll( + stageElementSubs(context, elementContext, elementStore, element, stagePublishTimeGetter, + stageAction)); + } + return elementTreeIds; + } + + private void stageElement(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime, Action action, + boolean conflicted, Set conflictDependents) { + StageEntity elementStage = + new StageEntity<>(element, publishTime, action, conflicted); + if (conflictDependents != null) { + elementStage.setConflictDependents( + conflictDependents.stream().map(ElementEntity::new).collect(Collectors.toSet())); + } + elementStageStore.create(context, elementContext, elementStage); + } + + private void stageVersion(SessionContext context, Id itemId, VersionEntity stageVersion, + Action stageAction, Date publishTime) { + versionStageStore + .create(context, itemId, new StageEntity<>(stageVersion, publishTime, stageAction, false)); + } + + private Map toMapById( + Collection syncStates) { + return syncStates.stream() + .collect(Collectors.toMap(SynchronizationStateEntity::getId, Function.identity())); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStore.java deleted file mode 100644 index db3066c313..0000000000 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStore.java +++ /dev/null @@ -1,110 +0,0 @@ -package org.openecomp.core.zusammen.plugin.collaboration; - -import com.amdocs.zusammen.datatypes.Id; -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.Space; -import com.amdocs.zusammen.datatypes.item.Action; -import com.amdocs.zusammen.datatypes.itemversion.Tag; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElementChange; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeChange; -import org.openecomp.core.zusammen.plugin.ZusammenPluginUtil; -import org.openecomp.core.zusammen.plugin.dao.ElementRepository; -import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; -import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; - -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.plugin.ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; -import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getSpaceName; - -public class VersionCollaborationStore { - - public void tagItemVersion(SessionContext context, Id itemId, Id versionId, Id changeId, - Tag tag) { - if (changeId != null) { - throw new UnsupportedOperationException( - "In this plugin implementation tag is supported only on versionId"); - } - String space = getSpaceName(context, Space.PRIVATE); - ElementEntityContext targetContext = new ElementEntityContext(space, itemId, versionId); - targetContext.setChangeRef(tag.getName()); - copyElements(context, new ElementEntityContext(space, itemId, versionId), targetContext, - getElementRepository(context)); - } - - public CollaborationMergeChange resetItemVersionHistory(SessionContext context, Id itemId, - Id versionId, String changeRef) { - ElementRepository elementRepository = getElementRepository(context); - - String spaceName = getSpaceName(context, Space.PRIVATE); - ElementEntityContext versionContext = new ElementEntityContext(spaceName, itemId, versionId); - - Collection deletedElements = - deleteElements(context, versionContext, elementRepository); - - ElementEntityContext changeRefContext = new ElementEntityContext(spaceName, itemId, versionId); - changeRefContext.setChangeRef(changeRef); - - Collection createdElements = - copyElements(context, changeRefContext, versionContext, elementRepository); - - // TODO: 4/19/2017 version change... - return createCollaborationMergeChange(versionContext, deletedElements, createdElements); - } - - private Collection deleteElements(SessionContext context, - ElementEntityContext elementContext, - ElementRepository elementRepository) { - Collection elements = elementRepository.list(context, elementContext); - elements.forEach(element -> elementRepository - .delete(context, elementContext, new ElementEntity(element.getId()))); - elementRepository.delete(context, elementContext, new ElementEntity(ROOT_ELEMENTS_PARENT_ID)); - return elements; - } - - private Collection copyElements(SessionContext context, - ElementEntityContext sourceElementContext, - ElementEntityContext targetElementContext, - ElementRepository elementRepository) { - Collection elements = elementRepository.list(context, sourceElementContext); - elements.forEach(elementEntity -> - elementRepository.create(context, targetElementContext, elementEntity)); - return elements; - } - - private CollaborationMergeChange createCollaborationMergeChange( - ElementEntityContext versionContext, - Collection deletedElements, - Collection createdElements) { - CollaborationMergeChange mergeChange = new CollaborationMergeChange(); - mergeChange.getChangedElements().addAll( - convertToCollaborationElementChanges(versionContext, deletedElements, Action.DELETE)); - mergeChange.getChangedElements().addAll( - convertToCollaborationElementChanges(versionContext, createdElements, Action.CREATE)); - return mergeChange; - } - - private List convertToCollaborationElementChanges( - ElementEntityContext elementContext, Collection changedElements, - Action action) { - return changedElements.stream() - .map(element -> convertToCollaborationElementChange(element, elementContext, action)) - .collect(Collectors.toList()); - } - - private CollaborationElementChange convertToCollaborationElementChange( - ElementEntity elementEntity, ElementEntityContext elementContext, Action action) { - CollaborationElementChange elementChange = new CollaborationElementChange(); - elementChange - .setElement(ZusammenPluginUtil.getCollaborationElement(elementContext, elementEntity)); - elementChange.setAction(action); - return elementChange; - } - - protected ElementRepository getElementRepository(SessionContext context) { - return ElementRepositoryFactory.getInstance().createInterface(context); - } -} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPrivateStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPrivateStore.java new file mode 100644 index 0000000000..a024327548 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPrivateStore.java @@ -0,0 +1,38 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Date; +import java.util.Optional; + +public interface VersionPrivateStore { + Optional get(SessionContext context, Id itemId, Id versionId); + + Optional getSynchronizationState(SessionContext context, Id itemId, + Id versionId); + + void create(SessionContext context, Id itemId, VersionEntity version); + + void update(SessionContext context, Id itemId, VersionEntity version); + + void update(SessionContext context, Id itemId, VersionEntity version, Date publishTime, + boolean dirty); + + void delete(SessionContext context, Id itemId, VersionEntity version); + + void markAsPublished(SessionContext context, Id itemId, Id versionId, Date publishTime); + + void commitStagedCreate(SessionContext context, Id itemId, VersionEntity version, + Date publishTime); + + void commitStagedUpdate(SessionContext context, Id itemId, VersionEntity version, + Date publishTime); + + void commitStagedIgnore(SessionContext context, Id itemId, VersionEntity version, + Date publishTime); + + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPublicStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPublicStore.java new file mode 100644 index 0000000000..c86db0ec43 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPublicStore.java @@ -0,0 +1,29 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.itemversion.ItemVersionRevisions; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Date; +import java.util.Map; +import java.util.Optional; + +public interface VersionPublicStore { + + Optional get(SessionContext context, Id itemId, Id versionId); + + Optional getSynchronizationState(SessionContext context, + Id itemId, Id versionId); + + void create(SessionContext context, Id itemId, VersionEntity version, Id revisionId, + Map versionElementIds, Date publishTime, String message); + + void update(SessionContext context, Id itemId, VersionEntity version, Id revisionId, + Map versionElementIds, Date publishTime, String message); + + boolean checkHealth(SessionContext context); + + ItemVersionRevisions listItemVersionRevisions(SessionContext context, Id itemId, Id versionId); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionStageStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionStageStore.java new file mode 100644 index 0000000000..5058a262cc --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionStageStore.java @@ -0,0 +1,18 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Optional; + +public interface VersionStageStore { + + Optional> get(SessionContext context, Id itemId, + VersionEntity versionEntity); + + void create(SessionContext context, Id itemId, StageEntity versionStage); + + void delete(SessionContext context, Id itemId, VersionEntity version); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPrivateStoreImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPrivateStoreImpl.java new file mode 100644 index 0000000000..9f54ee3ae2 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPrivateStoreImpl.java @@ -0,0 +1,269 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import org.openecomp.core.zusammen.plugin.ZusammenPluginConstants; +import org.openecomp.core.zusammen.plugin.collaboration.ElementPrivateStore; +import org.openecomp.core.zusammen.plugin.dao.ElementRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getPrivateElementContext; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getPrivateSpaceName; + +public class ElementPrivateStoreImpl implements ElementPrivateStore { + private static final Id REVISION_ID = Id.ZERO; // the private revision id is Id.ZERO 0000000... + + @Override + public Map listIds(SessionContext context, ElementContext elementContext) { + return getElementRepository(context) + .listIds(context, new ElementEntityContext(getPrivateSpaceName(context), elementContext)); + } + + @Override + public Collection listSubs(SessionContext context, ElementContext elementContext, + Id elementId) { + if (elementId == null) { + elementId = ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; + } + + ElementRepository elementRepository = getElementRepository(context); + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + return elementRepository.get(context, privateContext, new ElementEntity(elementId)) + .map(ElementEntity::getSubElementIds).orElse(new HashSet<>()).stream() + .map(subElementId -> elementRepository + .get(context, privateContext, new ElementEntity(subElementId)).get()) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + @Override + public Optional get(SessionContext context, ElementContext elementContext, + Id elementId) { + ElementEntityContext privateElementContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateElementContext.setRevisionId(REVISION_ID); + return getElementRepository(context) + .get(context, privateElementContext, + new ElementEntity(elementId)); + } + + @Override + public Optional getDescriptor(SessionContext context, + ElementContext elementContext, Id elementId) { + return getElementRepository(context) + .getDescriptor(context, + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext + (elementContext)), + new ElementEntity(elementId)); + } + + @Override + public Collection listSynchronizationStates(SessionContext context, + ElementContext elementContext) { + ElementEntityContext privateElementContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + return getElementSyncStateRepository(context) + .list(context, privateElementContext); + } + + @Override + public Optional getSynchronizationState(SessionContext context, + ElementContext elementContext, + Id elementId) { + + ElementEntityContext privateElementContext = + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext + (elementContext)); + return getElementSyncStateRepository(context) + .get(context, privateElementContext, + new SynchronizationStateEntity(elementId, REVISION_ID)); + } + + @Override + public void create(SessionContext context, ElementContext elementContext, ElementEntity element) { + create(context, elementContext, element, true, null); + } + + @Override + public boolean update(SessionContext context, ElementContext elementContext, + ElementEntity element) { + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + + if (!isElementChanged(context, privateContext, element)) { + return false; + } + + getElementRepository(context).update(context, privateContext, element); + getElementSyncStateRepository(context).markAsDirty(context, privateContext, + new SynchronizationStateEntity(element.getId(), REVISION_ID)); + return true; + } + + @Override + public void delete(SessionContext context, ElementContext elementContext, ElementEntity element) { + + ElementEntityContext privateElementContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateElementContext.setRevisionId(REVISION_ID); + deleteElementHierarchy(context, getElementRepository(context), + getElementSyncStateRepository(context), + privateElementContext, element); + } + + @Override + public void markAsPublished(SessionContext context, ElementContext elementContext, Id elementId, + Date publishTime) { + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + getElementSyncStateRepository(context).update(context, + privateContext, + new SynchronizationStateEntity(elementId, REVISION_ID, publishTime, false)); + } + + @Override + public void markDeletionAsPublished(SessionContext context, ElementContext elementContext, + Id elementId, Date publishTime) { + + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + getElementSyncStateRepository(context).delete(context, + privateContext, + new SynchronizationStateEntity(elementId, REVISION_ID)); + } + + @Override + public void commitStagedCreate(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime) { + create(context, elementContext, element, false, publishTime); + } + + @Override + public void commitStagedUpdate(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime) { + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + + getElementRepository(context).update(context, privateContext, element); + // Currently Resolution='Other' is not supported so this is invoked after conflict was + // resolved with Resolution='Theirs' so dirty flag should be turned off. + // (if there was no conflict it's off anyway) + getElementSyncStateRepository(context).update(context, privateContext, + new SynchronizationStateEntity(element.getId(), REVISION_ID, publishTime, false)); + } + + @Override + public void commitStagedDelete(SessionContext context, ElementContext elementContext, + ElementEntity element) { + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + getElementRepository(context).delete(context, privateContext, element); + getElementSyncStateRepository(context) + .delete(context, privateContext, + new SynchronizationStateEntity(element.getId(), REVISION_ID)); + } + + @Override + public void commitStagedIgnore(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime) { + // publish time - updated to mark that this element was already synced with this publish time + // (even though the local data was preferred) and to prevent this conflict again. + // dirty - turned on because the local data which is different than the public one was + // preferred. It will enable future publication of this data. + getElementSyncStateRepository(context).update(context, + new ElementEntityContext(getPrivateSpaceName(context), elementContext), + new SynchronizationStateEntity(element.getId(), REVISION_ID, publishTime, true)); + } + + private void create(SessionContext context, ElementContext elementContext, + ElementEntity element, boolean dirty, Date publishTime) { + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + getElementRepository(context).create(context, privateContext, element); + getElementSyncStateRepository(context).create(context, privateContext, + new SynchronizationStateEntity(element.getId(), REVISION_ID, publishTime, dirty)); + } + + + private void deleteElementHierarchy( + SessionContext context, ElementRepository elementRepository, + ElementSynchronizationStateRepository elementSyncStateRepository, + ElementEntityContext elementContext, ElementEntity element) { + + Optional retrieved = elementRepository.get(context, elementContext, element); + if (!retrieved.isPresent()) { + return; + } + retrieved.get().getSubElementIds().stream() + .map(ElementEntity::new) + .forEach(subElementEntity -> deleteElementHierarchy( + context, elementRepository, elementSyncStateRepository, elementContext, + subElementEntity)); + + // only for the first one the parentId will populated (so it'll be removed from its parent) + elementRepository.delete(context, elementContext, element); + handleDeletedElementSyncState(context, elementSyncStateRepository, elementContext, element); + } + + private void handleDeletedElementSyncState(SessionContext context, + ElementSynchronizationStateRepository elementSyncStateRepository, + ElementEntityContext elementContext, + ElementEntity element) { + SynchronizationStateEntity elementSyncState = new SynchronizationStateEntity(element.getId(), + REVISION_ID); + if (elementSyncStateRepository.get(context, elementContext, elementSyncState). + orElseThrow( + () -> new IllegalStateException("Synchronization state must exist for an element")) + .getPublishTime() == null) { + elementSyncStateRepository.delete(context, elementContext, elementSyncState); + } else { + elementSyncStateRepository.markAsDirty(context, elementContext, elementSyncState); + } + } + + private boolean isElementChanged(SessionContext context, + ElementEntityContext elementContext, + ElementEntity newElement) { + return getElementHash(context, elementContext, new ElementEntity(newElement.getId())) + .map(existingHash -> !newElement.getElementHash().equals(existingHash)) + .orElse(true); + } + + private Optional getElementHash(SessionContext context, + ElementEntityContext elementEntityContext, + ElementEntity element) { + return getElementRepository(context).getHash(context, elementEntityContext, element); + } + + protected ElementRepository getElementRepository(SessionContext context) { + return ElementRepositoryFactory.getInstance().createInterface(context); + } + + protected ElementSynchronizationStateRepository getElementSyncStateRepository( + SessionContext context) { + return ElementSynchronizationStateRepositoryFactory.getInstance().createInterface(context); + } + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPublicStoreImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPublicStoreImpl.java new file mode 100644 index 0000000000..d946a529ce --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPublicStoreImpl.java @@ -0,0 +1,189 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.Space; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import org.openecomp.core.zusammen.plugin.collaboration.ElementPublicStore; +import org.openecomp.core.zusammen.plugin.dao.ElementRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getSpaceName; + +public class ElementPublicStoreImpl implements ElementPublicStore { + + @Override + public Optional get(SessionContext context, + ElementContext elementContext, Id elementId) { + return getElementRepository(context) + .get(context, new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext), + new ElementEntity(elementId)); + } + + @Override + public Optional getDescriptor(SessionContext context, + ElementContext elementContext, Id elementId) { + return getElementRepository(context).getDescriptor(context, + new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext), + new ElementEntity(elementId)); + } + + @Override + public Collection listSynchronizationStates( + SessionContext context, ElementContext elementContext) { + ElementEntityContext entityContext = new ElementEntityContext(getSpaceName + (context, Space.PUBLIC), elementContext); + + ElementSynchronizationStateRepository elementSyncStateRepository = + getElementSyncStateRepository(context); + Map ids = getElementRepository(context).listIds(context, entityContext); + + Collection synchronizationStateEntities = new HashSet<>(); + for (Map.Entry elementEntry : ids.entrySet()) { + Optional synchronizationStateEntity = elementSyncStateRepository. + get(context, entityContext, new SynchronizationStateEntity(elementEntry.getKey(), + elementEntry.getValue())); + if (synchronizationStateEntity.isPresent()) { + synchronizationStateEntities.add(synchronizationStateEntity.get()); + } else { + /*throw new IllegalStateException(String.format( + "list Synchronization States error: " + "element %s revision %s, which appears as an " + + "element of " + + "item" + + " %s version %s, does not exist", + elementEntry.getKey(), elementEntry.getValue(), elementContext.getItemId().getValue(), + elementContext.getVersionId().getValue()));*/ + } + } + + return synchronizationStateEntities; + } + + @Override + public void create(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime) { + ElementEntityContext publicContext = + new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext); + + + if (element.getParentId() != null) { + createParentElement(context, elementContext, element.getParentId(), publishTime); + } + getElementRepository(context).create(context, publicContext, element); + getElementSyncStateRepository(context).create(context, publicContext, + new SynchronizationStateEntity(element.getId(), elementContext.getRevisionId(), + publishTime, false)); + } + + @Override + public void update(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime) { + //todo - update in public should be create new entry with new revision_id in public - this is a + // new revision + ElementEntityContext publicContext = + new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext); + + Optional publicElement = getElementRepository(context).get(context, + publicContext, new ElementEntity(element.getId())); + if (publicElement.isPresent()) { + getElementRepository(context).update(context, publicContext, element); + } else { + publicElement = get(context,new ElementContext(publicContext.getItemId(),publicContext + .getVersionId()),element.getId()); + element.setSubElementIds(publicElement.get().getSubElementIds()); + getElementRepository(context).create(context, publicContext, element); + } + getElementSyncStateRepository(context).update(context, publicContext, + new SynchronizationStateEntity(element.getId(), elementContext.getRevisionId(), publishTime, + false)); + } + + @Override + public void delete(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime) { + ElementEntityContext publicContext = + new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext); + + if (element.getParentId() != null) { + Optional parentElement = get(context, elementContext, element.getParentId()); + if (parentElement.isPresent()) { + createParentElement(context, elementContext, element.getParentId(), publishTime); + } + } + + getElementRepository(context).delete(context, publicContext, element); + getElementSyncStateRepository(context) + .delete(context, publicContext, new SynchronizationStateEntity(element.getId(), + elementContext.getRevisionId())); + } + + @Override + public Map listIds(SessionContext context, ElementContext elementContext) { + + return getElementRepository(context) + .listIds(context, + new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext)); + + } + + private void createParentElement(SessionContext context, ElementContext elementContext, + Id parentElementId, Date publishTime + ) { + ElementEntityContext publicContext = + new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext); + + Optional parentElement = + getElementRepository(context).get(context, new ElementEntityContext + (publicContext.getSpace(), publicContext.getItemId(), publicContext.getVersionId(), + elementContext.getRevisionId()), + new ElementEntity(parentElementId)); + if(parentElement.isPresent()) { + update(context, elementContext, parentElement.get(), publishTime); + } + + + /* Id elementRevisionId = getElementRevision(context, publicContext, elementContext.getRevisionId() + , parentElementId); + + if (elementRevisionId != null && !elementRevisionId.equals(elementContext.getRevisionId())) { + Optional parentElement = + getElementRepository(context).get(context, new ElementEntityContext + (publicContext.getSpace(), publicContext.getItemId(), publicContext.getVersionId(), + elementContext.getRevisionId()), + new ElementEntity(parentElementId)); + elementRevisionId = getElementRevision(context, publicContext, elementContext.getRevisionId() + , parentElement.get().getId()); + if (elementRevisionId != null) { + update(context, elementContext, parentElement.get(), publishTime); + } else { + create(context, elementContext, parentElement.get(), publishTime); + } + + }*/ + } + + + + + protected ElementRepository getElementRepository(SessionContext context) { + return ElementRepositoryFactory.getInstance().createInterface(context); + } + + protected ElementSynchronizationStateRepository getElementSyncStateRepository( + SessionContext context) { + return ElementSynchronizationStateRepositoryFactory.getInstance().createInterface(context); + } + + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImpl.java new file mode 100644 index 0000000000..f6c29432df --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImpl.java @@ -0,0 +1,133 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +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.Resolution; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import org.openecomp.core.zusammen.plugin.collaboration.ElementStageStore; +import org.openecomp.core.zusammen.plugin.dao.ElementStageRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementStageRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; + +import java.util.Collection; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getPrivateElementContext; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getPrivateSpaceName; + +public class ElementStageStoreImpl implements ElementStageStore { + + @Override + public Collection listIds(SessionContext context, ElementContext elementContext) { + return getElementStageRepository(context) + .listIds(context, new ElementEntityContext(getPrivateSpaceName(context), + getPrivateElementContext(elementContext))); + } + + @Override + public Optional> get(SessionContext context, + ElementContext elementContext, + ElementEntity element) { + return getElementStageRepository(context).get(context, + new ElementEntityContext(getPrivateSpaceName(context), + getPrivateElementContext(elementContext)), + element); + } + + @Override + public Optional> getConflicted(SessionContext context, + ElementContext elementContext, + ElementEntity element) { + return get(context, elementContext, element).filter(StageEntity::isConflicted); + } + + @Override + public boolean hasConflicts(SessionContext context, ElementContext elementContext) { + return !getElementStageRepository(context).listConflictedIds(context, + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext(elementContext))).isEmpty(); + } + + @Override + public Collection> listConflictedDescriptors(SessionContext context, + ElementContext elementContext) { + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext + (elementContext)); + ElementStageRepository elementStageRepository = getElementStageRepository(context); + + return elementStageRepository.listConflictedIds(context, privateContext).stream() + .map(conflictedElement -> elementStageRepository + .getDescriptor(context, privateContext, conflictedElement).get()) + .collect(Collectors.toList()); + } + + @Override + public void create(SessionContext context, ElementContext elementContext, + StageEntity elementStage) { + getElementStageRepository(context) + .create(context, + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext(elementContext)), + elementStage); + } + + @Override + public void delete(SessionContext context, ElementContext elementContext, ElementEntity element) { + getElementStageRepository(context) + .delete(context, + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext(elementContext)), + element); + } + + + @Override + public void resolveConflict(SessionContext context, ElementContext elementContext, + ElementEntity element, Resolution resolution) { + Optional> stagedElement = + getConflicted(context, elementContext, element); + if (!stagedElement.isPresent()) { + return; + } + + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext + (elementContext)); + + switch (resolution) { + case YOURS: + resolveConflictByYours(context, privateContext, stagedElement.get()); + break; + case THEIRS: + resolveConflictByTheirs(context, privateContext, stagedElement.get()); + break; + case OTHER: // other = data updates only? no data deletions? if so, then: + // conflicted = false + // element = the input of resolve + // action = update + throw new UnsupportedOperationException("'Other' conflict resolution is not yet supported"); + default: + break; + } + } + + private void resolveConflictByYours(SessionContext context, ElementEntityContext privateContext, + StageEntity stagedElement) { + getElementStageRepository(context) + .markAsNotConflicted(context, privateContext, stagedElement.getEntity(), Action.IGNORE); + stagedElement.getConflictDependents().forEach(conflictDependant -> + getElementStageRepository(context) + .markAsNotConflicted(context, privateContext, conflictDependant, Action.IGNORE)); + } + + private void resolveConflictByTheirs(SessionContext context, ElementEntityContext privateContext, + StageEntity stagedElement) { + getElementStageRepository(context) + .markAsNotConflicted(context, privateContext, stagedElement.getEntity()); + } + + protected ElementStageRepository getElementStageRepository(SessionContext context) { + return ElementStageRepositoryFactory.getInstance().createInterface(context); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPrivateStoreImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPrivateStoreImpl.java new file mode 100644 index 0000000000..11e61ab5a9 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPrivateStoreImpl.java @@ -0,0 +1,117 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.collaboration.VersionPrivateStore; +import org.openecomp.core.zusammen.plugin.dao.VersionDao; +import org.openecomp.core.zusammen.plugin.dao.VersionDaoFactory; +import org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Date; +import java.util.Optional; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getPrivateSpaceName; + +public class VersionPrivateStoreImpl implements VersionPrivateStore { + + Id revisionId = Id.ZERO; + + @Override + public Optional get(SessionContext context, Id itemId, Id versionId) { + return getVersionDao(context).get(context, getPrivateSpaceName(context), itemId, versionId); + } + + @Override + public Optional getSynchronizationState(SessionContext context, + Id itemId, Id versionId) { + + return getVersionSyncStateRepository(context) + .get(context, new VersionContext(getPrivateSpaceName(context), itemId), + new SynchronizationStateEntity(versionId, revisionId)); + } + + @Override + public void create(SessionContext context, Id itemId, VersionEntity version) { + String privateSpace = getPrivateSpaceName(context); + + + getVersionDao(context).create(context, privateSpace, itemId, version); + getVersionSyncStateRepository(context).create(context, new VersionContext(privateSpace, + itemId), + new SynchronizationStateEntity(version.getId(), revisionId, null, true)); + } + + @Override + public void update(SessionContext context, Id itemId, VersionEntity version) { + + getVersionDao(context) + .updateModificationTime(context, getPrivateSpaceName(context), itemId, version.getId(), + version.getModificationTime()); + } + + @Override + public void update(SessionContext context, Id itemId, VersionEntity version, Date publishTime, + boolean dirty) { + getVersionSyncStateRepository(context).updatePublishTime(context, + new VersionContext(getPrivateSpaceName(context), itemId), + new SynchronizationStateEntity(version.getId(), revisionId, publishTime, dirty)); + } + + @Override + public void delete(SessionContext context, Id itemId, VersionEntity version) { + String privateSpace = getPrivateSpaceName(context); + + getVersionDao(context).delete(context, privateSpace, itemId, version.getId()); + getVersionSyncStateRepository(context).delete(context, new VersionContext(privateSpace, + itemId), + new SynchronizationStateEntity(version.getId(), revisionId)); + } + + @Override + public void markAsPublished(SessionContext context, Id itemId, Id versionId, Date publishTime) { + getVersionSyncStateRepository(context) + .updatePublishTime(context, new VersionContext(getPrivateSpaceName(context), itemId), + new SynchronizationStateEntity(versionId, revisionId, publishTime, false)); + } + + @Override + public void commitStagedCreate(SessionContext context, Id itemId, VersionEntity version, + Date publishTime) { + String privateSpace = getPrivateSpaceName(context); + + getVersionDao(context).create(context, privateSpace, itemId, version); + getVersionSyncStateRepository(context).create(context, new VersionContext(privateSpace, + itemId), + new SynchronizationStateEntity(version.getId(), revisionId, publishTime, false)); + } + + @Override + public void commitStagedUpdate(SessionContext context, Id itemId, VersionEntity version, + Date publishTime) { + update(context, itemId, version, publishTime, false); + } + + @Override + public void commitStagedIgnore(SessionContext context, Id itemId, VersionEntity version, + Date publishTime) { + getVersionSyncStateRepository(context).updatePublishTime(context, + new VersionContext(getPrivateSpaceName(context), itemId), + new SynchronizationStateEntity(version.getId(), revisionId, publishTime, false)); + } + + + + + protected VersionDao getVersionDao(SessionContext context) { + return VersionDaoFactory.getInstance().createInterface(context); + } + + protected VersionSynchronizationStateRepository getVersionSyncStateRepository( + SessionContext context) { + return VersionSynchronizationStateRepositoryFactory.getInstance().createInterface(context); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPublicStoreImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPublicStoreImpl.java new file mode 100644 index 0000000000..aa628eb706 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPublicStoreImpl.java @@ -0,0 +1,135 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.Space; +import com.amdocs.zusammen.datatypes.itemversion.ItemVersionRevisions; +import com.amdocs.zusammen.datatypes.itemversion.Revision; +import org.openecomp.core.zusammen.plugin.collaboration.VersionPublicStore; +import org.openecomp.core.zusammen.plugin.dao.VersionDao; +import org.openecomp.core.zusammen.plugin.dao.VersionDaoFactory; +import org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getSpaceName; + +public class VersionPublicStoreImpl implements VersionPublicStore { + @Override + public Optional get(SessionContext context, Id itemId, Id versionId) { + return getVersionDao(context) + .get(context, getSpaceName(context, Space.PUBLIC), itemId, versionId); + } + + @Override + public Optional getSynchronizationState(SessionContext context, + Id itemId, Id versionId) { + Id revisionId = getLastItemVersionRevision(context, itemId, + versionId); + if (revisionId == null) { + return Optional.empty(); + } + + return getVersionSyncStateRepository(context) + .get(context, new VersionContext(getSpaceName(context, Space.PUBLIC), itemId), + new SynchronizationStateEntity(versionId, revisionId)); + } + + + @Override + public void create(SessionContext context, Id itemId, VersionEntity version, Id revisionId, + Map versionElementIds, Date + publishTime, String message) { + String publicSpace = getSpaceName(context, Space.PUBLIC); + + getVersionDao(context).create(context, publicSpace, itemId, version); + + getVersionDao(context).createVersionElements(context, publicSpace, itemId, version.getId(), + revisionId, versionElementIds, publishTime,message); + + getVersionSyncStateRepository(context).create(context, new VersionContext(publicSpace, + itemId), + new SynchronizationStateEntity(version.getId(), revisionId, publishTime, false)); + } + + @Override + public void update(SessionContext context, Id itemId, VersionEntity version, + Id revisionId, Map versionElementIds, Date publishTime, String message) { + String publicSpace = getSpaceName(context, Space.PUBLIC); + + getVersionDao(context). + createVersionElements(context, publicSpace, itemId, version.getId(), + revisionId, versionElementIds, publishTime,message); + + getVersionSyncStateRepository(context). + updatePublishTime(context, new VersionContext(publicSpace, itemId), + new SynchronizationStateEntity(version.getId(), revisionId, publishTime, false)); + } + + @Override + public boolean checkHealth(SessionContext context) { + return getVersionDao(context).checkHealth(context); + } + + @Override + public ItemVersionRevisions listItemVersionRevisions(SessionContext context, Id itemId, + Id versionId) { + VersionContext entityContext = new VersionContext(getSpaceName(context, Space.PUBLIC), itemId); + List versionRevisions = getVersionSyncStateRepository(context) + .list(context, entityContext, new VersionEntity(versionId)); + + if (versionRevisions == null || versionRevisions.size() == 0) { + return null; + } + + versionRevisions.sort(new Comparator() { + @Override + public int compare(SynchronizationStateEntity o1, SynchronizationStateEntity o2) { + if (o1.getPublishTime().after(o2.getPublishTime())) { + return -1; + } else { + return 1; + } + } + }); + ItemVersionRevisions itemVersionRevisions = new ItemVersionRevisions(); + versionRevisions.forEach(synchronizationStateEntity -> itemVersionRevisions.addChange + (convertSyncState2Revision(synchronizationStateEntity))); + return itemVersionRevisions; + } + + private Revision convertSyncState2Revision( + SynchronizationStateEntity synchronizationStateEntity) { + Revision revision = new Revision(); + revision.setRevisionId(synchronizationStateEntity.getRevisionId()); + revision.setTime(synchronizationStateEntity.getPublishTime()); + revision.setMessage(synchronizationStateEntity.getMessage()); + revision.setUser(synchronizationStateEntity.getUser()); + return revision; + } + + + private Id getLastItemVersionRevision(SessionContext context, Id itemId, Id versionId) { + + ItemVersionRevisions versionRevisions = listItemVersionRevisions(context, itemId, versionId); + if(versionRevisions ==null ) return null; + return versionRevisions.getItemVersionRevisions().get(0).getRevisionId(); + } + + protected VersionDao getVersionDao(SessionContext context) { + return VersionDaoFactory.getInstance().createInterface(context); + } + + protected VersionSynchronizationStateRepository getVersionSyncStateRepository( + SessionContext context) { + return VersionSynchronizationStateRepositoryFactory.getInstance().createInterface(context); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionStageStoreImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionStageStoreImpl.java new file mode 100644 index 0000000000..dac9d257ea --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionStageStoreImpl.java @@ -0,0 +1,39 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.collaboration.VersionStageStore; +import org.openecomp.core.zusammen.plugin.dao.VersionStageRepository; +import org.openecomp.core.zusammen.plugin.dao.VersionStageRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Optional; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getPrivateSpaceName; + +public class VersionStageStoreImpl implements VersionStageStore { + @Override + public Optional> get(SessionContext context, Id itemId, + VersionEntity versionEntity) { + return getVersionStageRepository(context) + .get(context, new VersionContext(getPrivateSpaceName(context), itemId), versionEntity); + } + + @Override + public void create(SessionContext context, Id itemId, StageEntity versionStage) { + getVersionStageRepository(context) + .create(context, new VersionContext(getPrivateSpaceName(context), itemId), versionStage); + } + + @Override + public void delete(SessionContext context, Id itemId, VersionEntity version) { + getVersionStageRepository(context) + .delete(context, new VersionContext(getPrivateSpaceName(context), itemId), version); + } + + protected VersionStageRepository getVersionStageRepository(SessionContext context) { + return VersionStageRepositoryFactory.getInstance().createInterface(context); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementRepository.java index 967814c4d8..7681327e40 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementRepository.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementRepository.java @@ -1,15 +1,18 @@ package org.openecomp.core.zusammen.plugin.dao; +import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; -import java.util.Collection; +import java.util.Map; import java.util.Optional; public interface ElementRepository { - Collection list(SessionContext context, ElementEntityContext elementContext); + Map listIds(SessionContext context, ElementEntityContext elementContext); + +/* void createVersionData(SessionContext context, ElementEntityContext elementContext, VersionDataElement element);*/ void create(SessionContext context, ElementEntityContext elementContext, ElementEntity element); @@ -20,8 +23,28 @@ public interface ElementRepository { Optional get(SessionContext context, ElementEntityContext elementContext, ElementEntity element); + Optional getDescriptor(SessionContext context, ElementEntityContext elementContext, + ElementEntity element); + void createNamespace(SessionContext context, ElementEntityContext elementContext, ElementEntity element); - boolean checkHealth(SessionContext context); + Optional getHash(SessionContext context, ElementEntityContext elementEntityContext, + ElementEntity element); + + + + +/* Collection listSynchronizationStates(SessionContext context, + ElementEntityContext elementContext); + + void updateSynchronizationState(SessionContext context, ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState); + + void markAsDirty(SessionContext context, ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState); + + Optional getSynchronizationState(SessionContext context, + ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState);*/ } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepository.java new file mode 100644 index 0000000000..ac3dc4e4bf --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepository.java @@ -0,0 +1,34 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; + +import java.util.Collection; +import java.util.Optional; + +public interface ElementStageRepository + extends StageRepository { + + Optional> getDescriptor(SessionContext context, + ElementEntityContext elementContext, + ElementEntity element); + + Collection listIds(SessionContext context, + ElementEntityContext elementContext); + + Collection listConflictedIds(SessionContext context, + ElementEntityContext elementContext); + + void markAsNotConflicted(SessionContext context, ElementEntityContext entityContext, + ElementEntity entity, Action action); + + void markAsNotConflicted(SessionContext context, ElementEntityContext entityContext, + ElementEntity entity); + + void update(SessionContext context, ElementEntityContext entityContext, ElementEntity entity, + Action action, boolean conflicted); + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepositoryFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepositoryFactory.java new file mode 100644 index 0000000000..1e41308ff2 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepositoryFactory.java @@ -0,0 +1,14 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.utils.facade.api.AbstractComponentFactory; +import com.amdocs.zusammen.utils.facade.api.AbstractFactory; + +public abstract class ElementStageRepositoryFactory + extends AbstractComponentFactory { + public static ElementStageRepositoryFactory getInstance() { + return AbstractFactory.getInstance(ElementStageRepositoryFactory.class); + } + + public abstract ElementStageRepository createInterface(SessionContext context); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepository.java new file mode 100644 index 0000000000..53c029bb6f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepository.java @@ -0,0 +1,21 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Collection; + +public interface ElementSynchronizationStateRepository + extends SynchronizationStateRepository { + + Collection list(SessionContext context, + ElementEntityContext elementContext); + + void update(SessionContext context, ElementEntityContext entityContext, + SynchronizationStateEntity syncStateEntity); + + void markAsDirty(SessionContext context, ElementEntityContext entityContext, + SynchronizationStateEntity syncStateEntity); + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepositoryFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepositoryFactory.java new file mode 100644 index 0000000000..26f3bb4f56 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepositoryFactory.java @@ -0,0 +1,14 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.utils.facade.api.AbstractComponentFactory; +import com.amdocs.zusammen.utils.facade.api.AbstractFactory; + +public abstract class ElementSynchronizationStateRepositoryFactory + extends AbstractComponentFactory { + public static ElementSynchronizationStateRepositoryFactory getInstance() { + return AbstractFactory.getInstance(ElementSynchronizationStateRepositoryFactory.class); + } + + public abstract ElementSynchronizationStateRepository createInterface(SessionContext context); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/StageRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/StageRepository.java new file mode 100644 index 0000000000..98b0d8242c --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/StageRepository.java @@ -0,0 +1,15 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; + +import java.util.Optional; + +public interface StageRepository { + + Optional> get(SessionContext context, C entityContext, E entity); + + void create(SessionContext context, C entityContext, StageEntity stageEntity); + + void delete(SessionContext context, C entityContext, E entity); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/SynchronizationStateRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/SynchronizationStateRepository.java new file mode 100644 index 0000000000..f227b0c925 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/SynchronizationStateRepository.java @@ -0,0 +1,16 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Optional; + +public interface SynchronizationStateRepository { + + void create(SessionContext context, C entityContext, SynchronizationStateEntity syncStateEntity); + + void delete(SessionContext context, C entityContext, SynchronizationStateEntity syncStateEntity); + + Optional get(SessionContext context, C entityContext, + SynchronizationStateEntity syncStateEntity); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDao.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDao.java new file mode 100644 index 0000000000..f8ad0405b2 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDao.java @@ -0,0 +1,29 @@ +package org.openecomp.core.zusammen.plugin.dao; + + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Collection; +import java.util.Date; +import java.util.Map; +import java.util.Optional; + +public interface VersionDao { + Collection list(SessionContext context, String space, Id itemId); + + Optional get(SessionContext context, String space, Id itemId, Id versionId); + + void create(SessionContext context, String space, Id itemId, VersionEntity version); + + void updateModificationTime(SessionContext context, String space, Id itemId, Id versionId, Date modificationTime); + + void delete(SessionContext context, String space, Id itemId, Id versionId); + + boolean checkHealth(SessionContext context); + + void createVersionElements(SessionContext context, String publicSpace, Id itemId, Id versionId, + Id revisionId, Map versionElementIds, Date publishTime, + String message); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDaoFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDaoFactory.java new file mode 100644 index 0000000000..2847959f8f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDaoFactory.java @@ -0,0 +1,13 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.utils.facade.api.AbstractComponentFactory; +import com.amdocs.zusammen.utils.facade.api.AbstractFactory; + +public abstract class VersionDaoFactory extends AbstractComponentFactory { + public static VersionDaoFactory getInstance() { + return AbstractFactory.getInstance(VersionDaoFactory.class); + } + + public abstract VersionDao createInterface(SessionContext context); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepository.java new file mode 100644 index 0000000000..568e0c9d2b --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepository.java @@ -0,0 +1,9 @@ +package org.openecomp.core.zusammen.plugin.dao; + + +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +public interface VersionStageRepository extends StageRepository { + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepositoryFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepositoryFactory.java new file mode 100644 index 0000000000..fc9e7725eb --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepositoryFactory.java @@ -0,0 +1,13 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.utils.facade.api.AbstractComponentFactory; +import com.amdocs.zusammen.utils.facade.api.AbstractFactory; + +public abstract class VersionStageRepositoryFactory extends AbstractComponentFactory { + public static VersionStageRepositoryFactory getInstance() { + return AbstractFactory.getInstance(VersionStageRepositoryFactory.class); + } + + public abstract VersionStageRepository createInterface(SessionContext context); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepository.java new file mode 100644 index 0000000000..9134392d3b --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepository.java @@ -0,0 +1,18 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.List; + +public interface VersionSynchronizationStateRepository + extends SynchronizationStateRepository { + + void updatePublishTime(SessionContext context, VersionContext entityContext, + SynchronizationStateEntity syncStateEntity); + + List list(SessionContext context, VersionContext entityContext, + VersionEntity versionEntity); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepositoryFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepositoryFactory.java new file mode 100644 index 0000000000..dfedb5897b --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepositoryFactory.java @@ -0,0 +1,14 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.utils.facade.api.AbstractComponentFactory; +import com.amdocs.zusammen.utils.facade.api.AbstractFactory; + +public abstract class VersionSynchronizationStateRepositoryFactory + extends AbstractComponentFactory { + public static VersionSynchronizationStateRepositoryFactory getInstance() { + return AbstractFactory.getInstance(VersionSynchronizationStateRepositoryFactory.class); + } + + public abstract VersionSynchronizationStateRepository createInterface(SessionContext context); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraDaoUtils.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraDaoUtils.java deleted file mode 100644 index 20a1e1803f..0000000000 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraDaoUtils.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.openecomp.core.zusammen.plugin.dao.impl; - -import com.datastax.driver.core.Session; -import com.amdocs.zusammen.commons.db.api.cassandra.CassandraConnectorFactory; -import com.amdocs.zusammen.commons.db.api.cassandra.types.CassandraContext; -import com.amdocs.zusammen.datatypes.SessionContext; - -class CassandraDaoUtils { - - static T getAccessor(SessionContext context, Class classOfT) { - return CassandraConnectorFactory.getInstance().createInterface(getCassandraContext(context)) - .getMappingManager() - .createAccessor(classOfT); - } - - static Session getSession(SessionContext context) { - return CassandraConnectorFactory.getInstance().createInterface(getCassandraContext(context)) - .getMappingManager() - .getSession(); - } - - private static CassandraContext getCassandraContext(SessionContext context) { - CassandraContext cassandraContext = new CassandraContext(); - cassandraContext.setTenant(context.getTenant()); - return cassandraContext; - } -} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepository.java deleted file mode 100644 index 6cc1350444..0000000000 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepository.java +++ /dev/null @@ -1,375 +0,0 @@ -/* - * Copyright © 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.core.zusammen.plugin.dao.impl; - -import com.amdocs.zusammen.datatypes.Id; -import com.amdocs.zusammen.datatypes.Namespace; -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.Relation; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.utils.fileutils.json.JsonUtil; -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.Param; -import com.datastax.driver.mapping.annotations.Query; -import com.google.gson.reflect.TypeToken; -import org.openecomp.core.zusammen.plugin.dao.ElementRepository; -import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; - -import java.lang.reflect.Type; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -public class CassandraElementRepository implements ElementRepository { - - private static final String VERSION_ELEMENT_NOT_EXIST_ERROR_MSG = - "List version elements error: " + - "element %s, which appears as an element of item %s version %s, does not exist"; - - @Override - public Collection list(SessionContext context, - ElementEntityContext elementContext) { - Set elementIds = getVersionElementIds(context, elementContext); - - Collection elements = new ArrayList<>(); - for (String elementId : elementIds) { - elements.add(get(context, elementContext, new ElementEntity(new Id(elementId))) - .orElseThrow( - () -> new IllegalStateException(String.format(VERSION_ELEMENT_NOT_EXIST_ERROR_MSG, - elementId, elementContext.getItemId().getValue(), - getVersionId(elementContext))))); - } - return elements; - } - - @Override - public void create(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - createElement(context, elementContext, element); - addElementToParent(context, elementContext, element); - } - - @Override - public void update(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - updateElement(context, elementContext, element); - } - - @Override - public void delete(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - removeElementFromParent(context, elementContext, element); - deleteElement(context, elementContext, element); - } - - @Override - public Optional get(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - Row row = getElementAccessor(context).get( - elementContext.getSpace(), - elementContext.getItemId().toString(), - getVersionId(elementContext), - element.getId().toString()).one(); - - return row == null ? Optional.empty() : Optional.of(getElementEntity(element, row)); - } - - @Override - public void createNamespace(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - getElementNamespaceAccessor(context).create( - elementContext.getSpace(), - elementContext.getItemId().toString(), - element.getId().toString(), - element.getNamespace().toString()); - } - - @Override - public boolean checkHealth(SessionContext context) { - ResultSet resultSet = getVersionElementsAccessor(context).checkHealth(); - return resultSet.getColumnDefinitions().contains("element_ids"); - } - - private String getVersionId(ElementEntityContext elementContext) { - return elementContext.getChangeRef() == null - ? elementContext.getVersionId().toString() - : elementContext.getChangeRef(); - } - - private ElementNamespaceAccessor getElementNamespaceAccessor(SessionContext context) { - return CassandraDaoUtils.getAccessor(context, ElementNamespaceAccessor.class); - } - - private ElementAccessor getElementAccessor(SessionContext context) { - return CassandraDaoUtils.getAccessor(context, ElementAccessor.class); - } - - private VersionElementsAccessor getVersionElementsAccessor(SessionContext context) { - return CassandraDaoUtils.getAccessor(context, VersionElementsAccessor.class); - } - - private void createElement(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - Set subElementIds = - element.getSubElementIds().stream().map(Id::toString).collect(Collectors.toSet()); - String versionId = getVersionId(elementContext); - - getElementAccessor(context).create( - elementContext.getSpace(), - elementContext.getItemId().toString(), - versionId, - element.getId().toString(), - element.getParentId().toString(), - element.getNamespace().toString(), - JsonUtil.object2Json(element.getInfo()), - JsonUtil.object2Json(element.getRelations()), - element.getData(), - element.getSearchableData(), - element.getVisualization(), - subElementIds); - - getVersionElementsAccessor(context).addElements( - Collections.singleton(element.getId().toString()), - elementContext.getSpace(), - elementContext.getItemId().toString(), - versionId); - } - - private void updateElement(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - getElementAccessor(context).update( - JsonUtil.object2Json(element.getInfo()), - JsonUtil.object2Json(element.getRelations()), - element.getData(), - element.getSearchableData(), - element.getVisualization(), - elementContext.getSpace(), - elementContext.getItemId().toString(), - elementContext.getVersionId().toString(), - element.getId().toString()); - } - - private void deleteElement(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - String versionId = getVersionId(elementContext); - - getElementAccessor(context).delete( - elementContext.getSpace(), - elementContext.getItemId().toString(), - versionId, - element.getId().toString()); - - getVersionElementsAccessor(context).removeElements( - Collections.singleton(element.getId().toString()), - elementContext.getSpace(), - elementContext.getItemId().toString(), - versionId); - } - - private void addElementToParent(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - getElementAccessor(context).addSubElements( - Collections.singleton(element.getId().toString()), - elementContext.getSpace(), - elementContext.getItemId().toString(), - getVersionId(elementContext), - element.getParentId().toString()); - } - - private void removeElementFromParent(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - if (element.getParentId() == null) { - return; - } - getElementAccessor(context).removeSubElements( - Collections.singleton(element.getId().toString()), - elementContext.getSpace(), - elementContext.getItemId().toString(), - getVersionId(elementContext), - element.getParentId().toString()); - } - - private ElementEntity getElementEntity(ElementEntity element, Row row) { - element.setNamespace(getNamespace(row.getString(ElementField.NAMESPACE))); - element.setParentId(new Id(row.getString(ElementField.PARENT_ID))); - element.setInfo(json2Object(row.getString(ElementField.INFO), Info.class)); - element.setRelations( - json2Object(row.getString(ElementField.RELATIONS), new TypeToken>() { - }.getType())); - element.setData(row.getBytes(ElementField.DATA)); - element.setSearchableData(row.getBytes(ElementField.SEARCHABLE_DATA)); - element.setVisualization(row.getBytes(ElementField.VISUALIZATION)); - element.setSubElementIds(row.getSet(ElementField.SUB_ELEMENT_IDS, String.class) - .stream().map(Id::new).collect(Collectors.toSet())); - return element; - } - - private Namespace getNamespace(String namespaceStr) { - Namespace namespace = new Namespace(); - if (namespaceStr != null) { - namespace.setValue(namespaceStr); - } - return namespace; - } - - private static T json2Object(String json, Type typeOfT) { - return json == null ? null : JsonUtil.json2Object(json, typeOfT); - } - - private Set getVersionElementIds(SessionContext context, - ElementEntityContext elementContext) { - Row row = getVersionElementsAccessor(context).get( - elementContext.getSpace(), - elementContext.getItemId().toString(), - getVersionId(elementContext)).one(); - return row == null - ? new HashSet<>() - : row.getSet(CassandraElementRepository.VersionElementsField.ELEMENT_IDS, String.class); - } - - /* -CREATE TABLE IF NOT EXISTS element_namespace ( - space text, - item_id text, - element_id text, - namespace text, - PRIMARY KEY (( space, item_id, element_id )) -); - */ - @Accessor - interface ElementNamespaceAccessor { - @Query( - "UPDATE 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 itemId, - @Param("id") String elementId, - @Param("ns") String namespace); - } - - /* -CREATE TABLE IF NOT EXISTS element ( - space text, - item_id text, - version_id text, - element_id text, - parent_id text, - namespace text, - info text, - relations text, - data blob, - searchable_data blob, - visualization blob, - sub_element_ids set, - PRIMARY KEY (( space, item_id, version_id, element_id )) -); - */ - @Accessor - interface ElementAccessor { - @Query( - "UPDATE element SET parent_id=:parentId, namespace=:ns, info=:info, relations=:rels, " + - "data=:data, searchable_data=:searchableData, visualization=:visualization, " + - "sub_element_ids=sub_element_ids+:subs " + - "WHERE space=:space AND item_id=:item AND version_id=:ver AND element_id=:id ") - void create(@Param("space") String space, - @Param("item") String itemId, - @Param("ver") String versionId, - @Param("id") String elementId, - @Param("parentId") String parentElementId, - @Param("ns") String namespace, - @Param("info") String info, - @Param("rels") String relations, - @Param("data") ByteBuffer data, - @Param("searchableData") ByteBuffer searchableData, - @Param("visualization") ByteBuffer visualization, - @Param("subs") Set subElementIds); - - @Query("UPDATE element SET info=?, relations=?, data=?, searchable_data=?, visualization=?" + - " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") - void update(String info, String relations, ByteBuffer data, ByteBuffer searchableData, - ByteBuffer visualization, String space, String itemId, String versionId, - String elementId); - - @Query("DELETE FROM element WHERE space=? AND item_id=? AND version_id=? AND element_id=?") - void delete(String space, String itemId, String versionId, String elementId); - - @Query("SELECT parent_id, namespace, info, relations, data, searchable_data, visualization, " + - "sub_element_ids FROM element " + - "WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") - ResultSet get(String space, String itemId, String versionId, String elementId); - - @Query("UPDATE element SET sub_element_ids=sub_element_ids+? " + - " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") - void addSubElements(Set subElementIds, String space, String itemId, String versionId, - String elementId); - - @Query("UPDATE element SET sub_element_ids=sub_element_ids-? " + - " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") - void removeSubElements(Set subElementIds, String space, String itemId, String versionId, - String elementId); - } - - private static final class ElementField { - private static final String NAMESPACE = "namespace"; - private static final String PARENT_ID = "parent_id"; - private static final String INFO = "info"; - private static final String RELATIONS = "relations"; - private static final String DATA = "data"; - private static final String SEARCHABLE_DATA = "searchable_data"; - private static final String VISUALIZATION = "visualization"; - private static final String SUB_ELEMENT_IDS = "sub_element_ids"; - } - - /* - CREATE TABLE IF NOT EXISTS version_elements ( - space text, - item_id text, - version_id text, - element_ids set, - PRIMARY KEY (( space, item_id, version_id )) - ); - */ - @Accessor - interface VersionElementsAccessor { - - @Query("UPDATE 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("UPDATE version_elements SET element_ids=element_ids-? " + - "WHERE space=? AND item_id=? AND version_id=?") - void removeElements(Set elementIds, String space, String itemId, String versionId); - - @Query("SELECT element_ids FROM version_elements WHERE space=? AND item_id=? AND version_id=?") - ResultSet get(String space, String itemId, String versionId); - - @Query("SELECT element_ids FROM version_elements LIMIT 1") - ResultSet checkHealth(); - } - - private static final class VersionElementsField { - private static final String ELEMENT_IDS = "element_ids"; - } -} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepositoryFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepositoryFactory.java deleted file mode 100644 index f3072a6502..0000000000 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepositoryFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright © 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.core.zusammen.plugin.dao.impl; - -import com.amdocs.zusammen.datatypes.SessionContext; -import org.openecomp.core.zusammen.plugin.dao.ElementRepository; -import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; - -public class CassandraElementRepositoryFactory extends ElementRepositoryFactory { - - private static final ElementRepository INSTANCE = new CassandraElementRepository(); - - @Override - public ElementRepository createInterface(SessionContext context) { - return INSTANCE; - } -} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/CassandraDaoUtils.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/CassandraDaoUtils.java new file mode 100644 index 0000000000..b6cb9e4070 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/CassandraDaoUtils.java @@ -0,0 +1,27 @@ +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.commons.db.api.cassandra.CassandraConnectorFactory; +import com.amdocs.zusammen.commons.db.api.cassandra.types.CassandraContext; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.datastax.driver.core.Session; + +class CassandraDaoUtils { + + static T getAccessor(SessionContext context, Class classOfT) { + return CassandraConnectorFactory.getInstance().createInterface(getCassandraContext(context)) + .getMappingManager() + .createAccessor(classOfT); + } + + static Session getSession(SessionContext context) { + return CassandraConnectorFactory.getInstance().createInterface(getCassandraContext(context)) + .getMappingManager() + .getSession(); + } + + private static CassandraContext getCassandraContext(SessionContext context) { + CassandraContext cassandraContext = new CassandraContext(); + cassandraContext.setTenant(context.getTenant()); + return cassandraContext; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementRepositoryFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementRepositoryFactoryImpl.java new file mode 100644 index 0000000000..8540816f00 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementRepositoryFactoryImpl.java @@ -0,0 +1,31 @@ +/* + * Copyright © 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.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.ElementRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; + +public class ElementRepositoryFactoryImpl extends ElementRepositoryFactory { + + private static final ElementRepository INSTANCE = new ElementRepositoryImpl(); + + @Override + public ElementRepository createInterface(SessionContext context) { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementRepositoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementRepositoryImpl.java new file mode 100644 index 0000000000..bb3b1cfa7c --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementRepositoryImpl.java @@ -0,0 +1,565 @@ +/* + * Copyright © 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.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.Namespace; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.Relation; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import com.amdocs.zusammen.utils.fileutils.json.JsonUtil; +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.Param; +import com.datastax.driver.mapping.annotations.Query; +import com.google.gson.reflect.TypeToken; +import org.openecomp.core.zusammen.plugin.ZusammenPluginConstants; +import org.openecomp.core.zusammen.plugin.dao.ElementRepository; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; + +import java.lang.reflect.Type; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.stream.Collectors; + +public class ElementRepositoryImpl implements ElementRepository { + + @Override + public Map listIds(SessionContext context, ElementEntityContext elementContext) { + + if (elementContext.getRevisionId() == null) { + String revisionId = calculateLastRevisionId(context, elementContext); + if (revisionId == null) { + return new HashMap<>(); + } + + elementContext.setRevisionId(new Id(revisionId)); + } + return getVersionElementIds(context, elementContext).entrySet().stream().collect(Collectors + .toMap(entry -> new Id(entry.getKey()), entry -> new Id(entry.getValue()))); + + /* return getVersionElementIds(context, elementContext).stream() + .map(Id::new) + .collect(Collectors.toList());*/ + + } + + @Override + public void create(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + createElement(context, elementContext, element); + addElementToParent(context, elementContext, element); + } + + @Override + public void update(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + + Id elementRevisionId = getElementRevision(context, elementContext, element.getId()); + if (elementRevisionId.equals(elementContext.getRevisionId())) { + updateElement(context, elementContext, element); + } else { + createElement(context, elementContext, element); + } + } + + @Override + public void delete(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + removeElementFromParent(context, elementContext, element); + deleteElement(context, elementContext, element); + } + + @Override + public Optional get(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + String revisionId = calculateElementRevisionId(context, elementContext, element); + if (revisionId == null) { + return Optional.empty(); + } + + Row row = getElementAccessor(context).get( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString(), + revisionId).one(); + + return row == null ? Optional.empty() : Optional.of(getElementEntity(element, row)); + } + + @Override + public Optional getDescriptor(SessionContext context, + ElementEntityContext elementContext, + ElementEntity element) { + String revisionId = calculateElementRevisionId(context, elementContext, element); + if (revisionId == null) { + return Optional.empty(); + } + + Row row = getElementAccessor(context).getDescriptor( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString(), + revisionId).one(); + + return row == null ? Optional.empty() : Optional.of(getElementEntityDescriptor(element, row)); + } + + @Override + public void createNamespace(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + getElementNamespaceAccessor(context).create(elementContext.getItemId().toString(), + element.getId().toString(), + element.getNamespace().toString()); + } + + @Override + public Optional getHash(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + String revisionId = calculateElementRevisionId(context, elementContext, element); + if (revisionId == null) { + return Optional.empty(); + } + + Row row = getElementAccessor(context).getHash( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getId().toString(), + revisionId).one(); + + return row == null ? Optional.empty() : Optional.of(getElementHash(row)); + } + + private String calculateElementRevisionId(SessionContext context, + ElementEntityContext elementContext, + ElementEntity element) { + + if (elementContext.getSpace().equals(ZusammenPluginConstants.PUBLIC_SPACE)) { + + String versionRevision; + if (elementContext.getRevisionId() == null) { + versionRevision = calculateLastRevisionId(context, elementContext); + } else { + versionRevision = elementContext.getRevisionId().getValue(); + } + + elementContext.setRevisionId(new Id(versionRevision)); + Map elementIds = getVersionElementIds(context, elementContext); + if (elementIds.containsKey(element.getId().getValue())) { + return elementIds.get(element.getId().getValue()); + } else { + return null; + } + + } else { + return Id.ZERO.getValue(); + } + } + + private String calculateLastRevisionId(SessionContext context, ElementEntityContext + elementContext) { + List rows = getVersionElementsAccessor(context).listRevisions(elementContext.getSpace(), + elementContext + .getItemId().toString(), elementContext.getVersionId().toString()).all(); + if (rows == null || rows.size() == 0) { + return null; + } + rows.sort((o1, o2) -> o1.getDate(VersionElementsField.PUBLISH_TIME) + .after(o2.getDate(VersionElementsField.PUBLISH_TIME)) ? -1 : 1); + return rows.get(0).getString(VersionElementsField.REVISION_ID); + } + + /*private static String getVersionId(ElementEntityContext elementContext) { + return elementContext.getRevisionId() == null + ? elementContext.getVersionId().toString() + : elementContext.getRevisionId().getValue(); + }*/ + + private ElementNamespaceAccessor getElementNamespaceAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, ElementNamespaceAccessor.class); + } + + private ElementAccessor getElementAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, ElementAccessor.class); + } + + private VersionElementsAccessor getVersionElementsAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, VersionElementsAccessor.class); + } + + private void createElement(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + createElementRow(context, elementContext, element); + + Map elementIds = new TreeMap<>(); + elementIds.put(element.getId().toString(), elementContext.getRevisionId().getValue()); + getVersionElementsAccessor(context).addElements( + elementIds, + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + } + + private void createElementRow(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + Set subElementIds = + element.getSubElementIds().stream().map(Id::toString).collect(Collectors.toSet()); + + getElementAccessor(context).create( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getId().toString(), + elementContext.getRevisionId().getValue(), + element.getParentId() == null ? null : element.getParentId().toString(), + element.getNamespace() == null ? null : element.getNamespace().toString(), + JsonUtil.object2Json(element.getInfo()), + JsonUtil.object2Json(element.getRelations()), + element.getData(), + element.getSearchableData(), + element.getVisualization(), + subElementIds, + element.getElementHash().getValue()); + } + + private void updateElement(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + + + if (element.getParentId() == null) { + getElementAccessor(context).update( + JsonUtil.object2Json(element.getInfo()), + JsonUtil.object2Json(element.getRelations()), + element.getData(), + element.getSearchableData(), + element.getVisualization(), + element.getElementHash().getValue(), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString(), + elementContext.getRevisionId().getValue()); + } else { + getElementAccessor(context).update( + JsonUtil.object2Json(element.getInfo()), + JsonUtil.object2Json(element.getRelations()), + element.getData(), + element.getSearchableData(), + element.getVisualization(), + element.getElementHash().getValue(), + element.getParentId().getValue(), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().getValue(), + elementContext.getRevisionId().getValue()); + } + + Map elementIds = new TreeMap<>(); + elementIds.put(element.getId().getValue(), elementContext.getRevisionId().getValue()); + getVersionElementsAccessor(context).addElements( + elementIds, + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + } + + private void deleteElement(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + + + getElementAccessor(context).delete( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString(), + elementContext.getRevisionId().getValue()); + + getVersionElementsAccessor(context).removeElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementContext.getRevisionId().getValue()); + } + + private void addElementToParent(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + if (element.getParentId() == null) { + return; + } + + + getElementAccessor(context).addSubElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getParentId().toString(), + elementContext.getRevisionId().getValue()); + + Map elementIds = new TreeMap<>(); + elementIds.put(element.getParentId().toString(), elementContext.getRevisionId().getValue()); + getVersionElementsAccessor(context).addElements(elementIds, elementContext.getSpace(), + elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + } + + private void removeElementFromParent(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + + if (element.getParentId() == null) { + return; + } + + Optional parentElement = + get(context, elementContext, new ElementEntity(element.getParentId())); + if (!parentElement.isPresent()) { + return; + } + getElementAccessor(context).removeSubElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getParentId().toString(), + elementContext.getRevisionId().getValue()); + + getVersionElementsAccessor(context) + .removeElements(Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + + Map elementIds = new TreeMap<>(); + elementIds.put(element.getParentId().toString(), elementContext.getRevisionId().getValue()); + getVersionElementsAccessor(context).addElements(elementIds, elementContext.getSpace(), + elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + } + + static ElementEntity getElementEntityDescriptor(ElementEntity element, Row row) { + element.setNamespace(getNamespace(row.getString(ElementField.NAMESPACE))); + element.setParentId(getParentId(row.getString(ElementField.PARENT_ID))); + element.setInfo(json2Object(row.getString(ElementField.INFO), Info.class)); + element.setRelations( + json2Object(row.getString(ElementField.RELATIONS), new TypeToken>() { + }.getType())); + + element.setSubElementIds(row.getSet(ElementField.SUB_ELEMENT_IDS, String.class) + .stream().map(Id::new).collect(Collectors.toSet())); + return element; + } + + static ElementEntity getElementEntity(ElementEntity element, Row row) { + getElementEntityDescriptor(element, row); + + element.setData(row.getBytes(ElementField.DATA)); + element.setSearchableData(row.getBytes(ElementField.SEARCHABLE_DATA)); + element.setVisualization(row.getBytes(ElementField.VISUALIZATION)); + element.setElementHash(new Id(row.getString(ElementField.ELEMENT_HASH))); + return element; + } + + private Id getElementHash(Row row) { + return new Id(row.getString(ElementField.ELEMENT_HASH)); + } + + private static Id getParentId(String parentIdStr) { + return parentIdStr == null ? null : new Id(parentIdStr); + } + + private static Namespace getNamespace(String namespaceStr) { + Namespace namespace = new Namespace(); + if (namespaceStr != null) { + namespace.setValue(namespaceStr); + } + return namespace; + } + + private static T json2Object(String json, Type typeOfT) { + return json == null ? null : JsonUtil.json2Object(json, typeOfT); + } + + private Map getVersionElementIds(SessionContext context, + ElementEntityContext elementContext) { + Row row = getVersionElementsAccessor(context).get( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()).one(); + return row == null + ? new HashMap<>() + : row.getMap(ElementRepositoryImpl.VersionElementsField.ELEMENT_IDS, String.class, String + .class); + } + + private Id getElementRevision(SessionContext context, ElementEntityContext elementContext + , Id elementId) { + Map versionElementIds = + listIds(context, new ElementEntityContext + (elementContext.getSpace(), elementContext.getItemId(), elementContext.getVersionId(), + elementContext.getRevisionId())); + return versionElementIds.get(elementId); + + } + + + /* +CREATE TABLE IF NOT EXISTS element_namespace ( + item_id text, + element_id text, + namespace text, + PRIMARY KEY (( item_id, element_id )) +); + */ + @Accessor + interface ElementNamespaceAccessor { + @Query("UPDATE element_namespace SET namespace=:ns " + + "WHERE item_id=:item AND element_id=:id ") + void create(@Param("item") String itemId, + @Param("id") String elementId, + @Param("ns") String namespace); + } + + @Accessor + interface ElementAccessor { + @Query( + "UPDATE element SET parent_id=:parentId, namespace=:ns, info=:info, relations=:rels, " + + "data=:data, searchable_data=:searchableData, visualization=:visualization, " + + "sub_element_ids=sub_element_ids+:subs , element_hash=:elementHash " + + " WHERE space=:space AND item_id=:item AND version_id=:ver AND element_id=:id AND " + + "revision_id=:rev ") + void create(@Param("space") String space, + @Param("item") String itemId, + @Param("ver") String versionId, + @Param("id") String elementId, + @Param("rev") String revisionId, + @Param("parentId") String parentElementId, + @Param("ns") String namespace, + @Param("info") String info, + @Param("rels") String relations, + @Param("data") ByteBuffer data, + @Param("searchableData") ByteBuffer searchableData, + @Param("visualization") ByteBuffer visualization, + @Param("subs") Set subElementIds, + @Param("elementHash") String elementHash); + + + @Query("UPDATE element SET info=?, relations=?, data=?, searchable_data=?, visualization=? ," + + "element_hash=? , parent_id=? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + void update(String info, String relations, ByteBuffer data, ByteBuffer searchableData, + ByteBuffer visualization, String elementHash, String parentId, String space, String + itemId, String + versionId, String elementId, String revisionId); + + @Query("UPDATE element SET info=?, relations=?, data=?, searchable_data=?, visualization=? ," + + "element_hash=? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + void update(String info, String relations, ByteBuffer data, ByteBuffer searchableData, + ByteBuffer visualization, String elementHash, String space, String + itemId, String + versionId, String elementId, String revisionId); + + @Query( + "DELETE FROM element WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + void delete(String space, String itemId, String versionId, String elementId, String revisionId); + + @Query("SELECT parent_id, namespace, info, relations, data, searchable_data, visualization, " + + "sub_element_ids,element_hash FROM element " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + ResultSet get(String space, String itemId, String versionId, String elementId, String + revisionId); + + @Query("SELECT parent_id, namespace, info, relations, sub_element_ids FROM element " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + ResultSet getDescriptor(String space, String itemId, String versionId, String elementId, + String revisionId); + + @Query("UPDATE element SET sub_element_ids=sub_element_ids+? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + void addSubElements(Set subElementIds, String space, String itemId, String versionId, + String elementId, String revisionId); + + @Query("UPDATE element SET sub_element_ids=sub_element_ids-? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + void removeSubElements(Set subElementIds, String space, String itemId, String versionId, + String elementId, String revisionId); + + @Query("SELECT element_hash FROM element " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + ResultSet getHash(String space, String itemId, String versionId, String elementId, String + revisionId); + } + + private static final class ElementField { + private static final String NAMESPACE = "namespace"; + private static final String PARENT_ID = "parent_id"; + private static final String INFO = "info"; + private static final String RELATIONS = "relations"; + private static final String DATA = "data"; + private static final String SEARCHABLE_DATA = "searchable_data"; + private static final String VISUALIZATION = "visualization"; + private static final String SUB_ELEMENT_IDS = "sub_element_ids"; + private static final String ELEMENT_HASH = "element_hash"; + } + + @Accessor + interface VersionElementsAccessor { + + @Query("UPDATE version_elements SET element_ids=element_ids+ ? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + void addElements(Map elementIds, String space, String itemId, String versionId, + String versionRevisionId); + + @Query("UPDATE version_elements SET element_ids=element_ids-? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=?") + void removeElements(Set elementIds, String space, String itemId, String versionId, + String revisionId); + + @Query( + "SELECT element_ids FROM version_elements WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + ResultSet get(String space, String itemId, String versionId, String revisionId); + + @Query( + "SELECT revision_id,publish_time FROM version_elements WHERE space=? AND item_id=? AND " + + "version_id=? ") + ResultSet listRevisions(String space, String itemId, String versionId); + + } + + private static final class VersionElementsField { + private static final String ELEMENT_IDS = "element_ids"; + private static final String REVISION_ID = "revision_id"; + private static final String PUBLISH_TIME = "publish_time"; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryFactoryImpl.java new file mode 100644 index 0000000000..02bec12302 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryFactoryImpl.java @@ -0,0 +1,31 @@ +/* + * Copyright © 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.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.ElementStageRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementStageRepositoryFactory; + +public class ElementStageRepositoryFactoryImpl extends ElementStageRepositoryFactory { + + private static final ElementStageRepository INSTANCE = new ElementStageRepositoryImpl(); + + @Override + public ElementStageRepository createInterface(SessionContext context) { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryImpl.java new file mode 100644 index 0000000000..c215f825a6 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryImpl.java @@ -0,0 +1,423 @@ +/* + * Copyright © 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.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import com.amdocs.zusammen.utils.fileutils.json.JsonUtil; +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.Param; +import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.core.zusammen.plugin.dao.ElementStageRepository; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; + +import java.nio.ByteBuffer; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +public class ElementStageRepositoryImpl implements ElementStageRepository { + + @Override + public Collection listIds(SessionContext context, + ElementEntityContext elementContext) { + return getElements(getStageElementIds(context, elementContext)); + } + + @Override + public Collection listConflictedIds(SessionContext context, + ElementEntityContext elementContext) { + return getElements(getConflictedElementIds(context, elementContext)); + } + + @Override + public void create(SessionContext context, ElementEntityContext elementContext, + StageEntity elementStage) { + createElement(context, elementContext, elementStage); + addElementToParent(context, elementContext, elementStage.getEntity()); + } + + @Override + public void markAsNotConflicted(SessionContext context, ElementEntityContext elementContext, + ElementEntity element, Action action) { + getElementStageAccessor(context).updateState(action, false, + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString()); + + getStageElementsAccessor(context).removeConflictElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementContext.getRevisionId().getValue()); + } + + @Override + public void markAsNotConflicted(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + getElementStageAccessor(context).markAsNotConflicted( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString()); + + getStageElementsAccessor(context).removeConflictElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementContext.getRevisionId().getValue()); + } + + @Override + public void update(SessionContext context, ElementEntityContext elementContext, + ElementEntity element, Action action, boolean conflicted) { + getElementStageAccessor(context).update( + JsonUtil.object2Json(element.getInfo()), + JsonUtil.object2Json(element.getRelations()), + element.getData(), + element.getSearchableData(), + element.getVisualization(), + element.getElementHash().getValue(), + action, + conflicted, + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString()); + + if (!conflicted) { + getStageElementsAccessor(context).removeConflictElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementContext.getRevisionId().getValue()); + } + } + + @Override + public void delete(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + removeElementFromParent(context, elementContext, element); + deleteElement(context, elementContext, element); + } + + @Override + public Optional> get(SessionContext context, + ElementEntityContext elementContext, + ElementEntity element) { + Row row = getElementStageAccessor(context).get( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getId().toString()).one(); + + return row == null ? Optional.empty() : Optional.of(getStageElement(row)); + } + + @Override + public Optional> getDescriptor(SessionContext context, + ElementEntityContext elementContext, + ElementEntity element) { + Row row = getElementStageAccessor(context).getDescriptor( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getId().toString()).one(); + + return row == null ? Optional.empty() : Optional.of(getStageElementDescriptor(row)); + } + + + + private Collection getElements(Set elementIds) { + return elementIds.stream() + .map(id -> new ElementEntity(new Id(id))) + .collect(Collectors.toList()); + } + + private void createElement(SessionContext context, ElementEntityContext elementContext, + StageEntity elementStage) { + + + ElementEntity element = elementStage.getEntity(); + Set subElementIds = + element.getSubElementIds().stream().map(Id::toString).collect(Collectors.toSet()); + Set conflictDependents = elementStage.getConflictDependents().stream() + .map(conflictDependent -> conflictDependent.getId().getValue()) + .collect(Collectors.toSet()); + + getElementStageAccessor(context).create( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getId().toString(), + element.getParentId() == null ? null : element.getParentId().toString(), + element.getNamespace() == null ? null : element.getNamespace().toString(), + JsonUtil.object2Json(element.getInfo()), + JsonUtil.object2Json(element.getRelations()), + element.getData(), + element.getSearchableData(), + element.getVisualization(), + subElementIds, + element.getElementHash() == null ? null : element.getElementHash().getValue(), + elementStage.getPublishTime(), + elementStage.getAction(), + elementStage.isConflicted(), + conflictDependents); + + getStageElementsAccessor(context).add( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + + if (elementStage.isConflicted()) { + getStageElementsAccessor(context).addConflictElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + } + } + + private void deleteElement(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + + + getElementStageAccessor(context).delete( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getId().toString()); + + getStageElementsAccessor(context).remove( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + } + + private void addElementToParent(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + if (element.getParentId() == null) { + return; + } + getElementStageAccessor(context).addSubElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getParentId().toString()); + } + + private void removeElementFromParent(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + if (element.getParentId() == null) { + return; + } + getElementStageAccessor(context).removeSubElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getParentId().toString()); + } + + private StageEntity getStageElementDescriptor(Row row) { + return buildStageElement(ElementRepositoryImpl.getElementEntityDescriptor( + new ElementEntity(new Id(row.getString(ElementStageField.ID))), row), row); + } + + private StageEntity getStageElement(Row row) { + return buildStageElement(ElementRepositoryImpl.getElementEntity( + new ElementEntity(new Id(row.getString(ElementStageField.ID))), row), row); + } + + + private StageEntity buildStageElement(ElementEntity element, Row row) { + StageEntity elementStage = + new StageEntity<>(element, row.getDate(ElementStageField.PUBLISH_TIME)); + elementStage.setAction(Action.valueOf(row.getString(ElementStageField.ACTION))); + elementStage.setConflicted(row.getBool(ElementStageField.CONFLICTED)); + elementStage.setConflictDependents( + row.getSet(ElementStageField.CONFLICT_DEPENDENTS, String.class).stream() + .map(conflictDependentId -> new ElementEntity(new Id(conflictDependentId))) + .collect(Collectors.toSet())); + return elementStage; + } + + private Set getStageElementIds(SessionContext context, + ElementEntityContext elementContext) { + Row row = getStageElementsAccessor(context).get( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()).one(); + return row == null ? new HashSet<>() + : row.getSet(StageElementsField.STAGE_ELEMENT_IDS, String.class); + } + + private Set getConflictedElementIds(SessionContext context, + ElementEntityContext elementContext) { + Row row = getStageElementsAccessor(context).getConflicted( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()).one(); + return row == null ? new HashSet<>() + : row.getSet(StageElementsField.CONFLICT_ELEMENT_IDS, String.class); + } + + private ElementStageAccessor getElementStageAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, ElementStageAccessor.class); + } + + private StageElementsAccessor getStageElementsAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, StageElementsAccessor.class); + } + + @Accessor + interface ElementStageAccessor { + @Query( + "UPDATE element_stage SET parent_id=:parentId, namespace=:ns, info=:info, relations=:rels, " + + "data=:data, searchable_data=:searchableData, visualization=:visualization, " + + "publish_time=:publishTime, action=:action, " + + "conflicted=:conflicted, conflict_dependent_ids=:conflictDependents, " + + "sub_element_ids=sub_element_ids+:subs, element_hash=:elementHash " + + "WHERE space=:space AND item_id=:item AND version_id=:ver AND element_id=:id ") + void create(@Param("space") String space, + @Param("item") String itemId, + @Param("ver") String versionId, + @Param("id") String elementId, + @Param("parentId") String parentElementId, + @Param("ns") String namespace, + @Param("info") String info, + @Param("rels") String relations, + @Param("data") ByteBuffer data, + @Param("searchableData") ByteBuffer searchableData, + @Param("visualization") ByteBuffer visualization, + @Param("subs") Set subElementIds, + @Param("elementHash") String elementHash, + @Param("publishTime") Date publishTime, + @Param("action") Action action, + @Param("conflicted") boolean conflicted, + @Param("conflictDependents") Set conflictDependents); + + @Query("UPDATE element_stage SET info=?, relations=?, data=?, searchable_data=?, " + + "visualization=?,element_hash=?, action=?, conflicted=? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + void update(String info, String relations, ByteBuffer data, ByteBuffer searchableData, + ByteBuffer visualization, String elementHash, Action action, boolean conflicted, + String space, + String itemId, String versionId, String elementId); + + @Query("UPDATE element_stage SET action=?, conflicted=? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + void updateState(Action action, boolean conflicted, String space, String itemId, + String versionId, String elementId); + + @Query("UPDATE element_stage SET conflicted=false " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + void markAsNotConflicted(String space, String itemId, String versionId, String elementId); + + @Query( + "DELETE FROM element_stage WHERE space=? AND item_id=? AND version_id=? AND element_id=?") + void delete(String space, String itemId, String versionId, String elementId); + + @Query("SELECT element_id, parent_id, namespace, info, relations, data, searchable_data, " + + "visualization, sub_element_ids,element_hash, publish_time, action, " + + "conflicted, conflict_dependent_ids FROM element_stage " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + ResultSet get(String space, String itemId, String versionId, String elementId); + + @Query("SELECT element_id, parent_id, namespace, info, relations, " + + "sub_element_ids, publish_time, action, conflicted, conflict_dependent_ids " + + "FROM element_stage WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + ResultSet getDescriptor(String space, String itemId, String versionId, String elementId); + + @Query("UPDATE element_stage SET sub_element_ids=sub_element_ids+? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + void addSubElements(Set subElementIds, String space, String itemId, String versionId, + String elementId); + + @Query("UPDATE element_stage SET sub_element_ids=sub_element_ids-? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + void removeSubElements(Set subElementIds, String space, String itemId, String versionId, + String elementId); + } + + private static final class ElementStageField { + private static final String ID = "element_id"; + private static final String PUBLISH_TIME = "publish_time"; + private static final String ACTION = "action"; + private static final String CONFLICTED = "conflicted"; + private static final String CONFLICT_DEPENDENTS = "conflict_dependent_ids"; + } + + @Accessor + interface StageElementsAccessor { + + @Query("UPDATE version_elements SET stage_element_ids=stage_element_ids+? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + void add(Set elementIds, String space, String itemId, String versionId, String + revisionId); + + @Query("UPDATE version_elements SET stage_element_ids=stage_element_ids-? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + void remove(Set elementIds, String space, String itemId, String versionId, String + revisionId); + + @Query("SELECT stage_element_ids FROM version_elements " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=?") + ResultSet get(String space, String itemId, String versionId, String revisionId); + + @Query("UPDATE version_elements SET conflict_element_ids=conflict_element_ids+? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + void addConflictElements(Set elementIds, String space, String itemId, String + versionId, String revisionId); + + @Query("UPDATE version_elements SET conflict_element_ids=conflict_element_ids-? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + void removeConflictElements(Set elementIds, String space, String itemId, + String versionId, String revisionId); + + @Query("SELECT conflict_element_ids FROM version_elements " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + ResultSet getConflicted(String space, String itemId, String versionId, String revisionId); + } + + private static final class StageElementsField { + private static final String STAGE_ELEMENT_IDS = "stage_element_ids"; + private static final String CONFLICT_ELEMENT_IDS = "conflict_element_ids"; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryFactoryImpl.java new file mode 100644 index 0000000000..ec7e1c30ae --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryFactoryImpl.java @@ -0,0 +1,33 @@ +/* + * Copyright © 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.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepositoryFactory; + +public class ElementSynchronizationStateRepositoryFactoryImpl + extends ElementSynchronizationStateRepositoryFactory { + + private static final ElementSynchronizationStateRepository INSTANCE = + new ElementSynchronizationStateRepositoryImpl(); + + @Override + public ElementSynchronizationStateRepository createInterface(SessionContext context) { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryImpl.java new file mode 100644 index 0000000000..d41d3d73b1 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryImpl.java @@ -0,0 +1,209 @@ +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +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.zusammen.plugin.dao.ElementSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +public class ElementSynchronizationStateRepositoryImpl + implements ElementSynchronizationStateRepository { + + @Override + public Collection list(SessionContext context, + ElementEntityContext elementContext) { + List rows = getAccessor(context) + .list(elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString()).all(); + return rows == null ? new HashSet<>() + : rows.stream().map(this::getSynchronizationStateEntity).collect(Collectors.toSet()); + + } + + @Override + public void create(SessionContext context, ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState) { + update(context, elementContext.getSpace(), + elementContext.getItemId(), + elementContext.getVersionId(), + elementContext.getRevisionId(), + elementSyncState.getRevisionId(), + elementSyncState.getId(), + elementSyncState.getPublishTime(), + elementSyncState.isDirty() + + ); + } + + @Override + public void update(SessionContext context, ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState) { + update(context, elementContext.getSpace(), + elementContext.getItemId(), + elementContext.getVersionId(), + elementContext.getRevisionId(), + elementSyncState.getRevisionId(), + elementSyncState.getId(), + elementSyncState.getPublishTime(), + elementSyncState.isDirty() + + ); + } + + @Override + public void markAsDirty(SessionContext context, ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState) { + + + getAccessor(context).updateDirty(true, + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementSyncState.getId().toString(), + elementContext.getRevisionId().getValue()); + + getVersionElementsAccessor(context).addDirtyElements( + Collections.singleton(elementSyncState.getId().toString()), elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementContext.getRevisionId().getValue()); + } + + @Override + public void delete(SessionContext context, ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState) { + getAccessor(context).delete(elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementSyncState.getId().toString(), + elementContext.getRevisionId().getValue()); + + getVersionElementsAccessor(context).removeDirtyElements( + Collections.singleton(elementSyncState.getId().toString()), elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementContext.getRevisionId().getValue()); + } + + @Override + public Optional get(SessionContext context, + ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState) { + + Row row = getAccessor(context) + .get(elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementSyncState.getId().toString(), + elementSyncState.getRevisionId().getValue()).one(); + + return row == null ? Optional.empty() : Optional.of(getSynchronizationStateEntity(row)); + } + + private void update(SessionContext context, String space, Id itemId, Id versionId, Id + versionRevisionId,Id elementRevisionId,Id elementId, Date publishTime, boolean isDirty) { + getAccessor(context).update(publishTime, + isDirty, + space, + itemId.toString(), + versionId.toString(), + elementId.toString(), + elementRevisionId.getValue()); + + if (isDirty) { + getVersionElementsAccessor(context).addDirtyElements( + Collections.singleton(elementId.toString()), space, + itemId.toString(), + versionId.toString(), + versionRevisionId.getValue()); + } else { + getVersionElementsAccessor(context).removeDirtyElements( + Collections.singleton(elementId.toString()), space, + itemId.toString(), + versionId.toString(), + versionRevisionId.getValue()); + } + } + + + private SynchronizationStateEntity getSynchronizationStateEntity(Row row) { + SynchronizationStateEntity entity = + new SynchronizationStateEntity(new Id(row.getString(SynchronizationStateField.ID)), + new Id(row.getString(SynchronizationStateField.REVISION_ID)), + row.getDate(SynchronizationStateField.PUBLISH_TIME), + row.getBool(SynchronizationStateField.DIRTY)); + entity.setRevisionId(new Id(row.getString(SynchronizationStateField.REVISION_ID))); + + return entity; + + } + + private ElementSynchronizationStateAccessor getAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, ElementSynchronizationStateAccessor.class); + } + + private VersionElementsAccessor getVersionElementsAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, VersionElementsAccessor.class); + } + + @Accessor + interface ElementSynchronizationStateAccessor { + @Query("UPDATE element_synchronization_state SET publish_time=?, dirty=? " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id = ? ") + void update(Date publishTime, boolean dirty, String space, String itemId, String versionId, + String elementId, String revisionId); + + @Query("UPDATE element_synchronization_state SET dirty=? " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id = ? ") + void updateDirty(boolean dirty, String space, String itemId, String versionId, + String elementId, String revisionId); + + @Query("DELETE FROM element_synchronization_state " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id = ? ") + void delete(String space, String itemId, String versionId, String elementId, String revisionId); + + @Query("SELECT element_id,revision_id, publish_time, dirty FROM element_synchronization_state" + + " WHERE space=? AND item_id=? AND version_id=?") + ResultSet list(String space, String itemId, String versionId); + + @Query("SELECT element_id,revision_id, publish_time, dirty FROM element_synchronization_state" + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id = ? ") + ResultSet get(String space, String itemId, String versionId, String elementId, String + revisionId); + } + + private static final class SynchronizationStateField { + private static final String ID = "element_id"; + private static final String PUBLISH_TIME = "publish_time"; + private static final String DIRTY = "dirty"; + private static final String REVISION_ID = "revision_id"; + } + + @Accessor + interface VersionElementsAccessor { + + @Query("UPDATE version_elements SET dirty_element_ids=dirty_element_ids+? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=?") + void addDirtyElements(Set elementIds, String space, String itemId, String versionId, + String revisionId); + + @Query("UPDATE version_elements SET dirty_element_ids=dirty_element_ids-? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + void removeDirtyElements(Set elementIds, String space, String itemId, String + versionId, String revisionId); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoFactoryImpl.java new file mode 100644 index 0000000000..60dc9d1765 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoFactoryImpl.java @@ -0,0 +1,15 @@ +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.VersionDao; +import org.openecomp.core.zusammen.plugin.dao.VersionDaoFactory; + +public class VersionDaoFactoryImpl extends VersionDaoFactory { + + private static final VersionDao INSTANCE = new VersionDaoImpl(); + + @Override + public VersionDao createInterface(SessionContext context) { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoImpl.java new file mode 100644 index 0000000000..bba2ddf267 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoImpl.java @@ -0,0 +1,185 @@ +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +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.zusammen.plugin.dao.VersionDao; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +import static java.util.stream.Collectors.toMap; + +public class VersionDaoImpl implements VersionDao { + + @Override + public void create(SessionContext context, String space, Id itemId, VersionEntity version) { + String baseVersion = version.getBaseId() != null ? version.getBaseId().toString() : null; + + getAccessor(context) + .create(space, itemId.toString(), version.getId().toString(), + baseVersion, + version.getCreationTime(), version.getModificationTime()); + + } + + @Override + public void delete(SessionContext context, String space, Id itemId, Id versionId) { + + getAccessor(context).delete(space, itemId.toString(), versionId.toString()); + } + + @Override + public void updateModificationTime(SessionContext context, String space, Id itemId, + Id versionId, Date modificationTime) { + getAccessor(context) + .updateModificationTime(modificationTime, space, itemId.toString(), versionId.toString()); + } + + + @Override + public Collection list(SessionContext context, String space, Id itemId) { + List rows = getAccessor(context).list(space, itemId.toString()).all(); + return rows == null ? new ArrayList<>() : + rows.stream().map(VersionDaoImpl::convertToVersionEntity).collect(Collectors.toList()); + } + + + @Override + public Optional get(SessionContext context, String space, Id itemId, + Id versionId) { + Row row; + + row = getAccessor(context).get(space, itemId.toString(), versionId.toString()).one(); + + + return row == null ? Optional.empty() : Optional.of(convertToVersionEntity(row)); + } + + @Override + public boolean checkHealth(SessionContext context) { + return getAccessor(context).checkHealth().getColumnDefinitions() + .contains(VersionField.VERSION_ID); + } + + @Override + public void createVersionElements(SessionContext context, String space, Id itemId, + Id versionId, Id revisionId, Map versionElementIds, + Date publishTime, String message) { + Map elementIds = versionElementIds==null?null:versionElementIds. + entrySet(). + stream(). + collect(toMap((Map.Entryentry)->entry.getKey().getValue(), + (Map.Entryentry)->entry.getValue().getValue())); + + getVersionElementsAccessor(context).create(space,itemId.toString(),versionId.toString(), + revisionId.getValue(),elementIds,publishTime,message,context.getUser().getUserName()); + } + + + private static VersionEntity convertToVersionEntity(Row row) { + + /*Id revisionId = row.getColumnDefinitions().contains("revision_id")?new Id(row.getString + (VersionField.REVISION_ID)):null;*/ + + VersionEntity version = new VersionEntity(new Id(row.getString(VersionField.VERSION_ID))); + return enrichVersionEntity(version, row); + } + + static VersionEntity enrichVersionEntity(VersionEntity version, Row row) { + version.setBaseId(new Id(row.getString(VersionField.BASE_VERSION_ID))); + version.setCreationTime(row.getDate(VersionField.CREATION_TIME)); + version.setModificationTime(row.getDate(VersionField.MODIFICATION_TIME)); + return version; + } + + private VersionAccessor getAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, VersionAccessor.class); + } + + private VersionElementsAccessor getVersionElementsAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, VersionElementsAccessor.class); + } + + @Accessor + interface VersionAccessor { + + @Query( + "INSERT INTO version (space, item_id, version_id, base_version_id, " + + "creation_time, " + + "modification_time) " + + "VALUES (?, ?, ?, ?, ?, ?)") + void create(String space, String itemId, String versionId, String baseVersionId, + Date creationTime, Date modificationTime); + + @Query("UPDATE version SET modification_time=? WHERE space=? AND item_id=? AND version_id=? ") + void updateModificationTime(Date modificationTime, String space, String itemId, + String versionId); + + @Query("DELETE FROM version WHERE space=? AND item_id=? AND version_id=? ") + void delete(String space, String itemId, String versionId); + + @Query("SELECT version_id, base_version_id, creation_time, modification_time " + + "FROM version WHERE space=? AND item_id=? AND version_id=? ") + ResultSet get(String space, String itemId, String versionId); + + /*@Query("SELECT version_id, base_version_id, creation_time, modification_time " + + "FROM version WHERE space=? AND item_id=? AND version_id=? ") + ResultSet get(String space, String itemId, String versionId);*/ + + + @Query("SELECT version_id, base_version_id, creation_time, modification_time " + + "FROM version WHERE space=? AND item_id=?") + ResultSet list(String space, String itemId); + + @Query("SELECT version_id FROM version LIMIT 1") + ResultSet checkHealth(); + } + + private static final class VersionField { + private static final String VERSION_ID = "version_id"; + private static final String BASE_VERSION_ID = "base_version_id"; + private static final String CREATION_TIME = "creation_time"; + private static final String MODIFICATION_TIME = "modification_time"; + //private static final String REVISION_ID = "revision_id"; + } + + @Accessor + interface VersionElementsAccessor { + + @Query("INSERT INTO version_elements (space,item_id,version_id,revision_id,element_ids," + + "publish_time,message,user) " + + "VALUES (?,?,?,?,?,?,?,?)") + void create(String space, + String itemId, + String versionId, + String versionRevisionId, + Map elementIds, + Date publishTime, + String message, + String user); + + + + } + + /* public static final class VersionElementsField { + private static final String SPACE = "space"; + private static final String ITEM_ID = "item_id"; + private static final String VERSION_ID = "version_id"; + private static final String ELEMENT_IDS = "element_ids"; + private static final String REVISION_ID = "revision_id"; + + }*/ + + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryFactoryImpl.java new file mode 100644 index 0000000000..547bf6a06c --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryFactoryImpl.java @@ -0,0 +1,15 @@ +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.VersionStageRepository; +import org.openecomp.core.zusammen.plugin.dao.VersionStageRepositoryFactory; + +public class VersionStageRepositoryFactoryImpl extends VersionStageRepositoryFactory { + + private static final VersionStageRepository INSTANCE = new VersionStageRepositoryImpl(); + + @Override + public VersionStageRepository createInterface(SessionContext context) { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryImpl.java new file mode 100644 index 0000000000..353f37b91b --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryImpl.java @@ -0,0 +1,82 @@ +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Action; +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.zusammen.plugin.dao.VersionStageRepository; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Date; +import java.util.Optional; + +public class VersionStageRepositoryImpl implements VersionStageRepository { + + @Override + public Optional> get(SessionContext context, + VersionContext entityContext, + VersionEntity entity) { + Row row = getAccessor(context) + .get(entityContext.getSpace(), entityContext.getItemId().toString(), + entity.getId().toString()).one(); + return row == null ? Optional.empty() : Optional.of(convertToVersionStage(entity, row)); + } + + @Override + public void create(SessionContext context, VersionContext entityContext, + StageEntity stageEntity) { + VersionEntity entity = stageEntity.getEntity(); + getAccessor(context).create(entityContext.getSpace(), + entityContext.getItemId().toString(), + entity.getId().toString(), + entity.getBaseId() == null ? null : entity.getBaseId().toString(), + entity.getCreationTime() == null ? null : entity.getCreationTime(), + entity.getModificationTime() == null ? null : entity.getModificationTime(), + stageEntity.getPublishTime(), + stageEntity.getAction()); + } + + @Override + public void delete(SessionContext context, VersionContext entityContext, VersionEntity entity) { + getAccessor(context).delete(entityContext.getSpace(), entityContext.getItemId().toString(), + entity.getId().toString()); + } + + private StageEntity convertToVersionStage(VersionEntity version, Row row) { + StageEntity versionStage = + new StageEntity<>(VersionDaoImpl.enrichVersionEntity(version, row), + row.getDate(VersionStageField.PUBLISH_TIME)); + versionStage.setAction(Action.valueOf(row.getString(VersionStageField.ACTION))); + return versionStage; + } + + private VersionStageAccessor getAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, VersionStageAccessor.class); + } + + @Accessor + interface VersionStageAccessor { + + @Query("INSERT INTO version_stage (space, item_id, version_id, base_version_id, " + + "creation_time, modification_time, publish_time, action) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)") + void create(String space, String itemId, String versionId, String baseVersionId, + Date creationTime, Date modificationTime, Date publishTime, Action action); + + @Query("DELETE FROM version_stage WHERE space=? AND item_id=? AND version_id=?") + void delete(String space, String itemId, String versionId); + + @Query("SELECT base_version_id, creation_time, modification_time, publish_time, action " + + "FROM version_stage WHERE space=? AND item_id=? AND version_id=?") + ResultSet get(String space, String itemId, String versionId); + } + + private static final class VersionStageField { + private static final String PUBLISH_TIME = "publish_time"; + private static final String ACTION = "action"; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryFactoryImpl.java new file mode 100644 index 0000000000..95c3ec2730 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryFactoryImpl.java @@ -0,0 +1,33 @@ +/* + * Copyright © 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.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepositoryFactory; + +public class VersionSynchronizationStateRepositoryFactoryImpl + extends VersionSynchronizationStateRepositoryFactory { + + private static final VersionSynchronizationStateRepository INSTANCE = + new VersionSynchronizationStateRepositoryImpl(); + + @Override + public VersionSynchronizationStateRepository createInterface(SessionContext context) { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryImpl.java new file mode 100644 index 0000000000..5fb9779bc2 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryImpl.java @@ -0,0 +1,137 @@ +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +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.zusammen.plugin.dao.VersionSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +public class VersionSynchronizationStateRepositoryImpl + implements VersionSynchronizationStateRepository { + + @Override + public void create(SessionContext context, VersionContext entityContext, + SynchronizationStateEntity syncStateEntity) { + updatePublishTime(context, entityContext, syncStateEntity); + } + + @Override + public void updatePublishTime(SessionContext context, VersionContext entityContext, + SynchronizationStateEntity syncStateEntity) { + getAccessor(context) + .updatePublishTime(syncStateEntity.getPublishTime(), entityContext.getSpace(), + entityContext.getItemId().toString(), syncStateEntity.getId().toString(), + syncStateEntity.getRevisionId().getValue()); + } + + @Override + public List list(SessionContext context, VersionContext + entityContext, VersionEntity versionEntity) { + + List rows = getAccessor(context).list(entityContext.getSpace(), entityContext.getItemId().toString + (),versionEntity.getId().toString()).all(); + return rows == null ? new ArrayList<>(): + rows.stream().map(VersionSynchronizationStateRepositoryImpl::getSynchronizationStateEntity).collect(Collectors.toList()); + } + + + + /*@Override + public List listRevisions(SessionContext context, + VersionContext entityContext, + SynchronizationStateEntity syncStateEntity) { + List rows = getAccessor(context).list(entityContext.getSpace(), entityContext.getItemId() + .toString(), syncStateEntity.getId().toString()).all(); + return rows == null ? new ArrayList<>() :rows.stream() + .map(VersionSynchronizationStateRepositoryImpl::getSynchronizationStateEntity) + .collect(Collectors.toList()); + + + + + //forEach(row -> getSynchronizationStateEntity(syncStateEntity.getId(), row)); + + + }*/ + + + @Override + public void delete(SessionContext context, VersionContext entityContext, + SynchronizationStateEntity syncStateEntity) { + // done by version dao + } + + @Override + public Optional get(SessionContext context, + VersionContext entityContext, + SynchronizationStateEntity syncStateEntity) { + Row row = + getAccessor(context).get(entityContext.getSpace(), entityContext.getItemId().toString(), + syncStateEntity.getId().toString(), syncStateEntity.getRevisionId().getValue()).one(); + + return row == null ? Optional.empty() + : Optional.of(getSynchronizationStateEntity(syncStateEntity.getId(), row)); + } + + private SynchronizationStateEntity getSynchronizationStateEntity(Id entityId, Row row) { + SynchronizationStateEntity syncStateEntity = new SynchronizationStateEntity(entityId, + new Id(row.getString(REVISION_ID_FIELD))); + syncStateEntity.setPublishTime(row.getDate(PUBLISH_TIME_FIELD)); + syncStateEntity.setDirty(!row.getSet(DIRTY_ELEMENT_FIELD, String.class).isEmpty()); + return syncStateEntity; + } + + private static SynchronizationStateEntity getSynchronizationStateEntity(Row row) { + Id entityId = new Id(row.getColumnDefinitions().contains("version_id") ? row.getString + ("version_id") : row.getString("element_id")); + SynchronizationStateEntity syncStateEntity = new SynchronizationStateEntity(entityId, + new Id(row.getString(REVISION_ID_FIELD))); + syncStateEntity.setPublishTime(row.getDate(PUBLISH_TIME_FIELD)); + syncStateEntity.setDirty(!row.getSet(DIRTY_ELEMENT_FIELD, String.class).isEmpty()); + syncStateEntity.setRevisionId(new Id(row.getString(REVISION_ID_FIELD))); + syncStateEntity.setUser(row.getString(USER)); + syncStateEntity.setMessage(row.getString(MESSAGE)); + return syncStateEntity; + } + + private VersionSyncStateAccessor getAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, VersionSyncStateAccessor.class); + } + + @Accessor + interface VersionSyncStateAccessor { + @Query( + "UPDATE version_elements SET publish_time=? WHERE space=? AND item_id=? AND version_id=? " + + "AND revision_id=? ") + void updatePublishTime(Date publishTime, String space, String itemId, String versionId, String + revisionId); + + @Query("SELECT version_id,revision_id,publish_time, dirty_element_ids FROM version_elements " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + ResultSet get(String space, String itemId, String versionId, String revisionId); + + @Query("SELECT version_id,revision_id,publish_time,user,message, dirty_element_ids FROM " + + "version_elements " + + "WHERE space=? AND item_id=? AND version_id=? ") + ResultSet list(String space, String itemId, String versionId); + + } + + + private static final String PUBLISH_TIME_FIELD = "publish_time"; + private static final String DIRTY_ELEMENT_FIELD = "dirty_element_ids"; + private static final String REVISION_ID_FIELD = "revision_id"; + private static final String USER = "user"; + private static final String MESSAGE = "message"; +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/ElementEntity.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/ElementEntity.java index 1663d83427..1cd15102f2 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/ElementEntity.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/ElementEntity.java @@ -30,6 +30,7 @@ public class ElementEntity { private Id id; private Id parentId; private Namespace namespace; + private Id elementHash; private Info info; private Collection relations = Collections.emptyList(); private ByteBuffer data; @@ -41,6 +42,10 @@ public class ElementEntity { this.id = id; } + public Id getId() { + return id; + } + public Id getParentId() { return parentId; } @@ -49,14 +54,6 @@ public class ElementEntity { this.parentId = parentId; } - public Id getId() { - return id; - } - - public void setId(Id id) { - this.id = id; - } - public Namespace getNamespace() { return namespace; } @@ -127,8 +124,17 @@ public class ElementEntity { return id.equals(that.id); } + public Id getElementHash() { + return elementHash; + } + + public void setElementHash(Id elementHash) { + this.elementHash = elementHash; + } + @Override public int hashCode() { return id.hashCode(); } + } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/StageEntity.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/StageEntity.java new file mode 100644 index 0000000000..58ac0a918a --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/StageEntity.java @@ -0,0 +1,60 @@ +package org.openecomp.core.zusammen.plugin.dao.types; + +import com.amdocs.zusammen.datatypes.item.Action; + +import java.util.Collections; +import java.util.Date; +import java.util.Set; + +public class StageEntity { + private E entity; + private Date publishTime; + private Action action = Action.IGNORE; + private boolean conflicted; + private Set conflictDependents = Collections.emptySet(); + + // used by sync on stage creation + public StageEntity(E entity, Date publishTime) { + this.entity = entity; + this.publishTime = publishTime; + } + + public StageEntity(E entity, Date publishTime, Action action, boolean conflicted) { + this.entity = entity; + this.publishTime = publishTime; + this.action = action; + this.conflicted = conflicted; + } + + public E getEntity() { + return entity; + } + + public Date getPublishTime() { + return publishTime; + } + + public Action getAction() { + return action; + } + + public void setAction(Action action) { + this.action = action; + } + + public boolean isConflicted() { + return conflicted; + } + + public void setConflicted(boolean conflicted) { + this.conflicted = conflicted; + } + + public Set getConflictDependents() { + return conflictDependents; + } + + public void setConflictDependents(Set conflictDependents) { + this.conflictDependents = conflictDependents; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/SynchronizationStateEntity.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/SynchronizationStateEntity.java new file mode 100644 index 0000000000..510cef820b --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/SynchronizationStateEntity.java @@ -0,0 +1,116 @@ +/* + * Copyright © 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.core.zusammen.plugin.dao.types; + +import com.amdocs.zusammen.datatypes.Id; + +import java.util.Date; + +/** + * Synchronization state of an entity: + *
      + *
    • On private entity edit (create/update/delete): marked as dirty
    • + *
    • On entity publication: + *
        + *
      • if the private entity exists - updated with the publish time, marked as not dirty
      • + *
      • Otherwise - deleted
      • + *
      + *
    • + *
    + */ +public class SynchronizationStateEntity { + private Id id; + private Id revisionId; + private Date publishTime; + private boolean dirty; + private String user; + private String message; + + public SynchronizationStateEntity(Id id,Id revisionId) { + this.id = id; + this.revisionId = revisionId; + } + + public SynchronizationStateEntity(Id id,Id revisionId, Date publishTime, boolean dirty) { + this(id,revisionId); + this.publishTime = publishTime; + this.dirty = dirty; + } + + public Id getId() { + return id; + } + + public Date getPublishTime() { + return publishTime; + } + + public void setPublishTime(Date publishTime) { + this.publishTime = publishTime; + } + + public boolean isDirty() { + return dirty; + } + + public void setDirty(boolean dirty) { + this.dirty = dirty; + } + + public Id getRevisionId() { + return revisionId; + } + + public void setRevisionId(Id revisionId) { + this.revisionId = revisionId; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + SynchronizationStateEntity that = (SynchronizationStateEntity) o; + + return id.equals(that.id); + } + + @Override + public int hashCode() { + return id.hashCode(); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionContext.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionContext.java new file mode 100644 index 0000000000..41a3e66e0e --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionContext.java @@ -0,0 +1,23 @@ +package org.openecomp.core.zusammen.plugin.dao.types; + +import com.amdocs.zusammen.datatypes.Id; + +public class VersionContext { + private String space; + private Id itemId; + + + public VersionContext(String space, Id itemId) { + this.space = space; + this.itemId = itemId; + } + + public String getSpace() { + return space; + } + + public Id getItemId() { + return itemId; + } + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionDataElement.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionDataElement.java new file mode 100644 index 0000000000..48a52c0d85 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionDataElement.java @@ -0,0 +1,21 @@ +package org.openecomp.core.zusammen.plugin.dao.types; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import org.openecomp.core.zusammen.plugin.ZusammenPluginConstants; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.calculateElementHash; + +public class VersionDataElement extends ElementEntity { + + public VersionDataElement() { + super(ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID); + } + + public VersionDataElement(ItemVersionData itemVersionData) { + this(); + setInfo(itemVersionData.getInfo()); + setRelations(itemVersionData.getRelations()); + setElementHash(new Id(calculateElementHash(this))); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionEntity.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionEntity.java new file mode 100644 index 0000000000..aeed998d96 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionEntity.java @@ -0,0 +1,45 @@ +package org.openecomp.core.zusammen.plugin.dao.types; + +import com.amdocs.zusammen.datatypes.Id; + +import java.util.Date; + +public class VersionEntity { + private Id id; + private Id baseId; + private Date creationTime; + private Date modificationTime; + + public VersionEntity(Id id) { + this.id = id; + } + + public Id getId() { + return id; + } + + public Id getBaseId() { + return baseId; + } + + public void setBaseId(Id baseId) { + this.baseId = baseId; + } + + 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; + } + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraCollaborationStorePluginImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraCollaborationStorePluginImpl.java index 90fd3366fe..f9b65224e0 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraCollaborationStorePluginImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraCollaborationStorePluginImpl.java @@ -21,97 +21,302 @@ import com.amdocs.zusammen.commons.health.data.HealthStatus; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.Namespace; import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.Space; +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.ItemVersion; import com.amdocs.zusammen.datatypes.item.ItemVersionData; -import com.amdocs.zusammen.datatypes.itemversion.ItemVersionHistory; +import com.amdocs.zusammen.datatypes.item.ItemVersionDataConflict; +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.Revision; import com.amdocs.zusammen.datatypes.itemversion.Tag; +import com.amdocs.zusammen.datatypes.response.ErrorCode; +import com.amdocs.zusammen.datatypes.response.Module; import com.amdocs.zusammen.datatypes.response.Response; +import com.amdocs.zusammen.datatypes.response.ReturnCode; import com.amdocs.zusammen.datatypes.response.ZusammenException; import com.amdocs.zusammen.sdk.collaboration.CollaborationStore; import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElementChange; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElementConflict; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationItemVersionConflict; import com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeChange; import com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeResult; import com.amdocs.zusammen.sdk.collaboration.types.CollaborationPublishResult; -import org.openecomp.core.zusammen.plugin.collaboration.ElementCollaborationStore; -import org.openecomp.core.zusammen.plugin.collaboration.VersionCollaborationStore; +import com.amdocs.zusammen.sdk.types.ElementConflictDescriptor; +import com.amdocs.zusammen.sdk.types.ElementDescriptor; +import org.openecomp.core.zusammen.plugin.ZusammenPluginUtil; +import org.openecomp.core.zusammen.plugin.collaboration.CommitStagingService; +import org.openecomp.core.zusammen.plugin.collaboration.ElementPrivateStore; +import org.openecomp.core.zusammen.plugin.collaboration.ElementPublicStore; +import org.openecomp.core.zusammen.plugin.collaboration.ElementStageStore; +import org.openecomp.core.zusammen.plugin.collaboration.PublishService; +import org.openecomp.core.zusammen.plugin.collaboration.RevertService; +import org.openecomp.core.zusammen.plugin.collaboration.SyncService; +import org.openecomp.core.zusammen.plugin.collaboration.VersionPrivateStore; +import org.openecomp.core.zusammen.plugin.collaboration.VersionPublicStore; +import org.openecomp.core.zusammen.plugin.collaboration.VersionStageStore; +import org.openecomp.core.zusammen.plugin.collaboration.impl.ElementPrivateStoreImpl; +import org.openecomp.core.zusammen.plugin.collaboration.impl.ElementPublicStoreImpl; +import org.openecomp.core.zusammen.plugin.collaboration.impl.ElementStageStoreImpl; +import org.openecomp.core.zusammen.plugin.collaboration.impl.VersionPrivateStoreImpl; +import org.openecomp.core.zusammen.plugin.collaboration.impl.VersionPublicStoreImpl; +import org.openecomp.core.zusammen.plugin.collaboration.impl.VersionStageStoreImpl; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionDataElement; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static com.amdocs.zusammen.datatypes.item.SynchronizationStatus.MERGING; +import static com.amdocs.zusammen.datatypes.item.SynchronizationStatus.OUT_OF_SYNC; +import static com.amdocs.zusammen.datatypes.item.SynchronizationStatus.UP_TO_DATE; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToCollaborationElement; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToElementChange; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToElementDescriptor; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToElementEntity; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToItemVersion; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToVersionData; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToVersionEntity; public class CassandraCollaborationStorePluginImpl implements CollaborationStore { + // TODO: 8/15/2017 inject + + private VersionPrivateStore versionPrivateStore = new VersionPrivateStoreImpl(); + private VersionPublicStore versionPublicStore = new VersionPublicStoreImpl(); + private VersionStageStore versionStageStore = new VersionStageStoreImpl(); + + private ElementPrivateStore elementPrivateStore = new ElementPrivateStoreImpl(); + private ElementPublicStore elementPublicStore = new ElementPublicStoreImpl(); + private ElementStageStore elementStageStore = new ElementStageStoreImpl(); - private VersionCollaborationStore versionCollaborationStore = new VersionCollaborationStore(); - private ElementCollaborationStore elementCollaborationStore = new ElementCollaborationStore(); + // TODO: 9/4/2017 + private CommitStagingService commitStagingService = + new CommitStagingService(versionPrivateStore, versionStageStore, elementPrivateStore, + elementStageStore); + private PublishService publishService = + new PublishService(versionPublicStore, versionPrivateStore, elementPublicStore, + elementPrivateStore); + private SyncService syncService = + new SyncService(versionPublicStore, versionPrivateStore, versionStageStore, + elementPublicStore, elementPrivateStore, elementStageStore); + + private RevertService revertService = + new RevertService(elementPublicStore, elementPrivateStore); @Override - public Response createItem(SessionContext context, Id id, Info info) { + public Response createItem(SessionContext context, Id itemId, Info info) { // done by state store return new Response(Void.TYPE); } @Override - public Response deleteItem(SessionContext context, Id id) { + public Response deleteItem(SessionContext context, Id itemId) { // done by state store return new Response(Void.TYPE); } @Override - public Response createItemVersion(SessionContext context, Id itemId, Id versionId, Id id2, - ItemVersionData itemVersionData) { - // done by state store + public Response createItemVersion(SessionContext context, Id itemId, Id baseVersionId, + Id versionId, ItemVersionData itemVersionData) { + Date creationTime = new Date(); + versionPrivateStore.create(context, itemId, + convertToVersionEntity(versionId, baseVersionId, creationTime, creationTime)); + + ElementContext elementContext = new ElementContext(itemId, versionId); + VersionDataElement versionData = new VersionDataElement(itemVersionData); + + if (baseVersionId == null) { + elementPrivateStore.create(context, elementContext, versionData); + } else { + copyElements(context, new ElementContext(itemId, baseVersionId), elementContext); + elementPrivateStore.update(context, elementContext, versionData); + } + return new Response(Void.TYPE); } @Override public Response updateItemVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData) { - // done by state store + + if (elementPrivateStore.update(context, new ElementContext(itemId, versionId), + new VersionDataElement(itemVersionData))) { + + VersionEntity version = new VersionEntity(versionId); + version.setModificationTime(new Date()); + versionPrivateStore.update(context, itemId, version); + } + return new Response(Void.TYPE); } @Override public Response deleteItemVersion(SessionContext context, Id itemId, Id versionId) { - // done by state store + elementPrivateStore + .delete(context, new ElementContext(itemId, versionId), new VersionDataElement()); + + versionPrivateStore.delete(context, itemId, new VersionEntity(versionId)); return new Response(Void.TYPE); } @Override - public Response tagItemVersion(SessionContext context, Id itemId, Id versionId, Id changeId, + public Response getItemVersionStatus(SessionContext context, Id itemId, + Id versionId) { + if (versionStageStore.get(context, itemId, new VersionEntity(versionId)).isPresent()) { + return new Response<>(new ItemVersionStatus(MERGING, true)); + } + + Optional publicSyncState = + versionPublicStore.getSynchronizationState(context, itemId, versionId); + + if (!publicSyncState.isPresent()) { + return new Response<>(new ItemVersionStatus(UP_TO_DATE, true)); + } + + SynchronizationStateEntity privateSyncState = + versionPrivateStore.getSynchronizationState(context, itemId, versionId) + // TODO: 7/18/2017 ? + .orElseThrow(() -> new IllegalStateException("private version must exist")); + + return new Response<>(new ItemVersionStatus( + privateSyncState.getPublishTime().equals(publicSyncState.get().getPublishTime()) + ? UP_TO_DATE + : OUT_OF_SYNC, + privateSyncState.isDirty())); + } + + @Override + public Response tagItemVersion(SessionContext context, Id itemId, Id versionId, + Id revisionId, Tag tag) { - versionCollaborationStore.tagItemVersion(context, itemId, versionId, changeId, tag); + /* if (revisionId != null) { + throw new UnsupportedOperationException( + "In this plugin implementation tag is supported only on versionId"); + } + + copyElements(context, + new ElementContext(itemId, versionId), + new ElementContext(itemId, versionId, tag.getName()));*/ + return new Response(Void.TYPE); } @Override public Response publishItemVersion(SessionContext context, Id itemId, Id versionId, - String s) { - throw new UnsupportedOperationException("publishItemVersion"); + String message) { + try { + return new Response<>(publishService.publish(context, itemId, versionId, message)); + } catch (ZusammenException ze) { + return new Response<>( + new ReturnCode(ErrorCode.CL_ITEM_VERSION_PUBLISH, Module.ZCSP, null, ze.getReturnCode())); + } + } + + @Override + public Response syncItemVersion(SessionContext context, Id itemId, + Id versionId) { + CollaborationMergeResult result = syncService.sync(context, itemId, versionId, false); + commitStagingService.commitStaging(context, itemId, versionId); + + return new Response<>(result); } @Override - public Response syncItemVersion(SessionContext context, Id id, - Id id1) { - throw new UnsupportedOperationException("syncItemVersion"); + public Response forceSyncItemVersion(SessionContext context, Id itemId, + Id versionId) { + CollaborationMergeResult result = syncService.sync(context, itemId, versionId, true); + commitStagingService.commitStaging(context, itemId, versionId); + + return new Response<>(result); } @Override - public Response mergeItemVersion(SessionContext context, Id id, - Id id1, Id id2) { + public Response mergeItemVersion(SessionContext context, Id itemId, + Id versionId, Id sourceVersionId) { throw new UnsupportedOperationException("mergeItemVersion"); } @Override - public Response listItemVersionHistory(SessionContext context, Id id, - Id id1) { - throw new UnsupportedOperationException("listItemVersionHistory"); + public Response getItemVersionConflict(SessionContext context, + Id itemId, + Id versionId) { + ElementContext elementContext = new ElementContext(itemId, versionId, Id.ZERO); + + Collection> conflictedStagedElementDescriptors = + elementStageStore.listConflictedDescriptors(context, elementContext); + + CollaborationItemVersionConflict result = new CollaborationItemVersionConflict(); + for (StageEntity stagedElementDescriptor : conflictedStagedElementDescriptors) { + if (ROOT_ELEMENTS_PARENT_ID.equals(stagedElementDescriptor.getEntity().getId())) { + result.setVersionDataConflict( + getVersionDataConflict(context, elementContext, stagedElementDescriptor)); + } else { + result.getElementConflictDescriptors() + .add(getElementConflictDescriptor(context, elementContext, stagedElementDescriptor)); + } + } + return new Response<>(result); + } + + @Override + public Response listItemVersionRevisions(SessionContext context, Id itemId, + Id versionId) { + return new Response<>(versionPublicStore.listItemVersionRevisions(context, itemId, versionId)); } @Override - public Response resetItemVersionHistory(SessionContext context, - Id itemId, Id versionId, - String changeRef) { - return new Response<>(versionCollaborationStore.resetItemVersionHistory(context, itemId, versionId, changeRef)); + public Response getItemVersionRevision(SessionContext context, Id itemId, Id versionId, + Id revisionId) { + throw new UnsupportedOperationException( + "get revision is not supported in the current cassandra plugin"); + } + + @Override + public Response resetItemVersionRevision(SessionContext context, + Id itemId, Id versionId, + Id revisionId) { + throw new UnsupportedOperationException("resetItemVersionRevision function not supported"); + + } + + @Override + public Response revertItemVersionRevision(SessionContext context, + Id itemId, Id versionId, + Id revisionId) { + Optional itemVersion = getItemVersion(context, itemId, versionId, revisionId); + if (!itemVersion.isPresent()) { + throw new RuntimeException(String + .format("Item %s, version %s: Cannot revert to revision %s since it is not found", + itemId, versionId, revisionId)); + } + + // TODO: 12/4/2017 force sync is done in order to clear dirty element on private + // this is temp solution that should be fixed. + forceSyncItemVersion(context, itemId, versionId); + + //updateItemVersion(context, itemId, versionId, itemVersion.get().getData()); + revertService.revert(context, itemId, versionId, revisionId); + + return new Response<>(new CollaborationMergeChange()); + } + + + @Override + public Response commitElements(SessionContext context, Id itemId, Id versionId, String s) { + // not needed + return new Response(Void.TYPE); } @Override @@ -119,52 +324,198 @@ public class CassandraCollaborationStorePluginImpl implements CollaborationStore ElementContext elementContext, Namespace namespace, Id elementId) { - return new Response<>( - elementCollaborationStore.listElements(context, elementContext, elementId)); + return new Response<>(elementPrivateStore.listSubs(context, elementContext, elementId).stream() + .map(elementEntity -> convertToCollaborationElement(elementContext, elementEntity)) + .collect(Collectors.toList())); } @Override public Response getElement(SessionContext context, ElementContext elementContext, Namespace namespace, Id elementId) { - return new Response<>(elementCollaborationStore.getElement(context, elementContext, elementId)); + return new Response<>(elementPrivateStore.get(context, elementContext, elementId) + .map(elementEntity -> convertToCollaborationElement(elementContext, elementEntity)) + .orElse(null)); + } + + @Override + public Response getElementConflict(SessionContext context, + ElementContext elementContext, + Namespace namespace, + Id elementId) { + Optional> conflictedStagedElement = + elementStageStore + .getConflicted(context, elementContext, new ElementEntity(elementId)); + + return new Response<>(conflictedStagedElement + .map(stagedElement -> getElementConflict(context, elementContext, stagedElement)) + .orElse(null)); } @Override public Response createElement(SessionContext context, CollaborationElement element) { - elementCollaborationStore.createElement(context, element); + elementPrivateStore.create(context, + new ElementContext(element.getItemId(), element.getVersionId()), + convertToElementEntity(element)); return new Response(Void.TYPE); } @Override public Response updateElement(SessionContext context, CollaborationElement element) { - elementCollaborationStore.updateElement(context, element); + elementPrivateStore.update(context, + new ElementContext(element.getItemId(), element.getVersionId()), + convertToElementEntity(element)); return new Response(Void.TYPE); } @Override public Response deleteElement(SessionContext context, CollaborationElement element) { - elementCollaborationStore.deleteElement(context, element); + elementPrivateStore + .delete(context, new ElementContext(element.getItemId(), element.getVersionId()), + convertToElementEntity(element)); + return new Response(Void.TYPE); } @Override - public Response commitElements(SessionContext context, Id itemId, Id versionId, String s) { - // not needed - return new Response(Void.TYPE); + public Response resolveElementConflict(SessionContext context, + CollaborationElement element, + Resolution resolution) { + ElementContext elementContext = new ElementContext(element.getItemId(), element.getVersionId()); + elementStageStore + .resolveConflict(context, elementContext, convertToElementEntity(element), resolution); + commitStagingService.commitStaging(context, element.getItemId(), element.getVersionId()); + + return new Response<>(new CollaborationMergeResult()); } @Override - public Response checkHealth(SessionContext sessionContext) throws ZusammenException { + public Response getItemVersion(SessionContext context, Space space, Id itemId, + Id versionId, Id revisionId) { + return new Response<>(getItemVersion(context, itemId, versionId, revisionId).orElse(null)); + } - boolean health = elementCollaborationStore.checkHealth(sessionContext); - HealthInfo healthInfo ; - if (health){ - healthInfo = new HealthInfo("Collaboration", HealthStatus.UP,""); - } else { - healthInfo = new HealthInfo("Collaboration", HealthStatus.DOWN,"No Schema Available"); + @Override + public Response checkHealth(SessionContext context) throws ZusammenException { + HealthInfo healthInfo = versionPublicStore.checkHealth(context) + ? new HealthInfo(Module.ZCSP.getDescription(), HealthStatus.UP, "") + : new HealthInfo(Module.ZCSP.getDescription(), HealthStatus.DOWN, "No Schema Available"); + + return new Response<>(healthInfo); + } + + private Optional getItemVersion(SessionContext context, Id itemId, Id versionId, + Id revisionId) { + // since revisions are kept only on public - get from there + Optional versionEntity = versionPublicStore.get(context, itemId, versionId); + if (!versionEntity.isPresent()) { + return Optional.empty(); + } + + return elementPublicStore + .getDescriptor(context, new ElementContext(itemId, versionId, revisionId), + ROOT_ELEMENTS_PARENT_ID) + .map(ZusammenPluginUtil::convertToVersionData) + .map(itemVersionData -> convertToItemVersion(versionEntity.get(), itemVersionData)); + } + + private List listVersionElements(SessionContext context, + ElementContext elementContext) { + return elementPrivateStore.listIds(context, elementContext).entrySet().stream() // TODO: + // 9/5/2017 parallel + .map(entry -> elementPrivateStore.get(context, elementContext, entry.getKey()).get()) + .collect(Collectors.toList()); + } + + private void copyElements(SessionContext context, + ElementContext sourceContext, ElementContext targetContext) { + listVersionElements(context, sourceContext).forEach(element -> { + // publishTime copied as is and dirty is off + Date publishTime = + elementPrivateStore.getSynchronizationState(context, sourceContext, element.getId()) + .get().getPublishTime(); + elementPrivateStore.commitStagedCreate(context, targetContext, element, publishTime); + }); + } + + private ItemVersionDataConflict getVersionDataConflict(SessionContext context, + ElementContext elementContext, + StageEntity stagedElementDescriptor) { + ItemVersionDataConflict versionConflict = new ItemVersionDataConflict(); + versionConflict.setRemoteData(convertToVersionData(stagedElementDescriptor.getEntity())); + if (stagedElementDescriptor.getAction() == Action.UPDATE) { + versionConflict.setLocalData(getPrivateVersionData(context, elementContext)); } - return new Response(healthInfo); + return versionConflict; + } + private ItemVersionData getPrivateVersionData(SessionContext context, + ElementContext elementContext) { + return elementPrivateStore.getDescriptor(context, elementContext, ROOT_ELEMENTS_PARENT_ID) + .map(ZusammenPluginUtil::convertToVersionData) + .orElseThrow(() -> new IllegalStateException("Version must have data")); + } + + private ElementConflictDescriptor getElementConflictDescriptor(SessionContext context, + ElementContext elementContext, + StageEntity stagedElementDescriptor) { + ElementDescriptor elementDescriptorFromStage = + convertToElementDescriptor(elementContext, (stagedElementDescriptor.getEntity())); + + ElementConflictDescriptor conflictDescriptor = new ElementConflictDescriptor(); + switch (stagedElementDescriptor.getAction()) { + case CREATE: + conflictDescriptor.setRemoteElementDescriptor(elementDescriptorFromStage); + break; + case UPDATE: + conflictDescriptor.setRemoteElementDescriptor(elementDescriptorFromStage); + conflictDescriptor.setLocalElementDescriptor(convertToElementDescriptor(elementContext, + elementPrivateStore + .getDescriptor(context, elementContext, stagedElementDescriptor.getEntity().getId()) + .orElse(null)));// updated on public while deleted from private + break; + case DELETE: + conflictDescriptor.setLocalElementDescriptor(elementDescriptorFromStage); + break; + default: + break; + } + return conflictDescriptor; + } + + private void addElementsToChangedElements(ElementContext elementContext, + Collection elements, + Collection changedElements, + Action action) { + elements.stream() + .map(elementEntity -> convertToElementChange(elementContext, elementEntity, action)) + .forEach(changedElements::add); + } + + private CollaborationElementConflict getElementConflict(SessionContext context, + ElementContext entityContext, + StageEntity stagedElement) { + CollaborationElement elementFromStage = + convertToCollaborationElement(entityContext, (stagedElement.getEntity())); + + CollaborationElementConflict conflict = new CollaborationElementConflict(); + switch (stagedElement.getAction()) { + case CREATE: + conflict.setRemoteElement(elementFromStage); + break; + case UPDATE: + conflict.setRemoteElement(elementFromStage); + conflict.setLocalElement( + elementPrivateStore.get(context, entityContext, stagedElement.getEntity().getId()) + .map(element -> convertToCollaborationElement(entityContext, element)) + .orElse(null));// updated on public while deleted from private + break; + case DELETE: + conflict.setLocalElement(elementFromStage); + break; + default: + break; + } + return conflict; } } \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraStateStorePluginImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraStateStorePluginImpl.java index b4767b2872..3ed668e331 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraStateStorePluginImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraStateStorePluginImpl.java @@ -17,18 +17,87 @@ package org.openecomp.core.zusammen.plugin.main; +import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.Space; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import com.amdocs.zusammen.datatypes.item.ItemVersionData; import com.amdocs.zusammen.datatypes.response.Response; import com.amdocs.zusammen.plugin.statestore.cassandra.StateStoreImpl; import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; import com.amdocs.zusammen.sdk.state.types.StateElement; +import org.openecomp.core.zusammen.plugin.ZusammenPluginUtil; +import org.openecomp.core.zusammen.plugin.collaboration.ElementPrivateStore; +import org.openecomp.core.zusammen.plugin.collaboration.impl.ElementPrivateStoreImpl; +import org.openecomp.core.zusammen.plugin.dao.ElementRepository; import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.VersionDao; +import org.openecomp.core.zusammen.plugin.dao.VersionDaoFactory; import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionDataElement; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; +import java.util.Collection; +import java.util.Date; +import java.util.stream.Collectors; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToItemVersion; import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getSpaceName; public class CassandraStateStorePluginImpl extends StateStoreImpl { + private ElementPrivateStore elementPrivateStore = new ElementPrivateStoreImpl(); + + @Override + public Response> listItemVersions(SessionContext context, Space space, + Id itemId) { + String spaceName = getSpaceName(context, space); + return new Response<>(getVersionDao(context).list(context, spaceName, itemId).stream() + .map(versionEntity -> getItemVersion(context, spaceName, itemId, versionEntity)) + .collect(Collectors.toList())); + } + + @Override + public Response isItemVersionExist(SessionContext context, Space space, Id itemId, + Id versionId) { + return new Response<>( + getVersionDao(context).get(context, getSpaceName(context, space), itemId, versionId) + .isPresent()); + } + + @Override + public Response getItemVersion(SessionContext context, Space space, Id itemId, + Id versionId) { + String spaceName = getSpaceName(context, space); + return new Response<>(getVersionDao(context).get(context, spaceName, itemId, versionId) + .map(versionEntity -> getItemVersion(context, spaceName, itemId, versionEntity)) + .orElse(null)); + } + + @Override + public Response createItemVersion(SessionContext context, Space space, Id itemId, + Id baseVersionId, Id versionId, ItemVersionData data, + Date creationTime) { + // done by collaboration store + return new Response(Void.TYPE); + } + + @Override + public Response updateItemVersion(SessionContext context, Space space, Id itemId, + Id versionId, ItemVersionData data, + Date modificationTime) { + // done by collaboration store + return new Response(Void.TYPE); + } + + @Override + public Response deleteItemVersion(SessionContext context, Space space, Id itemId, + Id versionId) { + // done by collaboration store + return new Response(Void.TYPE); + } + @Override public Response createElement(SessionContext context, StateElement element) { ElementEntity elementEntity = new ElementEntity(element.getId()); @@ -37,8 +106,7 @@ public class CassandraStateStorePluginImpl extends StateStoreImpl { ElementRepositoryFactory.getInstance().createInterface(context) .createNamespace(context, new ElementEntityContext(getSpaceName(context, element.getSpace()), - element.getItemId(), element.getVersionId()), - elementEntity); + element.getItemId(), element.getVersionId()), elementEntity); // create element is done by collaboration store return new Response(Void.TYPE); } @@ -55,4 +123,46 @@ public class CassandraStateStorePluginImpl extends StateStoreImpl { return new Response(Void.TYPE); } + @Override + public Response> listElements(SessionContext context, + ElementContext elementContext, + Id elementId) { + return new Response(elementPrivateStore.listSubs(context, elementContext, elementId).stream() + .map(elementEntity -> ZusammenPluginUtil.getStateElement(elementContext, elementEntity)) + .collect(Collectors.toList())); + + } + + @Override + public Response getElement(SessionContext context, ElementContext elementContext, + Id elementId) { + + return new Response(elementPrivateStore.get(context, elementContext, elementId) + .map(elementEntity -> ZusammenPluginUtil + .getStateElement(elementContext, elementEntity)) + .orElse + (null)); + + + } + + private ItemVersion getItemVersion(SessionContext context, String spaceName, Id itemId, + VersionEntity versionEntity) { + + ItemVersionData itemVersionData = getElementRepository(context) + .get(context, new ElementEntityContext(spaceName, itemId, versionEntity.getId(), null), + new VersionDataElement()) + .map(ZusammenPluginUtil::convertToVersionData) + .orElseThrow(() -> new IllegalStateException("Version must have data")); + + return convertToItemVersion(versionEntity, itemVersionData); + } + + protected VersionDao getVersionDao(SessionContext context) { + return VersionDaoFactory.getInstance().createInterface(context); + } + + protected ElementRepository getElementRepository(SessionContext context) { + return ElementRepositoryFactory.getInstance().createInterface(context); + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/resources/factoryConfiguration.json index cd1e293b4b..841e005709 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/resources/factoryConfiguration.json +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/resources/factoryConfiguration.json @@ -1,3 +1,8 @@ { - "org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory": "org.openecomp.core.zusammen.plugin.dao.impl.CassandraElementRepositoryFactory" + "org.openecomp.core.zusammen.plugin.dao.VersionDaoFactory": "org.openecomp.core.zusammen.plugin.dao.impl.cassandra.VersionDaoFactoryImpl", + "org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory": "org.openecomp.core.zusammen.plugin.dao.impl.cassandra.ElementRepositoryFactoryImpl", + "org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepositoryFactory": "org.openecomp.core.zusammen.plugin.dao.impl.cassandra.VersionSynchronizationStateRepositoryFactoryImpl", + "org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepositoryFactory": "org.openecomp.core.zusammen.plugin.dao.impl.cassandra.ElementSynchronizationStateRepositoryFactoryImpl", + "org.openecomp.core.zusammen.plugin.dao.VersionStageRepositoryFactory": "org.openecomp.core.zusammen.plugin.dao.impl.cassandra.VersionStageRepositoryFactoryImpl", + "org.openecomp.core.zusammen.plugin.dao.ElementStageRepositoryFactory": "org.openecomp.core.zusammen.plugin.dao.impl.cassandra.ElementStageRepositoryFactoryImpl" } \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/TestUtils.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/TestUtils.java new file mode 100644 index 0000000000..79e918c808 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/TestUtils.java @@ -0,0 +1,64 @@ +/* + * Copyright © 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.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.UserInfo; +import com.amdocs.zusammen.datatypes.item.ElementContext; +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.Relation; + +import java.util.Arrays; + +public class TestUtils { + + public static SessionContext createSessionContext(UserInfo user, String tenant) { + SessionContext context = new SessionContext(); + context.setUser(user); + context.setTenant(tenant); + return context; + } + + public static ElementContext createElementContext(Id itemId, Id versionId) { + ElementContext elementContext = new ElementContext(); + elementContext.setItemId(itemId); + elementContext.setVersionId(versionId); + return elementContext; + } + + public static Info createInfo(String value) { + Info info = new Info(); + info.setName(value); + info.addProperty("Name", "name_" + value); + info.addProperty("Desc", "desc_" + value); + return info; + } + + public static ItemVersion createItemVersion(Id id, Id baseId, String name, boolean dirty) { + ItemVersion version = new ItemVersion(); + version.setId(id); + version.setBaseId(baseId); + ItemVersionData data = new ItemVersionData(); + data.setInfo(TestUtils.createInfo(name)); + data.setRelations(Arrays.asList(new Relation(), new Relation())); + version.setData(data); + return version; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStoreTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStoreTest.java new file mode 100644 index 0000000000..4c4621e98b --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStoreTest.java @@ -0,0 +1,237 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +public class VersionCollaborationStoreTest {/* + private static final String TENANT = "test"; + private static final String USER = "ItemStateStoreTest_user"; + private static final SessionContext context = + TestUtils.createSessionContext(new UserInfo(USER), TENANT); + + @Mock + private VersionDao versionDaoMock; + @Mock + private ElementStore elementCollaborationStore; + @Spy + @InjectMocks + private VersionStore versionCollaborationStore; + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + when(versionCollaborationStore.getVersionDao(anyObject())).thenReturn(versionDaoMock); + } +*//* + @Test + public void testListPrivateItemVersions() throws Exception { + testListItemVersions(Space.PRIVATE, USER); + } + + @Test + public void testListPublicItemVersions() throws Exception { + testListItemVersions(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE); + } + + @Test + public void testIsPrivateItemVersionExist() throws Exception { + testIsItemVersionExist(Space.PRIVATE, USER); + } + + @Test + public void testIsPublicItemVersionExist() throws Exception { + testIsItemVersionExist(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE); + } + + @Test + public void testIsItemVersionExistWhenNot() throws Exception { + Id itemId = new Id(); + Id versionId = new Id(); + doReturn(Optional.empty()).when(versionDaoMock).get(context, USER, itemId, versionId); + + boolean itemExist = + versionCollaborationStore.isItemVersionExist(context, Space.PRIVATE, itemId, versionId); + Assert.assertFalse(itemExist); + } + + @Test + public void testGetPrivateItemVersion() throws Exception { + testGetItemVersion(Space.PRIVATE, USER); + } + + @Test + public void testGetPublicItemVersion() throws Exception { + testGetItemVersion(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE); + } + + + @Test + public void testGetNonExistingItemVersion() throws Exception { + Id itemId = new Id(); + Id versionId = new Id(); + doReturn(Optional.empty()).when(versionDaoMock).get(context, USER, itemId, versionId); + + ItemVersion itemVersion = + versionCollaborationStore.getItemVersion(context, Space.PRIVATE, itemId, versionId); + Assert.assertNull(itemVersion); + }*//* + + @Test + public void testCreatePrivateItemVersion() throws Exception { + testCreateItemVersion(Space.PRIVATE, USER, null); + } + + @Test + public void testCreatePrivateItemVersionBasedOn() throws Exception { + testCreateItemVersion(Space.PRIVATE, USER, new Id()); + } + + @Test + public void testCreatePublicItemVersion() throws Exception { + testCreateItemVersion(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE, null); + } + + @Test + public void testCreatePublicItemVersionBasedOn() throws Exception { + testCreateItemVersion(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE, new Id()); + } + + @Test + public void testUpdatePrivateItemVersion() throws Exception { + testUpdateItemVersion(Space.PRIVATE, USER); + } + + @Test + public void testUpdatePublicItemVersion() throws Exception { + testUpdateItemVersion(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE); + } + + @Test + public void testDeletePrivateItemVersion() throws Exception { + testDeleteItemVersion(Space.PRIVATE, USER); + } + + @Test + public void testDeletePublicItemVersion() throws Exception { + testDeleteItemVersion(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE); + } + + @Test + public void testPublishItemVersionWhenNotDirty() throws Exception { + Id itemId = new Id(); + ItemVersion version = TestUtils.createItemVersion(new Id(), null, "v1", false); + doReturn(Optional.of(version)).when(versionDaoMock).get(context, USER, itemId, version.getId()); + + versionCollaborationStore.publishItemVersion(context, itemId, version.getId(), "message"); + + } +*//* + private void testIsItemVersionExist(Space space, String spaceName) { + Id itemId = new Id(); + ItemVersion retrievedVersion = TestUtils.createItemVersion(new Id(), null, "v1"); + doReturn(Optional.of(retrievedVersion)).when(versionDaoMock) + .get(context, spaceName, itemId, retrievedVersion.getId()); + + boolean itemExist = + versionCollaborationStore + .isItemVersionExist(context, space, itemId, retrievedVersion.getId()); + Assert.assertTrue(itemExist); + } + + private void testGetItemVersion(Space space, String spaceName) throws Exception { + Id itemId = new Id(); + ItemVersion retrievedVersion = TestUtils.createItemVersion(new Id(), null, "v1"); + doReturn(Optional.of(retrievedVersion)).when(versionDaoMock) + .get(context, spaceName, itemId, retrievedVersion.getId()); + + ItemVersion itemVersion = + versionCollaborationStore.getItemVersion(context, space, itemId, retrievedVersion.getId()); + Assert.assertEquals(itemVersion, retrievedVersion); + } + + private void testListItemVersions(Space space, String spaceName) { + Id itemId = new Id(); + ItemVersion v1 = TestUtils.createItemVersion(new Id(), null, "v1"); + ItemVersion v2 = TestUtils.createItemVersion(new Id(), v1.getId(), "v2"); + ItemVersion v3 = TestUtils.createItemVersion(new Id(), v2.getId(), "v3"); + List retrievedVersions = Arrays.asList(v1, v2, v3); + doReturn(retrievedVersions).when(versionDaoMock).list(context, spaceName, itemId); + + Collection itemVersions = + versionCollaborationStore.listItemVersions(context, space, itemId); + Assert.assertEquals(itemVersions, retrievedVersions); + }*//* + + private void testCreateItemVersion(Space space, String spaceName, Id baseId) { + Id itemId = new Id(); + ItemVersion v1 = TestUtils.createItemVersion(new Id(), baseId, "v1", false); + List baseVersionElements = mockVersionElements(spaceName, itemId, baseId); + + ArgumentCaptor versionCaptor = ArgumentCaptor.forClass(ItemVersion.class); + + Date creationTime = new Date(); + versionCollaborationStore + .createItemVersion(context, space, itemId, baseId, v1.getId(), v1.getData(), creationTime); + + verify(versionDaoMock).create(eq(context), eq(spaceName), eq(itemId), versionCaptor.capture()); + //baseId, v1.getId(),v1.getData(), creationTime); + + ItemVersion capturedVersion = versionCaptor.getValue(); + Assert.assertEquals(baseId, capturedVersion.getBaseId()); + Assert.assertEquals(v1.getId(), capturedVersion.getId()); + Assert.assertEquals(v1.getData(), capturedVersion.getData()); + Assert.assertEquals(creationTime, capturedVersion.getCreationTime()); +*//* verify(versionDaoMock) + .create(anyObject(), anyObject(), anyObject(), anyObject(), anyObject(), anyObject(), + anyObject());*//* + +*//* if (baseId != null) { + baseVersionElements.forEach(element -> + verify(elementCollaborationStore).create(eq(context), + eq(new ElementEntityContext(spaceName, itemId, v1.getId())), + eq(element))); + } else { + verifyZeroInteractions(elementCollaborationStore); + }*//* + } + + private void testUpdateItemVersion(Space space, String spaceName) { + Id itemId = new Id(); + ItemVersion retrievedVersion = TestUtils.createItemVersion(new Id(), null, "v1", false); + doReturn(Optional.of(retrievedVersion)).when(versionDaoMock) + .get(context, spaceName, itemId, retrievedVersion.getId()); + + ItemVersionData updatedData = new ItemVersionData(); + updatedData.setInfo(TestUtils.createInfo("v1 updated")); + updatedData.setRelations( + Arrays.asList(new Relation(), new Relation(), new Relation(), new Relation())); + versionCollaborationStore.updateItemVersion( + context, space, itemId, retrievedVersion.getId(), updatedData, new Date()); + + *//*verify(versionDaoMock) + .update(context, spaceName, itemId, retrievedVersion.getId(), updatedData, modificationTime);*//* + verify(versionDaoMock) + .update(anyObject(), anyObject(), anyObject(), anyObject()); + + } + + private void testDeleteItemVersion(Space space, String spaceName) { + Id itemId = new Id(); + Id versionId = new Id(); + + List versionElements = mockVersionElements(spaceName, itemId, versionId); + versionCollaborationStore.deleteItemVersion(context, space, itemId, versionId); + +*//* versionElements.forEach(element -> + verify(elementCollaborationStore).delete(eq(context), + eq(new ElementEntityContext(spaceName, itemId, versionId)), + eq(element)));*//* + verify(versionDaoMock).delete(context, spaceName, itemId, versionId); + } + + private List mockVersionElements(String spaceName, Id itemId, Id versionId) { + ElementEntity elm1 = new ElementEntity(new Id()); + ElementEntity elm2 = new ElementEntity(new Id()); + List baseVersionElements = Arrays.asList(elm1, elm2); +*//* doReturn(baseVersionElements).when(elementCollaborationStore) + .list(eq(context), eq(new ElementEntityContext(spaceName, itemId, versionId)));*//* + return baseVersionElements; + }*/ +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImplTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImplTest.java new file mode 100644 index 0000000000..7f137b01b0 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImplTest.java @@ -0,0 +1,167 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.UserInfo; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.Resolution; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.core.zusammen.plugin.collaboration.TestUtils; +import org.openecomp.core.zusammen.plugin.dao.ElementStageRepository; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Date; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.same; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class ElementStageStoreImplTest { + private static final UserInfo USER = new UserInfo("user"); + private static final SessionContext context = TestUtils.createSessionContext(USER, "test"); + private static final ElementContext elementContext = + TestUtils.createElementContext(new Id(), new Id()); + + @Mock + private ElementStageRepository elementStageRepositoryMock; + @Spy + private ElementStageStoreImpl elementStageStore; + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + when(elementStageStore.getElementStageRepository(anyObject())) + .thenReturn(elementStageRepositoryMock); + } + + @Test + public void testListIds() throws Exception { + + } + + @Test + public void testGet() throws Exception { + + } + + @Test + public void testGetConflicted() throws Exception { + + } + + @Test + public void testHasConflicts() throws Exception { + + } + + @Test + public void testListConflictedDescriptors() throws Exception { + + } + + @Test + public void testCreate() throws Exception { + + } + + @Test + public void testDelete() throws Exception { + + } + + @Test + public void testResolveConflictWhenNotStaged() throws Exception { + doReturn(Optional.empty()) + .when(elementStageRepositoryMock).get(anyObject(), anyObject(), anyObject()); + elementStageStore + .resolveConflict(context, elementContext, new ElementEntity(new Id()), Resolution.YOURS); + } + + @Test + public void testResolveConflictWhenNotConflicted() throws Exception { + Id elementId = new Id(); + StageEntity stagedElement = + new StageEntity<>(new ElementEntity(elementId), new Date()); + doReturn(Optional.of(stagedElement)) + .when(elementStageRepositoryMock).get(anyObject(), anyObject(), anyObject()); + elementStageStore + .resolveConflict(context, elementContext, new ElementEntity(elementId), Resolution.YOURS); + } + + @Test + public void testResolveConflictByYours() throws Exception { + Id elementId = new Id(); + StageEntity stagedElement = + new StageEntity<>(new ElementEntity(elementId), new Date()); + stagedElement.setAction(Action.UPDATE); + stagedElement.setConflicted(true); + + doReturn(Optional.of(stagedElement)) + .when(elementStageRepositoryMock).get(anyObject(), anyObject(), anyObject()); + + elementStageStore + .resolveConflict(context, elementContext, new ElementEntity(elementId), Resolution.YOURS); + + verify(elementStageRepositoryMock).markAsNotConflicted(same(context), + eq(new ElementEntityContext(USER.getUserName(), elementContext)), + same(stagedElement.getEntity()), same(Action.IGNORE)); + } + + @Test + public void testResolveConflictByYoursWithRelated() throws Exception { + Id elementId = new Id(); + StageEntity stagedElement = + new StageEntity<>(new ElementEntity(elementId), new Date()); + stagedElement.setAction(Action.UPDATE); + stagedElement.setConflicted(true); + ElementEntity relatedElement1 = new ElementEntity(new Id()); + ElementEntity relatedElement2 = new ElementEntity(new Id()); + ElementEntity relatedElement3 = new ElementEntity(new Id()); + Set relatedElements = new HashSet<>(); + relatedElements.add(relatedElement1); + relatedElements.add(relatedElement2); + relatedElements.add(relatedElement3); + stagedElement.setConflictDependents(relatedElements); + + doReturn(Optional.of(stagedElement)) + .when(elementStageRepositoryMock).get(anyObject(), anyObject(), anyObject()); + + elementStageStore + .resolveConflict(context, elementContext, new ElementEntity(elementId), Resolution.YOURS); + + ElementEntityContext elementEntityContext = + new ElementEntityContext(USER.getUserName(), elementContext); + verify(elementStageRepositoryMock).markAsNotConflicted(same(context), eq(elementEntityContext), + same(stagedElement.getEntity()), same(Action.IGNORE)); + verify(elementStageRepositoryMock).markAsNotConflicted(same(context), eq(elementEntityContext), + same(relatedElement1), same(Action.IGNORE)); + verify(elementStageRepositoryMock).markAsNotConflicted(same(context), eq(elementEntityContext), + same(relatedElement2), same(Action.IGNORE)); + verify(elementStageRepositoryMock).markAsNotConflicted(same(context), eq(elementEntityContext), + same(relatedElement3), same(Action.IGNORE)); + } + + @Test + public void testResolveConflictByTheirs() throws Exception { + + } + + @Test + public void testResolveConflictByTheirsWithRelated() throws Exception { + + } + +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/pom.xml b/openecomp-be/lib/openecomp-core-lib/pom.xml index 3784593668..51faa10566 100644 --- a/openecomp-be/lib/openecomp-core-lib/pom.xml +++ b/openecomp-be/lib/openecomp-core-lib/pom.xml @@ -20,5 +20,6 @@ /openecomp-utilities-lib /openecomp-config-lib /openecomp-zusammen-lib + /openecomp-session-lib diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/pom.xml b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/pom.xml index 2900785b55..fa3533fde9 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/pom.xml +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/pom.xml @@ -13,6 +13,23 @@ + + org.openecomp.sdc.common + openecomp-configuration-management-core + ${openecomp.sdc.common.version} + runtime + + + org.slf4j + slf4j-log4j12 + + + + + org.openecomp.sdc.common + openecomp-configuration-management-api + ${openecomp.sdc.common.version} + org.openecomp.sdc.core openecomp-facade-core @@ -33,6 +50,11 @@ openecomp-sdc-versioning-api ${project.version} + + org.openecomp.sdc + openecomp-item-permissions-core + ${project.version} + 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 211d9a21b2..ca0a3c79d7 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 @@ -20,16 +20,24 @@ package org.openecomp.sdc.healing.api; +import org.openecomp.sdc.datatypes.model.ItemType; import org.openecomp.sdc.healing.types.HealCode; +import org.openecomp.sdc.healing.types.HealerType; +import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Map; import java.util.Optional; /** * Created by Talio on 11/29/2016. */ public interface HealingManager { - Object heal(HealCode code, Map healParameters); - Optional healAll(Map healParameters); + /** + * @return healed version, if healing was not performed - Optional.empty. + */ + Optional healItemVersion(String itemId, Version version, ItemType itemType, + boolean force); + + Object heal(String itemId, Version version, HealerType healerType, HealCode code, + ItemType itemType); } 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 new file mode 100644 index 0000000000..b766bd8d88 --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/dao/HealingDao.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.healing.dao; + +import java.util.Optional; + +/** + * Created by ayalaben on 10/17/2017 + */ +public interface HealingDao { + + Optional getItemHealingFlag(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 8e8d633b42..5e375ee046 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 @@ -20,9 +20,9 @@ package org.openecomp.sdc.healing.factory; -import org.openecomp.sdc.healing.api.HealingManager; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; +import org.openecomp.sdc.healing.api.HealingManager; /** * Created by Talio on 11/29/2016. 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 eb2f9a74d2..38afd1342a 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 @@ -20,11 +20,11 @@ package org.openecomp.sdc.healing.interfaces; -import java.util.Map; +import org.openecomp.sdc.versioning.dao.types.Version; /** * Created by Talio on 11/29/2016. */ public interface Healer { - Object heal(Map healingParams) throws Exception; + Object 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 new file mode 100644 index 0000000000..06301279a9 --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/ConfigConstants.java @@ -0,0 +1,5 @@ +package org.openecomp.sdc.healing.types; + +public class ConfigConstants { + 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/HealerType.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealerType.java new file mode 100644 index 0000000000..3355a3cd92 --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealerType.java @@ -0,0 +1,6 @@ +package org.openecomp.sdc.healing.types; + +public enum HealerType { + data, + structure +} diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealingContext.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealingContext.java deleted file mode 100644 index 2ad143a0ec..0000000000 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealingContext.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.openecomp.sdc.healing.types; -import org.openecomp.sdc.versioning.dao.types.Version; - -/** - * Created by TALIO on 7/3/2017. - */ -public class HealingContext { - private String vspId; - private Version version; - private String user; - - public HealingContext(String vspId, Version version, String user) { - this.vspId = vspId; - this.version = version; - this.user = user; - } - - public String getVspId() { - return vspId; - } - - public void setVspId(String vspId) { - this.vspId = vspId; - } - - public Version getVersion() { - return version; - } - - public void setVersion(Version version) { - this.version = version; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } -} 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 new file mode 100644 index 0000000000..921f418118 --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/dao/impl/HealingDaoImpl.java @@ -0,0 +1,46 @@ +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 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); + } + + + @Accessor + interface HealingAccessor { + + @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 84aff4327d..5a283f954b 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 @@ -21,15 +21,17 @@ package org.openecomp.sdc.healing.impl; import org.openecomp.sdc.healing.api.HealingManager; +import org.openecomp.sdc.healing.dao.impl.HealingDaoImpl; import org.openecomp.sdc.healing.factory.HealingManagerFactory; +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(); + 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 1c895ffc6f..59c6732cab 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 @@ -24,34 +24,147 @@ import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.datatypes.model.ItemType; import org.openecomp.sdc.healing.api.HealingManager; +import org.openecomp.sdc.healing.dao.HealingDao; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.healing.types.HealCode; +import org.openecomp.sdc.healing.types.HealerType; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.versioning.VersioningManager; +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.lang.reflect.InvocationTargetException; import java.util.ArrayList; +import java.util.Collection; +import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; +import java.util.stream.Collectors; /** * Created by Talio on 11/29/2016. */ public class HealingManagerImpl implements HealingManager { - private static String HEALING_CONF_FILE = "healingConfiguration.json"; - private static Map healerCodeToImplClass = initHealers(); + + 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(String itemId, Version version, ItemType itemType, + boolean force) { + String user = getUser(); + if (force || isPrivateHealingNeededByFlag(itemId, version.getId(), user)) { + version = versioningManager.get(itemId, version); + Version origVersion = version; + if (version.getStatus() == VersionStatus.Certified) { + Optional newVersion = createNewVersion(itemId, version); + if (!newVersion.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(); + } + version = newVersion.get(); + } + + doHeal(itemId, version, origVersion, itemType, user, force); + return Optional.of(version); + } + return Optional.empty(); + } + + private void doHeal(String itemId, Version version, Version origVersion, + ItemType itemType, String user, boolean force) { + Optional privateFailureMessages = + healPrivate(itemId, version, origVersion, getItemHealers(itemType), user); + + Optional publicFailureMessages = + force || origVersion.getStatus() == VersionStatus.Certified || + isPublicHealingNeededByFlag(itemId, origVersion.getId()) + ? healPublic(itemId, version, origVersion, getItemHealers(itemType), user) + : Optional.empty(); + + if (privateFailureMessages.isPresent() || publicFailureMessages.isPresent()) { + throw new RuntimeException( + publicFailureMessages.orElse("") + " " + privateFailureMessages.orElse("")); + } + } + + private Optional healPrivate(String itemId, Version version, Version origVersion, + Map> itemHealers, String user) { + if (origVersion.getStatus() != VersionStatus.Certified) { + itemHealers.remove(HealerType.structure.name()); + } + + Optional privateHealingFailureMessages = executeHealers(itemId, version, itemHealers); + markAsHealed(itemId, origVersion.getId(), user); + return privateHealingFailureMessages; + } + + private Optional healPublic(String itemId, Version version, Version origVersion, + Map> itemHealers, String user) { + Optional healingFailureMessages = origVersion.getStatus() == VersionStatus.Certified + ? Optional.empty() + : healPublic(itemId, version, itemHealers, user); + + markAsHealed(itemId, origVersion.getId(), PUBLIC_USER); + return healingFailureMessages; + } + + private Optional healPublic(String itemId, Version version, + Map> itemHealers, String user) { + SessionContextProviderFactory.getInstance().createInterface() + .create(user + HEALING_USER_SUFFIX); + + versioningManager.sync(itemId, version); + + Optional healingFailureMessages = executeHealers(itemId, version, itemHealers); + 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); + return healingFailureMessages; + } + + private Optional createNewVersion(String itemId, Version version) { + Version newVersion = new Version(); + newVersion.setBaseId(version.getId()); + try { + return Optional.of(versioningManager.create(itemId, newVersion, VersionCreationMethod.major)); + } catch (Exception e) { + return Optional.empty(); + } + } @Override - public Object heal(HealCode code, Map healParameters) { + public Object heal(String itemId, Version version, HealerType healerType, HealCode code, + ItemType itemType) { + String healerClassName = getItemHealers(itemType).get(healerType.name()).get(code.name()); ArrayList healingFailureMessages = new ArrayList<>(); - Object result = - heal(healParameters, healerCodeToImplClass.get(code.name()), healingFailureMessages); + Object result = executeHealer(itemId, version, healerClassName, healingFailureMessages); if (!healingFailureMessages.isEmpty()) { throw new RuntimeException(CommonMethods.listToSeparatedString(healingFailureMessages, '\n')); @@ -59,46 +172,77 @@ public class HealingManagerImpl implements HealingManager { return result; } - @Override - public Optional healAll(Map healParameters) { - ArrayList healingFailureMessages = new ArrayList<>(); + private Optional executeHealers(String itemId, Version version, + Map> itemHealers) { + List healers = itemHealers.values().stream() + .map(Map::values) + .flatMap(Collection::stream) + .collect(Collectors.toList()); - for (String implClassName : healerCodeToImplClass.values()) { - heal(healParameters, implClassName, healingFailureMessages); + List healingFailureMessages = new ArrayList<>(); + for (String implClassName : healers) { + executeHealer(itemId, version, implClassName, healingFailureMessages); } - return healingFailureMessages.isEmpty() ? Optional.empty() + return healingFailureMessages.isEmpty() + ? Optional.empty() : Optional.of(CommonMethods.listToSeparatedString(healingFailureMessages, '\n')); } - private Object heal(Map healParameters, String healerImplClassName, - ArrayList healingFailureMessages) { - Healer healerImpl; + + private Object executeHealer(String itemId, Version version, String healerClassName, + List healingFailureMessages) { + Healer healer; try { - healerImpl = getHealerImplInstance(healerImplClassName); + healer = getHealerImplInstance(healerClassName); } catch (Exception e) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.SELF_HEALING, ErrorLevel.ERROR.name(), LoggerErrorCode .DATA_ERROR.getErrorCode(), LoggerErrorDescription.CANT_HEAL); healingFailureMessages .add(String.format(Messages.CANT_LOAD_HEALING_CLASS.getErrorMessage(), - healerImplClassName)); + healerClassName)); return null; } try { - return healerImpl.heal(healParameters); + return healer.heal(itemId, version); } catch (Exception e) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.SELF_HEALING, ErrorLevel.ERROR.name(), LoggerErrorCode .DATA_ERROR.getErrorCode(), LoggerErrorDescription.CANT_HEAL); - healingFailureMessages.add(e.getMessage() + " ,healer name :" + healerImplClassName); + healingFailureMessages.add(e.getMessage() + " ,healer name :" + healerClassName); } return null; } - private static Map initHealers() { - return FileUtils.readViaInputStream(HEALING_CONF_FILE, stream -> JsonUtil.json2Object(stream, Map.class)); + private boolean isPrivateHealingNeededByFlag(String itemId, String version, String user) { + Optional userHealingFlag = getHealingFlag(itemId, version, user); + return userHealingFlag.isPresent() + ? userHealingFlag.get() + : isPublicHealingNeededByFlag(itemId, version); + } + + private boolean isPublicHealingNeededByFlag(String itemId, String versionId) { + Optional publicHealingFlag = getHealingFlag(itemId, versionId, PUBLIC_USER); + return publicHealingFlag.isPresent() && publicHealingFlag.get(); + } + + private Optional getHealingFlag(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 Map> getItemHealers(ItemType itemType) { + // TODO: 11/29/2017 create objects to hold this configuration + + // load once from the json file and use the relevant healers (by itemType, healerType) as needed. + Map healingConfig = FileUtils + .readViaInputStream(HEALERS_BY_ENTITY_TYPE_FILE, + stream -> JsonUtil.json2Object(stream, Map.class)); + return (Map>) healingConfig.get(itemType.name()); } private Healer getHealerImplInstance(String implClassName) @@ -106,4 +250,9 @@ public class HealingManagerImpl implements HealingManager { NoSuchMethodException, ClassNotFoundException { return (Healer) Class.forName(implClassName).getConstructor().newInstance(); } + + 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/resources/entityHealingConfiguration.json b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/entityHealingConfiguration.json new file mode 100644 index 0000000000..ab8a1dfb4f --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/entityHealingConfiguration.json @@ -0,0 +1,12 @@ +{ + "vsp": { + "structure": { + "ownerHealer": "org.openecomp.sdc.healing.healers.OwnerHealer" + } + }, + "vlm": { + "structure": { + "ownerHealer": "org.openecomp.sdc.healing.healers.OwnerHealer" + } + } +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/healingConfiguration.json b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/healingConfiguration.json index 4e1b0df97a..85eec77c56 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/healingConfiguration.json +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/healingConfiguration.json @@ -1,13 +1,19 @@ { - "FILE_DATA_STRUCTURE_HEALER" : "org.openecomp.sdc.healing.healers.FileDataStructureHealer", - "QUESTIONNAIRE_HEALER" : "org.openecomp.sdc.healing.healers.VspQuestionnaireHealer", - "COMPOSITION_DATA_HEALER" : "org.openecomp.sdc.healing.healers.CompositionDataHealer", - "SUB_ENTITIES_HEALER" : "org.openecomp.sdc.healing.healers.SubEntitiesQuestionnaireHealer", - "ONBOARDING_METHOD_HEALER" : "org.openecomp.sdc.healing.healers.VspOnboardingMethodHealer", - "NIC_DATA_HEALER" : "org.openecomp.sdc.healing.healers.NicDataHealer", - "COMPONENT_QUESTIONNAIRE_HEALER" : "org.openecomp.sdc.healing.healers.ComponentQuestionnaireHealer", - "HEAT_TOSCA_TRANSLATION_HEALER" : "org.openecomp.sdc.healing.healers.HeatToToscaTranslationHealer", - "VLM_VERSION_HEALER" : "org.openecomp.sdc.healing.healers.VlmVersionHealer", - "VALIDATION_STRUCTURE_HEALER" : "org.openecomp.sdc.healing.healers.ValidationStructureHealer", - "FORWARDER_CAPABILITY_HEALER" : "org.openecomp.sdc.healing.healers.ForwarderCapabilityHealer" + "VendorSoftwareProduct" : { + "VSP_OWNER_HEALER" : "org.openecomp.sdc.healing.healers.VspOwnerHealer", + "FILE_DATA_STRUCTURE_HEALER" : "org.openecomp.sdc.healing.healers.FileDataStructureHealer", + "QUESTIONNAIRE_HEALER" : "org.openecomp.sdc.healing.healers.VspQuestionnaireHealer", + "COMPOSITION_DATA_HEALER" : "org.openecomp.sdc.healing.healers.CompositionDataHealer", + "SUB_ENTITIES_HEALER" : "org.openecomp.sdc.healing.healers.SubEntitiesQuestionnaireHealer", + "ONBOARDING_METHOD_HEALER" : "org.openecomp.sdc.healing.healers.VspOnboardingMethodHealer", + "NIC_DATA_HEALER" : "org.openecomp.sdc.healing.healers.NicDataHealer", + "COMPONENT_QUESTIONNAIRE_HEALER" : "org.openecomp.sdc.healing.healers.ComponentQuestionnaireHealer", + "HEAT_TOSCA_TRANSLATION_HEALER" : "org.openecomp.sdc.healing.healers.HeatToToscaTranslationHealer", + "VLM_VERSION_HEALER" : "org.openecomp.sdc.healing.healers.VlmVersionHealer", + "VALIDATION_STRUCTURE_HEALER" : "org.openecomp.sdc.healing.healers.ValidationStructureHealer", + "FORWARDER_CAPABILITY_HEALER" : "org.openecomp.sdc.healing.healers.ForwarderCapabilityHealer" + }, + "VendorLicenseModel" : { + "VLM_OWNER_HEALER" : "org.openecomp.sdc.healing.healers.VlmOwnerHealer" + } } \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/pom.xml b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/pom.xml index c54f724b9a..1359e6921d 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/pom.xml +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/pom.xml @@ -39,6 +39,11 @@ openecomp-sdc-vendor-license-api ${project.version} + + org.openecomp.sdc + openecomp-item-permissions-impl + ${project.version} + diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealer.java index 50e76781b3..83395e015a 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealer.java @@ -4,7 +4,6 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; @@ -19,7 +18,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; import org.openecomp.sdc.versioning.dao.types.Version; import java.util.Collection; -import java.util.Map; import java.util.Objects; @@ -57,11 +55,9 @@ public class ComponentQuestionnaireHealer implements Healer { } @Override - public Object heal(Map healingParams) throws Exception { - mdcDataDebugMessage.debugEntryMessage("VSP ID", - (String) healingParams.get(SdcCommon.VSP_ID)); - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); + public Object heal(String vspId, Version version) throws Exception { + mdcDataDebugMessage.debugEntryMessage("VSP ID", vspId); + Collection componentEntities = componentDao.list(new ComponentEntity(vspId, version, null)); componentEntities.forEach(componentEntity -> { diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/CompositionDataHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/CompositionDataHealer.java index 6fc8cfef61..e7a5e30f2d 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/CompositionDataHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/CompositionDataHealer.java @@ -31,7 +31,6 @@ import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.sdc.common.utils.CommonUtil; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; @@ -57,7 +56,7 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionDataExtractorFactory; import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionEntityDataManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor; @@ -69,7 +68,6 @@ import org.openecomp.sdc.versioning.dao.types.Version; import java.io.IOException; import java.util.Collection; -import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -102,14 +100,10 @@ public class CompositionDataHealer implements Healer { } @Override - public Optional heal(Map healingParams) throws IOException { + public Optional heal(String vspId, + Version version) throws IOException { mdcDataDebugMessage.debugEntryMessage(null); - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = VERSION00.equals(healingParams.get(SdcCommon.VERSION)) - ? VERSION01 - : (Version) healingParams.get(SdcCommon.VERSION); - Collection componentEntities = componentDao.list(new ComponentEntity(vspId, version, null)); Collection nicEntities = nicDao.listByVsp(vspId, version); @@ -131,7 +125,7 @@ public class CompositionDataHealer implements Healer { serviceModels.get()) : null; } - if(serviceModels.isPresent()) { + if (serviceModels.isPresent()) { compositionData = getCompositionDataForHealing(vspId, version, serviceModels.get()); HealNfodData(vspId, version, compositionData); @@ -150,16 +144,16 @@ public class CompositionDataHealer implements Healer { if (CollectionUtils.isEmpty(computeEntities) && CollectionUtils.isEmpty(imageEntities)) { for (Component component : compositionData.getComponents()) { String componentId = null; - for (ComponentEntity componentEntity:componentEntities) { + for (ComponentEntity componentEntity : componentEntities) { if (componentEntity.getComponentCompositionData().getName().equals(component.getData() .getName())) { componentId = componentEntity.getId(); break; } } - compositionEntityDataManager.saveComputesFlavorByComponent(vspId,version,component, + compositionEntityDataManager.saveComputesFlavorByComponent(vspId, version, component, componentId); - compositionEntityDataManager.saveImagesByComponent(vspId,version,component, + compositionEntityDataManager.saveImagesByComponent(vspId, version, component, componentId); } @@ -228,13 +222,15 @@ public class CompositionDataHealer implements Healer { } private Optional> getServiceModelForHealing(String - vspId, Version + vspId, + Version version) throws IOException { mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); - UploadDataEntity uploadData = - orchestrationTemplateDataDao.getOrchestrationTemplate(vspId, version); + /*OrchestrationTemplateEntity uploadData = + vendorSoftwareProductDao.getUploadData(new OrchestrationTemplateEntity(vspId, version));*/ + OrchestrationTemplateEntity uploadData = orchestrationTemplateDataDao.get(vspId, version); if (Objects.isNull(uploadData) || Objects.isNull(uploadData.getContentData())) { return Optional.empty(); @@ -259,7 +255,7 @@ public class CompositionDataHealer implements Healer { .getNonUnifiedToscaServiceModel())); } - private TranslatorOutput getTranslatorOutputForHealing(UploadDataEntity uploadData) { + private TranslatorOutput getTranslatorOutputForHealing(OrchestrationTemplateEntity uploadData) { FileContentHandler fileContentHandler; try { diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/FileDataStructureHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/FileDataStructureHealer.java index 4a0a5f9d63..6e49c9a6cf 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/FileDataStructureHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/FileDataStructureHealer.java @@ -24,33 +24,23 @@ import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.sdc.common.utils.CommonUtil; -import org.openecomp.sdc.common.utils.SdcCommon; -import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.factory.CandidateServiceFactory; -import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService; import org.openecomp.sdc.vendorsoftwareproduct.services.utils.CandidateEntityBuilder; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure; import org.openecomp.sdc.versioning.dao.types.Version; import java.util.HashMap; -import java.util.List; -import java.util.Map; import java.util.Optional; public class FileDataStructureHealer implements Healer { - private static final OrchestrationTemplateDao orchestrationTemplateDataDao = - OrchestrationTemplateDaoFactory.getInstance().createInterface(); - private static CandidateService candidateService = - CandidateServiceFactory.getInstance().createInterface(); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); @@ -59,64 +49,55 @@ public class FileDataStructureHealer implements Healer { } @Override - public Optional heal(Map healingParams) throws Exception { - - + public Optional heal(String vspId, + Version version) throws Exception { mdcDataDebugMessage.debugEntryMessage(null); - Optional healingResult = Optional.empty(); - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - String user = (String) healingParams.get(SdcCommon.USER); + OrchestrationTemplateCandidateDao candidateDao = + OrchestrationTemplateCandidateDaoFactory.getInstance().createInterface(); + + OrchestrationTemplateCandidateData candidateData = candidateDao.get(vspId, version); - UploadDataEntity uploadData = - orchestrationTemplateDataDao.getOrchestrationTemplate(vspId,version); - if (uploadData == null || uploadData.getContentData() == null) { - FilesDataStructure emptyFilesDataStructure = new FilesDataStructure(); - return Optional.of(emptyFilesDataStructure); + if (candidateData == null || candidateData.getContentData() == null || + candidateData.getFilesDataStructure() != null) { + return Optional.of(new FilesDataStructure()); } - Optional candidateFileDataStructure = - candidateService.getOrchestrationTemplateCandidateFileDataStructure(vspId, version); + Optional filesDataStructure = + healFilesDataStructure(vspId, version, candidateData); - if (!candidateFileDataStructure.isPresent()) { - healingResult = healFilesDataStructure(vspId, version, user, uploadData); - } + filesDataStructure + .ifPresent(structure -> candidateDao.updateStructure(vspId, version, structure)); mdcDataDebugMessage.debugExitMessage(null); - return healingResult; + return filesDataStructure; } - private Optional healFilesDataStructure(String vspId, Version version, - String user, - UploadDataEntity uploadData) + private Optional healFilesDataStructure( + String vspId, Version version, OrchestrationTemplateCandidateData candidateData) throws Exception { - - mdcDataDebugMessage.debugEntryMessage(null); Optional healingResult; - byte[] byteContentData = uploadData.getContentData().array(); + byte[] byteContentData = candidateData.getContentData().array(); FileContentHandler fileContentHandler; - try{ - fileContentHandler = CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, byteContentData); - Map> errors = new HashMap<>(); - OrchestrationTemplateCandidateData candidateDataEntity = - new CandidateEntityBuilder(candidateService) - .buildCandidateEntityFromZip(new VspDetails(vspId, version), byteContentData, - fileContentHandler, errors, user); - - healingResult = getFileDataStructureFromJson(candidateDataEntity.getFilesDataStructure()); - }catch (Exception e){ + try { + fileContentHandler = + CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, byteContentData); + + String filesDataStructure = + new CandidateEntityBuilder(CandidateServiceFactory.getInstance().createInterface()) + .buildCandidateEntityFromZip(new VspDetails(vspId, version), byteContentData, + fileContentHandler, new HashMap<>()).getFilesDataStructure(); + + healingResult = + Optional.of(JsonUtil.json2Object(filesDataStructure, FilesDataStructure.class)); + } catch (Exception e) { log.debug("", e); - return Optional.empty(); + healingResult = Optional.empty(); } mdcDataDebugMessage.debugExitMessage(null); return healingResult; } - - private Optional getFileDataStructureFromJson(String fileDataStructureJson) { - return Optional.of(JsonUtil.json2Object(fileDataStructureJson, FilesDataStructure.class)); - } } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealer.java index c2d7c2c5e4..7991c5904e 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealer.java @@ -5,7 +5,6 @@ import org.openecomp.core.model.dao.ServiceModelDao; import org.openecomp.core.model.dao.ServiceModelDaoFactory; import org.openecomp.core.model.types.ServiceElement; import org.openecomp.sdc.common.togglz.ToggleableFeature; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; @@ -46,10 +45,7 @@ public class ForwarderCapabilityHealer implements Healer { } @Override - public Object heal(Map healingParams) throws Exception { - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - + public Object heal(String vspId, Version version) throws Exception { if(!ToggleableFeature.FORWARDER_CAPABILITY.isActive()) { return Optional.empty(); } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/HeatToToscaTranslationHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/HeatToToscaTranslationHealer.java index 32cd8cbae3..ddae09fa01 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/HeatToToscaTranslationHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/HeatToToscaTranslationHealer.java @@ -3,14 +3,11 @@ package org.openecomp.sdc.healing.healers; import org.openecomp.core.model.dao.ServiceModelDao; import org.openecomp.core.model.dao.ServiceModelDaoFactory; -import org.openecomp.core.model.dao.ServiceTemplateDaoFactory; -import org.openecomp.core.model.dao.ServiceTemplateDaoInter; import org.openecomp.core.model.types.ServiceElement; import org.openecomp.core.translator.datatypes.TranslatorOutput; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.sdc.common.utils.CommonUtil; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; @@ -19,37 +16,32 @@ import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Map; import java.util.Objects; import java.util.Optional; -public class HeatToToscaTranslationHealer implements Healer { +public class HeatToToscaTranslationHealer implements Healer { private static final OrchestrationTemplateDao orchestrationTemplateDao = OrchestrationTemplateDaoFactory.getInstance().createInterface(); private static final ServiceModelDao serviceModelDao = ServiceModelDaoFactory.getInstance().createInterface(); - public static final ServiceTemplateDaoInter - templateDao = ServiceTemplateDaoFactory.getInstance().createInterface(); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); - public HeatToToscaTranslationHealer(){ + public HeatToToscaTranslationHealer() { } @Override - public Object heal(Map healingParams) throws Exception { - mdcDataDebugMessage.debugEntryMessage(null, null); - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - String user = (String) healingParams.get(SdcCommon.USER); - UploadDataEntity uploadData = - orchestrationTemplateDao.getOrchestrationTemplate(vspId, version); + public Object heal(String vspId, Version version) throws Exception { + mdcDataDebugMessage.debugEntryMessage(null);; + + OrchestrationTemplateEntity uploadData = + orchestrationTemplateDao.get(vspId, version); if (Objects.isNull(uploadData) || Objects.isNull(uploadData.getContentData())) { return Optional.empty(); @@ -58,8 +50,9 @@ public class HeatToToscaTranslationHealer implements Healer { FileContentHandler fileContentHandler; TranslatorOutput translatorOutput; try { - fileContentHandler = CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, uploadData - .getContentData().array()); + fileContentHandler = + CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, uploadData + .getContentData().array()); translatorOutput = HeatToToscaUtil.loadAndTranslateTemplateData(fileContentHandler); } catch (Exception e) { diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NicDataHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NicDataHealer.java index 123a943785..b2ef965286 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NicDataHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NicDataHealer.java @@ -1,20 +1,16 @@ package org.openecomp.sdc.healing.healers; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.NetworkType; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Nic; import org.openecomp.sdc.versioning.dao.types.Version; import java.util.Collection; -import java.util.Map; public class NicDataHealer implements Healer { /*private static final VendorSoftwareProductDao vendorSoftwareProductDao = @@ -28,11 +24,9 @@ public class NicDataHealer implements Healer { } @Override - public Object heal(Map healingParams) throws Exception { + public Object heal(String vspId, Version version) throws Exception { mdcDataDebugMessage.debugEntryMessage(null, null); - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - String user = (String) healingParams.get(SdcCommon.USER); + Collection nics = nicDao.listByVsp(vspId, version); for (NicEntity nicEntity : nics) { Nic nic = nicEntity.getNicCompositionData(); 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 new file mode 100644 index 0000000000..acc20c97e4 --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/OwnerHealer.java @@ -0,0 +1,47 @@ +package org.openecomp.sdc.healing.healers; + +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.healing.interfaces.Healer; +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDao; +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDaoFactory; +import org.openecomp.sdc.itempermissions.impl.types.PermissionTypes; +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.versioning.dao.types.Version; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; + +/** + * Created by ayalaben on 8/28/2017 + */ +public class OwnerHealer implements Healer { + private static final String HEALING_USER_SUFFIX = "_healer"; + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + private static final ItemPermissionsDao permissionsDao = + ItemPermissionsDaoFactory.getInstance().createInterface(); + + public Object heal(String itemId, Version version) { + mdcDataDebugMessage.debugEntryMessage(null); + + 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<>()); + + return currentUserId; + } + return itemPermissions.stream().filter(this::isOwnerPermission).findFirst().get().getUserId(); + } + + 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/SubEntitiesQuestionnaireHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/SubEntitiesQuestionnaireHealer.java index 9355eb076f..a1dd80c307 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/SubEntitiesQuestionnaireHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/SubEntitiesQuestionnaireHealer.java @@ -21,7 +21,6 @@ package org.openecomp.sdc.healing.healers; import org.openecomp.core.utilities.json.JsonSchemaDataGenerator; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; @@ -30,8 +29,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.CompositionEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; @@ -42,15 +39,12 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTempl import org.openecomp.sdc.versioning.dao.types.Version; import java.util.Collection; -import java.util.Map; import java.util.Objects; public class SubEntitiesQuestionnaireHealer implements Healer { private static Version version00 = new Version(0, 0); private MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private static final VendorSoftwareProductDao vendorSoftwareProductDao = - VendorSoftwareProductDaoFactory.getInstance().createInterface(); private static ComponentDao componentDao = ComponentDaoFactory.getInstance().createInterface(); private static NicDao nicDao = NicDaoFactory.getInstance().createInterface(); private static NetworkDao networkDao = NetworkDaoFactory.getInstance().createInterface(); @@ -59,22 +53,17 @@ public class SubEntitiesQuestionnaireHealer implements Healer { private static String emptyJson = "{}"; @Override - public Object heal(Map healingParams) throws Exception { + public Object heal(String vspId, Version version) throws Exception { mdcDataDebugMessage.debugEntryMessage(null); - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = version00.equals(healingParams.get(SdcCommon.VERSION)) ? new Version - (0, 1) - : (Version) healingParams.get(SdcCommon.VERSION); - Collection componentEntities = componentDao.listCompositionAndQuestionnaire(vspId, version); networkDao.list(new NetworkEntity(vspId, version, null)); - Collection nicEntities = vendorSoftwareProductDao.listNicsByVsp(vspId, version); + Collection nicEntities = nicDao.listByVsp(vspId, version); healCompositionEntityQuestionnaire(componentEntities, version, CompositionEntityType.component); healCompositionEntityQuestionnaire(nicEntities, version, CompositionEntityType.nic); diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ValidationStructureHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ValidationStructureHealer.java index 4bf7e18091..d172432284 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ValidationStructureHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ValidationStructureHealer.java @@ -2,7 +2,6 @@ package org.openecomp.sdc.healing.healers; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.heat.datatypes.manifest.FileData; @@ -13,16 +12,11 @@ import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadData; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.versioning.dao.types.Version; import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -32,78 +26,55 @@ import java.util.Set; */ public class ValidationStructureHealer implements Healer { - private static final VendorSoftwareProductInfoDao vspInfoDao = - VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(); + private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class); private static final OrchestrationTemplateDao orchestrationTemplateDao = OrchestrationTemplateDaoFactory.getInstance().createInterface(); - private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class); @Override - public Object heal(Map healingParams) throws Exception { + public Object heal(String vspId, Version version) throws Exception { - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); + OrchestrationTemplateEntity orchestrationTemplate = + orchestrationTemplateDao.get(vspId, version); - VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); - UploadDataEntity orchestrationTemplate = - orchestrationTemplateDao.getOrchestrationTemplate(vspId, version); - - if(Objects.isNull(orchestrationTemplate.getValidationData()) - || !JsonUtil.isValidJson(orchestrationTemplate.getValidationData())){ + if (Objects.isNull(orchestrationTemplate.getValidationData()) + || !JsonUtil.isValidJson(orchestrationTemplate.getValidationData())) { return Optional.empty(); } OldValidationStructureTree oldValidationStructureTree; - try{ - oldValidationStructureTree = - JsonUtil.json2Object(orchestrationTemplate.getValidationData(), OldValidationStructureTree - .class); - } catch (Exception e){ - logger.debug("",e); + try { + oldValidationStructureTree = JsonUtil + .json2Object(orchestrationTemplate.getValidationData(), OldValidationStructureTree.class); + } catch (Exception e) { + logger.debug("", e); return Optional.empty(); } Optional newHeatStructureTreeFromOldStructureTree = - createNewHeatStructureTreeFromOldStructureTree(oldValidationStructureTree.getImportStructure()); + createNewHeatStructureTreeFromOldStructureTree( + oldValidationStructureTree.getImportStructure()); - if(newHeatStructureTreeFromOldStructureTree.isPresent()){ - ValidationStructureList validationData = new ValidationStructureList - (newHeatStructureTreeFromOldStructureTree.get()); - vspDetails.setValidationDataStructure(validationData); + newHeatStructureTreeFromOldStructureTree.ifPresent(newStructure -> + updateValuesInDb(vspId, version, orchestrationTemplate, + new ValidationStructureList(newStructure))); - updateValuesInDb(vspId, vspDetails, orchestrationTemplate, validationData); - } return newHeatStructureTreeFromOldStructureTree; } - private void updateValuesInDb(String vspId, VspDetails vspDetails, - UploadDataEntity orchestrationTemplate, + private void updateValuesInDb(String vspId, Version version, + OrchestrationTemplateEntity orchestrationTemplate, ValidationStructureList validationData) { - vspInfoDao.update(vspDetails); - UploadData uploadData = getUpdatedUploadData(orchestrationTemplate, validationData); - orchestrationTemplateDao.updateOrchestrationTemplateData(vspId, uploadData); + orchestrationTemplate.setValidationDataStructure(validationData); + orchestrationTemplateDao.update(vspId, version, orchestrationTemplate); } - private UploadData getUpdatedUploadData(UploadDataEntity orchestrationTemplate, - ValidationStructureList validationData) { - UploadData uploadData = new UploadData(); - uploadData.setValidationDataStructure(validationData); - uploadData.setValidationData(JsonUtil.object2Json(validationData)); - uploadData.setContentData(orchestrationTemplate.getContentData()); - uploadData.setId(orchestrationTemplate.getId()); - uploadData.setPackageName(orchestrationTemplate.getPackageName()); - uploadData.setPackageVersion(orchestrationTemplate.getPackageVersion()); - return uploadData; - } - - - private Optional createNewHeatStructureTreeFromOldStructureTree(OldHeatStructureTree - oldHeatStructureTree){ + private Optional createNewHeatStructureTreeFromOldStructureTree( + OldHeatStructureTree oldHeatStructureTree) { HeatStructureTree heatStructureTree = new HeatStructureTree(); - if(Objects.isNull(oldHeatStructureTree)){ + if (Objects.isNull(oldHeatStructureTree)) { return Optional.empty(); } @@ -112,11 +83,14 @@ public class ValidationStructureHealer implements Healer { Set heat = oldHeatStructureTree.getHeat() == null ? new HashSet<>() : oldHeatStructureTree.getHeat(); Set volume = - oldHeatStructureTree.getVolume() == null ? new HashSet<>() : oldHeatStructureTree.getVolume(); + oldHeatStructureTree.getVolume() == null ? new HashSet<>() + : oldHeatStructureTree.getVolume(); Set nested = - oldHeatStructureTree.getNested() == null ? new HashSet<>() : oldHeatStructureTree.getNested(); + oldHeatStructureTree.getNested() == null ? new HashSet<>() + : oldHeatStructureTree.getNested(); Set network = - oldHeatStructureTree.getNetwork() == null ? new HashSet<>() : oldHeatStructureTree.getNetwork(); + oldHeatStructureTree.getNetwork() == null ? new HashSet<>() + : oldHeatStructureTree.getNetwork(); heatStructureTree.setHeat(createHeatStructureTreeSetFromOld(heat)); @@ -124,57 +98,47 @@ public class ValidationStructureHealer implements Healer { heatStructureTree.setNested(createHeatStructureTreeSetFromOld(nested)); heatStructureTree.setNetwork(createHeatStructureTreeSetFromOld(network)); - return Optional.of(heatStructureTree); - } - private void mapOldHeatStructureTreeValues( - OldHeatStructureTree oldHeatStructureTree, - HeatStructureTree heatStructureTree) { + private void mapOldHeatStructureTreeValues(OldHeatStructureTree oldHeatStructureTree, + HeatStructureTree heatStructureTree) { heatStructureTree.setFileName(oldHeatStructureTree.getFileName()); heatStructureTree.setBase(oldHeatStructureTree.getBase()); heatStructureTree.setType(oldHeatStructureTree.getType()); heatStructureTree.setArtifacts(oldHeatStructureTree.getArtifacts()); heatStructureTree.setErrors(oldHeatStructureTree.getErrors()); - if(Objects.nonNull(oldHeatStructureTree.getEnv())) { + if (Objects.nonNull(oldHeatStructureTree.getEnv())) { heatStructureTree.setEnv(new HeatStructureTree(oldHeatStructureTree.getEnv(), false)); } } private Set createHeatStructureTreeSetFromOld(Set - oldHeatStructureTreeSet){ - if(CollectionUtils.isEmpty(oldHeatStructureTreeSet)){ + oldHeatStructureTreeSet) { + if (CollectionUtils.isEmpty(oldHeatStructureTreeSet)) { return null; } Set newHeatStructureSet = new HashSet<>(); - for(OldHeatStructureTree old : oldHeatStructureTreeSet){ + for (OldHeatStructureTree old : oldHeatStructureTreeSet) { Optional newHeatStructureTree = createNewHeatStructureTreeFromOldStructureTree(old); - if(newHeatStructureTree.isPresent()){ - newHeatStructureSet.add(newHeatStructureTree.get()); - } + newHeatStructureTree.ifPresent(newHeatStructureSet::add); } return newHeatStructureSet; } - private class OldValidationStructureTree{ + private class OldValidationStructureTree { private OldHeatStructureTree importStructure; - public OldHeatStructureTree getImportStructure() { + OldHeatStructureTree getImportStructure() { return importStructure; } - - public void setImportStructure( - OldHeatStructureTree importStructure) { - this.importStructure = importStructure; - } } - private class OldHeatStructureTree{ + private class OldHeatStructureTree { private String fileName; private FileData.Type type; private Boolean isBase; @@ -190,93 +154,93 @@ public class ValidationStructureHealer implements Healer { public OldHeatStructureTree() { } - public String getFileName() { - return fileName; - } + public String getFileName() { + return fileName; + } - public void setFileName(String fileName) { - this.fileName = fileName; - } + public void setFileName(String fileName) { + this.fileName = fileName; + } - public FileData.Type getType() { - return type; - } + public FileData.Type getType() { + return type; + } - public void setType(FileData.Type type) { - this.type = type; - } + public void setType(FileData.Type type) { + this.type = type; + } - public Boolean getBase() { - return isBase; - } + public Boolean getBase() { + return isBase; + } - public void setBase(Boolean base) { - isBase = base; - } + public void setBase(Boolean base) { + isBase = base; + } - public String getEnv() { - return env; - } + public String getEnv() { + return env; + } - public void setEnv(String env) { - this.env = env; - } + public void setEnv(String env) { + this.env = env; + } - public List getErrors() { - return errors; - } + public List getErrors() { + return errors; + } - public void setErrors(List errors) { - this.errors = errors; - } + public void setErrors(List errors) { + this.errors = errors; + } - public Set getHeat() { - return heat; - } + public Set getHeat() { + return heat; + } - public void setHeat(Set heat) { - this.heat = heat; - } + public void setHeat(Set heat) { + this.heat = heat; + } - public Set getVolume() { - return volume; - } + public Set getVolume() { + return volume; + } - public void setVolume(Set volume) { - this.volume = volume; - } + public void setVolume(Set volume) { + this.volume = volume; + } - public Set getNetwork() { - return network; - } + public Set getNetwork() { + return network; + } - public void setNetwork( - Set network) { - this.network = network; - } + public void setNetwork( + Set network) { + this.network = network; + } - public Set getNested() { - return nested; - } + public Set getNested() { + return nested; + } - public void setNested(Set nested) { - this.nested = nested; - } + public void setNested(Set nested) { + this.nested = nested; + } - public Set getOther() { - return other; - } + public Set getOther() { + return other; + } - public void setOther(Set other) { - this.other = other; - } + public void setOther(Set other) { + this.other = other; + } - public Set getArtifacts() { - return artifacts; - } + public Set getArtifacts() { + return artifacts; + } - public void setArtifacts(Set artifacts) { - this.artifacts = artifacts; + public void setArtifacts(Set artifacts) { + this.artifacts = artifacts; + } } } -} diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VlmVersionHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VlmVersionHealer.java index 085923b8a0..a57ac74350 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VlmVersionHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VlmVersionHealer.java @@ -1,26 +1,21 @@ package org.openecomp.sdc.healing.healers; -import org.apache.commons.collections4.CollectionUtils; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDao; import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDaoFactory; import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; -import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; -import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; -import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacadeFactory; -import org.openecomp.sdc.vendorlicense.types.VersionedVendorLicenseModel; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; +import org.openecomp.sdc.versioning.VersioningManager; +import org.openecomp.sdc.versioning.VersioningManagerFactory; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.types.VersionInfo; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.Collection; import java.util.Objects; import java.util.Optional; @@ -28,8 +23,8 @@ import java.util.Optional; * Created by TALIO on 7/3/2017. */ public class VlmVersionHealer implements Healer { - private static final VendorLicenseFacade vendorLicenseFacade = - VendorLicenseFacadeFactory.getInstance().createInterface(); + private VersioningManager versioningManager = + VersioningManagerFactory.getInstance().createInterface(); private static final VendorSoftwareProductInfoDao vspInfoDao = VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(); private static final LicenseAgreementDao licenseAgreementDao = @@ -38,51 +33,35 @@ public class VlmVersionHealer implements Healer { LoggerFactory.getLogger(VlmVersionHealer.class); @Override - public Object heal(Map healingParams) throws Exception { - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - String user = (String) healingParams.get(SdcCommon.USER); - + public Object heal(String vspId, Version version) throws Exception { VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); - VersionedVendorLicenseModel vendorLicenseModel; - - if(!Objects.isNull(vspDetails.getVlmVersion())) { + + if (!Objects.isNull(vspDetails.getVlmVersion())) { return Optional.empty(); } - - try{ - vendorLicenseModel = - vendorLicenseFacade.getVendorLicenseModel(vspDetails.getVendorId(), null, user); - } catch (Exception e){ - logger.debug("" + e); + // get the certified vlm version with the highest number in its name + Optional certifiedVlmVersion = + versioningManager.list(vspDetails.getVendorId()).stream() + .filter(ver -> VersionStatus.Certified == ver.getStatus()) + .max((o1, o2) -> ((Double) Double.parseDouble(o1.getName())) + .compareTo(Double.parseDouble(o2.getName()))); + if (!certifiedVlmVersion.isPresent()) { logger.debug("No Vlm was found for Vsp " + vspDetails.getName()); return Optional.empty(); } + vspDetails.setVlmVersion(certifiedVlmVersion.get()); - VendorLicenseModelEntity vlm = vendorLicenseModel.getVendorLicenseModel(); - String vlmId = vlm.getId(); - Version vlmVersion = getLatestFinalVlmVersion(vendorLicenseModel.getVersionInfo()); - - List laList = - new ArrayList<>( - licenseAgreementDao.list(new LicenseAgreementEntity(vlmId, vlmVersion, null))); - - - vspDetails.setVlmVersion(vlmVersion); - - if(CollectionUtils.isNotEmpty(laList)) { - vspDetails.setLicenseAgreement(laList.get(0).getId()); - vspDetails.setFeatureGroups(new ArrayList<>(laList.get(0).getFeatureGroupIds())); + Collection licenseAgreements = licenseAgreementDao.list( + new LicenseAgreementEntity(vspDetails.getVendorId(), certifiedVlmVersion.get(), null)); + if (!licenseAgreements.isEmpty()) { + LicenseAgreementEntity licenseAgreement = licenseAgreements.iterator().next(); + vspDetails.setLicenseAgreement(licenseAgreement.getId()); + vspDetails.setFeatureGroups(new ArrayList<>(licenseAgreement.getFeatureGroupIds())); } vspInfoDao.update(vspDetails); - return vspDetails; - } - - private Version getLatestFinalVlmVersion(VersionInfo versionInfo){ - return versionInfo.getActiveVersion().isFinal() ? versionInfo.getActiveVersion() - : versionInfo.getLatestFinalVersion(); + return vspDetails; } } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealer.java index ddcd31453c..d5c082bdae 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealer.java @@ -2,55 +2,91 @@ package org.openecomp.sdc.healing.healers; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; +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.VspDetails; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Map; import java.util.Objects; public class VspOnboardingMethodHealer implements Healer { - private static VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao; + + private static final String DEFAULT_FILE_NAME = "Upload File"; private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + private VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao; + private OrchestrationTemplateDao orchestrationTemplateDao; + private OrchestrationTemplateCandidateDao candidateDao; public VspOnboardingMethodHealer(){ - this(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface()); + this(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), + OrchestrationTemplateDaoFactory.getInstance().createInterface(), + OrchestrationTemplateCandidateDaoFactory.getInstance().createInterface()); } - public VspOnboardingMethodHealer( VendorSoftwareProductInfoDao inVendorSoftwareProductInfoDao){ - vendorSoftwareProductInfoDao = inVendorSoftwareProductInfoDao; + public VspOnboardingMethodHealer(VendorSoftwareProductInfoDao vspInfoDao, + OrchestrationTemplateDao orchestrationTemplateDao, + OrchestrationTemplateCandidateDao candidateDao) { + this.vendorSoftwareProductInfoDao = vspInfoDao; + this.orchestrationTemplateDao = orchestrationTemplateDao; + this.candidateDao = candidateDao; } - @Override - public Object heal(Map healingParams) throws Exception { - mdcDataDebugMessage.debugEntryMessage(null, null); - - String onboardingMethod=null; - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - VspDetails vendorSoftwareProductInfo = - vendorSoftwareProductInfoDao.get(new VspDetails(vspId, version)); - String onboardingValue = vendorSoftwareProductInfo.getOnboardingMethod(); - - if(Objects.isNull(onboardingValue)) { - onboardingMethod="NetworkPackage"; - - updateVSPInfo(OnboardingTypesEnum.ZIP.toString(), onboardingMethod, vendorSoftwareProductInfo); - } else if (onboardingValue.equals("HEAT")){ - onboardingMethod="NetworkPackage"; - updateVSPInfo(OnboardingTypesEnum.ZIP.toString(),onboardingMethod, vendorSoftwareProductInfo); + public Object heal(String vspId, Version version) throws Exception { + mdcDataDebugMessage.debugEntryMessage(null); + + VspDetails vsp = vendorSoftwareProductInfoDao.get(new VspDetails(vspId, version)); + healOnboardingMethod(vsp); + + if (!OnboardingMethod.Manual.name().equals(vsp.getOnboardingMethod())) { + healOrchestrationTemplateFileName(vspId, version); + healOrchestrationTemplateCandidateFileName(vspId, version); + } + + mdcDataDebugMessage.debugExitMessage(null); + return null; + } + + private void healOnboardingMethod(VspDetails vsp) { + if (Objects.isNull(vsp.getOnboardingMethod()) || "HEAT".equals(vsp.getOnboardingMethod())) { + vsp.setOnboardingMethod(OnboardingMethod.NetworkPackage.name()); + vendorSoftwareProductInfoDao.update(vsp); } - return onboardingMethod; } - private void updateVSPInfo(String onboardingOrigin, String onboardingMethod, VspDetails vendorSoftwareProductInfo) { - vendorSoftwareProductInfo.setOnboardingMethod(onboardingMethod); - vendorSoftwareProductInfo.setOnboardingOrigin(onboardingOrigin); - vendorSoftwareProductInfoDao.update(vendorSoftwareProductInfo); + private void healOrchestrationTemplateFileName(String vspId, Version version) { + OrchestrationTemplateEntity orchestrationTemplate = + orchestrationTemplateDao.get(vspId, version); + + if (orchestrationTemplate == null || orchestrationTemplate.getContentData() == null || + orchestrationTemplate.getFileSuffix() != null) { + return; + } + orchestrationTemplate.setFileSuffix(OnboardingTypesEnum.ZIP.toString()); + orchestrationTemplate.setFileName(DEFAULT_FILE_NAME); + + orchestrationTemplateDao.update(vspId, version, orchestrationTemplate); + } + + private void healOrchestrationTemplateCandidateFileName(String vspId, Version version) { + OrchestrationTemplateCandidateData candidate = candidateDao.get(vspId, version); + + if (candidate == null || candidate.getContentData() == null || + candidate.getFileSuffix() != null) { + return; + } + candidate.setFileSuffix(OnboardingTypesEnum.ZIP.toString()); + candidate.setFileName(DEFAULT_FILE_NAME); + + candidateDao.update(vspId, version, candidate); } } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspQuestionnaireHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspQuestionnaireHealer.java index 0952a4c88f..b45ce30a3e 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspQuestionnaireHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspQuestionnaireHealer.java @@ -21,7 +21,6 @@ package org.openecomp.sdc.healing.healers; import org.openecomp.core.utilities.json.JsonSchemaDataGenerator; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; @@ -35,7 +34,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTempl import org.openecomp.sdc.versioning.dao.types.Version; import java.io.IOException; -import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -50,15 +48,12 @@ public class VspQuestionnaireHealer implements Healer { } @Override - public Object heal(Map healingParams) throws IOException { + public Object heal(String vspId, Version version) throws IOException { mdcDataDebugMessage.debugEntryMessage(null, null); Optional questionnaireData = null; - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - VspQuestionnaireEntity vspQuestionnaireEntity = vspInfoDao.getQuestionnaire(vspId, version); diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealerTest.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealerTest.java index 69f4287cd1..688d1d4236 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealerTest.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealerTest.java @@ -8,7 +8,6 @@ import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDao; @@ -20,10 +19,7 @@ import org.openecomp.sdc.versioning.dao.types.Version; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.HashMap; -import java.util.Map; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.doNothing; @@ -47,7 +43,6 @@ public class ComponentQuestionnaireHealerTest { private static final String DUMMY_COMPONENT_ID = "2495ef442f964cbfb00d82bd54292f89"; private static final String DUMMY_COMPUTE_ID = "3495ef442f964cbfb00d82bd54292f89"; private static final String DUMMY_IMAGE_ID = "4495ef442f964cbfb00d82bd54292f89"; - private static Map healingParams = new HashMap<>(); private static final String componentQuestionnaireData = "{\"compute\": {" + "\"guestOS\": {\"bitSize\": 64},\"vmSizing\": {\"IOOperationsPerSec\": \"0\"}," + "\"numOfVMs\": {\"CpuOverSubscriptionRatio\": \"1:1\",\"MemoryRAM\": \"2 GB\"}}," + @@ -131,16 +126,13 @@ public class ComponentQuestionnaireHealerTest { @Before public void init() throws Exception { MockitoAnnotations.initMocks(ComponentQuestionnaireHealerTest.this); - - healingParams.put(SdcCommon.VSP_ID, DUMMY_VSP_ID); - healingParams.put(SdcCommon.VERSION, VERSION); } @Test public void healQuestionnaireNullTest() throws Exception { prepareHealingData(); componentEntity.setQuestionnaireData(null); - Object returnObject = componentQuestionnaireHealer.heal(healingParams); + Object returnObject = componentQuestionnaireHealer.heal(DUMMY_VSP_ID, VERSION); Assert.assertTrue(returnObject instanceof Collection); Collection componentEntities = (Collection) returnObject; componentEntities.forEach(componentEntity -> { @@ -152,7 +144,7 @@ public class ComponentQuestionnaireHealerTest { public void healAllCasesTest() throws Exception { prepareHealingData(); - Object returnObject = componentQuestionnaireHealer.heal(healingParams); + Object returnObject = componentQuestionnaireHealer.heal(DUMMY_VSP_ID, VERSION); Assert.assertTrue(returnObject instanceof Collection); Collection componentEntities = (Collection) returnObject; componentEntities.forEach(componentEntity -> { @@ -177,7 +169,7 @@ public class ComponentQuestionnaireHealerTest { public void healDiskAttrMissingTest() throws Exception { prepareHealingData(); componentEntity.setQuestionnaireData(componentQuestionnaireMissingDiskAttrData); - Object returnObject = componentQuestionnaireHealer.heal(healingParams); + Object returnObject = componentQuestionnaireHealer.heal(DUMMY_VSP_ID, VERSION); Assert.assertTrue(returnObject instanceof Collection); Collection componentEntities = (Collection) returnObject; componentEntities.forEach(componentEntity -> { @@ -238,7 +230,7 @@ public class ComponentQuestionnaireHealerTest { .getDeclaredMethod(methodName, JsonObject.class, JsonObject.class); method.setAccessible(true); - method.invoke(componentQuestionnaireHealer,jsonObject.getAsJsonObject(COMPUTE), null); + method.invoke(componentQuestionnaireHealer, jsonObject.getAsJsonObject(COMPUTE), null); } private void prepareHealingData() { diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealerTest.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealerTest.java index 406d039178..a07ace683f 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealerTest.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealerTest.java @@ -13,7 +13,6 @@ import org.mockito.MockitoAnnotations; import org.openecomp.core.model.dao.ServiceModelDao; import org.openecomp.core.model.types.ServiceElement; import org.openecomp.sdc.common.togglz.ToggleableFeature; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.healers.util.TestUtil; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; @@ -32,13 +31,14 @@ import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.eq; public class ForwarderCapabilityHealerTest { + private static final String vspId = "1"; + private static final Version version = new Version(1, 1); private static final String IN_SUFFIX = "/in"; private static final String OUT_SUFFIX = "/out"; private static final String BASE_DIRECTORY = "/mock/healers/forwarder"; private static final String ENTRY_DEFINITION_SERVICE_TEMPLATE = "MainServiceTemplate.yaml"; private static TestFeatureManager manager; - private Map params = new HashMap<>(); @Mock private ServiceModelDao serviceModelDao; @@ -65,8 +65,6 @@ public class ForwarderCapabilityHealerTest { @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(ForwarderCapabilityHealerTest.this); - params.put(SdcCommon.VSP_ID,"1"); - params.put(SdcCommon.VERSION, new Version(1,1)); } @@ -127,7 +125,7 @@ public class ForwarderCapabilityHealerTest { private void validateServiceModelAfterHealing(String testDirectory) throws Exception { Optional serviceModelObject = - (Optional) forwarderCapabilityHealer.heal(params); + (Optional) forwarderCapabilityHealer.heal(vspId, version); Assert.assertTrue(serviceModelObject.isPresent()); TestUtil diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealerTest.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealerTest.java index b732cb03b6..5584a5fe77 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealerTest.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealerTest.java @@ -2,69 +2,77 @@ package org.openecomp.sdc.healing.healers; import org.junit.Before; import org.junit.Test; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.common.utils.SdcCommon; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.HashMap; -import java.util.Map; - import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; -public class VspOnboardingMethodHealerTest{ +public class VspOnboardingMethodHealerTest { + private static final String vspId = "1"; + private static final Version version = new Version(1, 1); + + @Mock + private VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao; + @Mock + private OrchestrationTemplateDao orchestrationTemplateDao; + @Mock + private OrchestrationTemplateCandidateDao candidateDao; + @InjectMocks + private VspOnboardingMethodHealer vspOnboardingMethodHealer; + + private OrchestrationTemplateEntity orchestrationTemplateEntity = new OrchestrationTemplateEntity(); + private OrchestrationTemplateCandidateData candidateData = new OrchestrationTemplateCandidateData(); + private static final String NETWORK_PACKAGE = "NetworkPackage"; + private static final String HEAT = "HEAT"; + private static final String MANUAL = "Manual"; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(VspOnboardingMethodHealerTest.this); + } + + @Test + public void checkHealingWithNullOnboarding() throws Exception { + VspDetails vspDetails = initAndExecuteHealer(null); + assertEquals(vspDetails.getOnboardingMethod(), NETWORK_PACKAGE); + } - @Mock - private VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao; + @Test + public void checkHealingWithHEATOnboarding() throws Exception { + VspDetails vspDetails = initAndExecuteHealer(HEAT); + assertEquals(vspDetails.getOnboardingMethod(), NETWORK_PACKAGE); + } - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(VspOnboardingMethodHealerTest.this); - } + @Test + public void checkHealingWithManualOnboarding() throws Exception { + VspDetails vspDetails = initAndExecuteHealer(MANUAL); + assertEquals(vspDetails.getOnboardingMethod(), MANUAL); + } - @Test - public void checkHealingWithNullOnboarding() throws Exception{ - VspOnboardingMethodHealer vspOnboardingMethodHealer = new VspOnboardingMethodHealer(vendorSoftwareProductInfoDao); - Map params = new HashMap<>(); - params.put(SdcCommon.VSP_ID,"1"); - params.put(SdcCommon.VERSION, new Version(1,1)); - VspDetails vspDetails = new VspDetails(); - vspDetails.setOnboardingMethod(null); - Mockito.when(vendorSoftwareProductInfoDao.get(any())).thenReturn(vspDetails); - vspOnboardingMethodHealer.heal(params); - assertEquals(vspDetails.getOnboardingMethod(),"NetworkPackage"); - assertEquals(vspDetails.getOnboardingOrigin(),"zip"); - } + private VspDetails initAndExecuteHealer(String onboardingMethod) throws Exception { + VspDetails vspDetails = new VspDetails(); + vspDetails.setOnboardingMethod(onboardingMethod); - @Test - public void checkHealingWithHEATOnboarding() throws Exception{ - VspOnboardingMethodHealer vspOnboardingMethodHealer = new VspOnboardingMethodHealer(vendorSoftwareProductInfoDao); - Map params = new HashMap<>(); - params.put(SdcCommon.VSP_ID,"1"); - params.put(SdcCommon.VERSION, new Version(1,1)); - VspDetails vspDetails = new VspDetails(); - vspDetails.setOnboardingMethod("HEAT"); - Mockito.when(vendorSoftwareProductInfoDao.get(any())).thenReturn(vspDetails); - vspOnboardingMethodHealer.heal(params); - assertEquals(vspDetails.getOnboardingMethod(),"NetworkPackage"); - assertEquals(vspDetails.getOnboardingOrigin(),"zip"); - } + setMockActions(vspDetails); + vspOnboardingMethodHealer.heal(vspId, version); + return vspDetails; + } - @Test - public void checkHealingWithManualOnboarding() throws Exception{ - VspOnboardingMethodHealer vspOnboardingMethodHealer = new VspOnboardingMethodHealer(vendorSoftwareProductInfoDao); - Map params = new HashMap<>(); - params.put(SdcCommon.VSP_ID,"1"); - params.put(SdcCommon.VERSION, new Version(1,1)); - VspDetails vspDetails = new VspDetails(); - vspDetails.setOnboardingMethod("Manual"); - Mockito.when(vendorSoftwareProductInfoDao.get(any())).thenReturn(vspDetails); - vspOnboardingMethodHealer.heal(params); - assertEquals(vspDetails.getOnboardingMethod(),"Manual"); - assertEquals(vspDetails.getOnboardingOrigin(),null); - } + private void setMockActions(VspDetails vspDetails) { + Mockito.doReturn(vspDetails).when(vendorSoftwareProductInfoDao).get(any()); + Mockito.doReturn(orchestrationTemplateEntity).when(orchestrationTemplateDao).get(any(), any()); + Mockito.doNothing().when(orchestrationTemplateDao).update(any(), any(), any()); + Mockito.doReturn(candidateData).when(candidateDao).get(any(), any()); + Mockito.doNothing().when(candidateDao).update(any(), any(), any()); + } } \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/data/TestDescriptionHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/data/TestDescriptionHealer.java new file mode 100644 index 0000000000..aac1a502ef --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/data/TestDescriptionHealer.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.healing.healers.testHealers.data; + +import org.openecomp.sdc.healing.interfaces.Healer; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; +import org.openecomp.sdc.versioning.dao.types.Version; + +public class TestDescriptionHealer implements Healer { + + @Override + public Object heal(String vspId, Version version) throws Exception { + VspDetails vspDetails = new VspDetails(vspId, version); + vspDetails.setDescription("This is a data healer"); + + return vspDetails; + } +} diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/structure/TestNewEntityInVspHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/structure/TestNewEntityInVspHealer.java new file mode 100644 index 0000000000..7d71c0319b --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/structure/TestNewEntityInVspHealer.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.healing.healers.testHealers.structure; + +import org.openecomp.sdc.healing.interfaces.Healer; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; +import org.openecomp.sdc.versioning.dao.types.Version; + +public class TestNewEntityInVspHealer implements Healer { + + @Override + public Object heal(String vspId, Version version) throws Exception { + VspDetails vspDetails = new VspDetails(vspId, version); + vspDetails.setDescription("This is a structure healer"); + + return vspDetails; + } +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/pom.xml b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/pom.xml new file mode 100644 index 0000000000..f69f3041a7 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/pom.xml @@ -0,0 +1,32 @@ + + + 4.0.0 + + + + org.openecomp.sdc + openecomp-item-permissions-lib + 1.2.0-SNAPSHOT + .. + + + openecomp-item-permissions-api + + + + + org.openecomp.sdc.core + openecomp-nosqldb-core + ${project.version} + + + + org.openecomp.sdc.core + openecomp-facade-api + ${project.version} + + + + + + \ No newline at end of file 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 new file mode 100644 index 0000000000..b5a119e8ed --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRules.java @@ -0,0 +1,17 @@ +package org.openecomp.sdc.itempermissions; + +import java.util.Set; + +/** + * Created by ayalaben on 6/22/2017. + */ +public interface PermissionsRules { + + 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); + +} 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 new file mode 100644 index 0000000000..c3e0672939 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRulesFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.itempermissions; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +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); + } + +} 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 new file mode 100644 index 0000000000..09c8102ef0 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServices.java @@ -0,0 +1,26 @@ +package org.openecomp.sdc.itempermissions; + +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; + +import java.util.Collection; +import java.util.Set; + +/** + * Created by ayalaben on 6/22/2017 + */ +public interface PermissionsServices { + + Collection listItemPermissions(String itemId); + + void updateItemPermissions(String itemId, String permission, Set addedUsersIds, + Set removedUsersIds); + + boolean isAllowed(String itemId,String userId,String action); + + void execute(String itemId,String userId,String action); + + String getUserItemPermiission(String itemId, String userId); + + + +} 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 new file mode 100644 index 0000000000..97769bcc82 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServicesFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.itempermissions; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +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); + } + +} 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 new file mode 100644 index 0000000000..a0f51f90bb --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDao.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.itempermissions.dao; + +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; + +import java.util.Collection; +import java.util.Set; + +/** + * Created by ayalaben on 6/18/2017. + */ +public interface ItemPermissionsDao { + + Collection listItemPermissions(String itemId); + + void updateItemPermissions(String itemId, String permission, Set addedUsersIds, + Set removedUsersIds); + + void addUserPermission(String itemId, String userId, String permission); + + String getUserItemPermiission(String itemId, String userId); +} 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 new file mode 100644 index 0000000000..95d541e028 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDaoFactory.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.itempermissions.dao; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +/** + * Created by ayalaben on 6/18/2017. + */ +public abstract class ItemPermissionsDaoFactory extends AbstractComponentFactory { + + 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/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 new file mode 100644 index 0000000000..a3fb9a14a8 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessages.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.itempermissions.errors; + +/** + * Created by ayalaben on 6/28/2017 + */ +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"); + + private String errorMessage; + + PermissionsErrorMessages(String errorMessage) { + this.errorMessage = 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 new file mode 100644 index 0000000000..f0c13d9cda --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessagesBuilder.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.itempermissions.errors; + +import org.openecomp.sdc.common.errors.ErrorCategory; +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(); + } + + +} 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 new file mode 100644 index 0000000000..d4235cd6c6 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/notifications/NotificationConstants.java @@ -0,0 +1,14 @@ +package org.openecomp.sdc.itempermissions.notifications; + +/** + * @author avrahamg + * @since July 10, 2017 + */ +public class NotificationConstants { + 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"; + public static final String PERMISSION_GRANTED = "granted"; + public static final String PERMISSION_USER = "userId"; +} 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 new file mode 100644 index 0000000000..22ff43778c --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/type/ItemPermissionsEntity.java @@ -0,0 +1,50 @@ +package org.openecomp.sdc.itempermissions.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; + +/** + * Created by ayalaben on 6/18/2017. + */ + +@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; + + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getPermission() { + return permission; + } + + public void setPermission(String permission) { + this.permission = permission; + } +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/pom.xml b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/pom.xml new file mode 100644 index 0000000000..a420b23f6e --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + + + org.openecomp.sdc + openecomp-item-permissions-lib + 1.2.0-SNAPSHOT + .. + + + openecomp-item-permissions-core + + + + + org.openecomp.sdc.core + openecomp-session-lib + ${project.version} + + + + + org.openecomp.sdc + openecomp-item-permissions-api + ${project.version} + + + + + org.openecomp.sdc.core + openecomp-facade-core + ${project.version} + + + + + org.openecomp.sdc.core + openecomp-nosqldb-core + ${project.version} + + + org.openecomp.sdc + openecomp-sdc-notification-api + ${project.version} + + + org.mockito + mockito-all + RELEASE + + + org.testng + testng + RELEASE + + + + + \ No newline at end of file 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 new file mode 100644 index 0000000000..87c0338c25 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoFactoryImpl.java @@ -0,0 +1,19 @@ +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. + */ +public class ItemPermissionsDaoFactoryImpl extends ItemPermissionsDaoFactory { + + private static ItemPermissionsDao INSTANCE =new ItemPermissionsDaoImpl(); + + @Override + public ItemPermissionsDao 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/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 new file mode 100644 index 0000000000..e1a9d1c874 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoImpl.java @@ -0,0 +1,66 @@ +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 org.openecomp.core.nosqldb.api.NoSqlDb; +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDao; +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; + +import java.util.Collection; +import java.util.Set; + +/** + * Created by ayalaben on 6/20/2017. + */ +public class ItemPermissionsDaoImpl implements ItemPermissionsDao { + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static ItemPermissionsAccessor accessor = + noSqlDb.getMappingManager().createAccessor(ItemPermissionsAccessor.class); + + @Override + public Collection listItemPermissions(String itemId) { + return accessor.getItemPermissions(itemId).all(); + } + + @Override + public void updateItemPermissions(String itemId, String permission, Set addedUsersIds, + Set removedUsersIds) { + addedUsersIds.forEach(userId -> accessor.addPermission(itemId,userId,permission)); + removedUsersIds.forEach(userId -> accessor.deletePermission(itemId,userId)); + } + + @Override + public void addUserPermission(String itemId, String userId, String permission){ + accessor.addPermission(itemId,userId,permission); + } + + @Override + public String getUserItemPermiission(String itemId, String userId) { + + ResultSet result = accessor.getUserItemPermission(itemId,userId); + if (result.getAvailableWithoutFetching() < 1) { + return null; + } + return result.one().getString(0); + } + + + @Accessor + interface ItemPermissionsAccessor { + @Query("select * from dox.item_permissions WHERE item_id = ?") + Result getItemPermissions(String itemId); + + @Query("select permission from dox.item_permissions WHERE item_id = ? AND user_id=?") + ResultSet getUserItemPermission(String itemId,String userId); + + @Query("delete from dox.item_permissions where item_id = ? and user_id = ?") + void deletePermission(String itemId, String userId); + + @Query("insert into dox.item_permissions (item_id,user_id,permission) values (?,?,?)") + void addPermission(String itemId,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/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 new file mode 100644 index 0000000000..ae40ea8d97 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImpl.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.itempermissions.dao.impl; + +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.itempermissions.PermissionsRules; +import org.openecomp.sdc.itempermissions.PermissionsServices; +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDao; +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; + +import java.util.Collection; +import java.util.Set; + + +/** + * Created by ayalaben on 6/22/2017. + */ +public class PermissionsServicesImpl implements PermissionsServices { + + private ItemPermissionsDao permissionsDao; + + private PermissionsRules permissionsRules; + + private static final String CHANGE_PERMISSIONS = "Change_Item_Permissions"; + + public PermissionsServicesImpl(PermissionsRules permissionsRules, + ItemPermissionsDao permissionsDao) { + this.permissionsDao = permissionsDao; + this.permissionsRules = permissionsRules; + } + + + @Override + public Collection listItemPermissions(String itemId) { + return permissionsDao.listItemPermissions(itemId); + } + + @Override + 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); + + permissionsDao.updateItemPermissions(itemId, permission, + addedUsersIds, removedUsersIds); + + } + + @Override + public boolean isAllowed(String itemId,String userId,String action) { + + String userPermission = permissionsDao.getUserItemPermiission(itemId,userId); + return permissionsRules.isAllowed(userPermission,action); + } + + @Override + public void execute(String itemId,String userId,String action) { + permissionsRules.executeAction(itemId, userId, action); + } + + @Override + public String getUserItemPermiission(String itemId, String userId) { + return permissionsDao.getUserItemPermiission(itemId,userId); + } + +} 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 new file mode 100644 index 0000000000..34532cb384 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PrmissionsServicesFactoryImpl.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.itempermissions.dao.impl; + +import org.openecomp.sdc.itempermissions.PermissionsRulesFactory; +import org.openecomp.sdc.itempermissions.PermissionsServices; +import org.openecomp.sdc.itempermissions.PermissionsServicesFactory; +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDaoFactory; + +/** + * Created by ayalaben on 6/22/2017 + */ +public class PrmissionsServicesFactoryImpl extends PermissionsServicesFactory { + + private static final PermissionsServices INSTANCE = + new org.openecomp.sdc.itempermissions.dao.impl.PermissionsServicesImpl(PermissionsRulesFactory.getInstance().createInterface(), + ItemPermissionsDaoFactory.getInstance().createInterface()); + + @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/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 new file mode 100644 index 0000000000..21acc07733 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/servlet/PermissionsFilter.java @@ -0,0 +1,72 @@ +package org.openecomp.sdc.itempermissions.servlet; + +import org.openecomp.sdc.itempermissions.PermissionsServices; +import org.openecomp.sdc.itempermissions.PermissionsServicesFactory; + +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; + +/** + * Created by ayalaben on 6/27/2017. + */ +public class PermissionsFilter implements Filter { + + private final PermissionsServices permissionsServices; + public static final String IRRELEVANT_REQUEST = "Irrelevant_Request"; + public static final String EDIT_ITEM = "Edit_Item"; + + public PermissionsFilter() { + this.permissionsServices = PermissionsServicesFactory.getInstance().createInterface(); + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, + FilterChain filterChain) throws IOException, ServletException { + + if (servletRequest instanceof HttpServletRequest) { + if (((HttpServletRequest) servletRequest).getMethod().equals("POST") + || ((HttpServletRequest) servletRequest).getMethod().equals("PUT")) { + + String userId = ((HttpServletRequest) servletRequest).getHeader("USER_ID"); + String itemId = parseItemIdFromPath(((HttpServletRequest) servletRequest).getPathInfo()); + if ( ! itemId.equals(IRRELEVANT_REQUEST)) { + if ( ! permissionsServices.isAllowed(itemId,userId,EDIT_ITEM)) { + ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_FORBIDDEN); + servletResponse.getWriter().print("Permissions Error. The user does not have " + + "permission to perform" + + " this action."); + return; + } + } + } + } + + filterChain.doFilter(servletRequest, servletResponse); + } + + private String parseItemIdFromPath(String pathInfo) { + String[] tokens = pathInfo.split("/"); + if (tokens.length < 4) { + return IRRELEVANT_REQUEST; + } else { + return tokens[3]; + } + } + + @Override + public void destroy() { + + } +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..d23948437f --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/resources/factoryConfiguration.json @@ -0,0 +1,4 @@ +{ + "org.openecomp.sdc.itempermissions.dao.ItemPermissionsDaoFactory": "org.openecomp.sdc.itempermissions.dao.impl.ItemPermissionsDaoFactoryImpl", +"org.openecomp.sdc.itempermissions.PermissionsServicesFactory" : "org.openecomp.sdc.itempermissions.dao.impl.PrmissionsServicesFactoryImpl" +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/test/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImplTest.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/test/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImplTest.java new file mode 100644 index 0000000000..0a87c29f50 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/test/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImplTest.java @@ -0,0 +1,111 @@ +package org.openecomp.sdc.itempermissions.dao.impl; + +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.itempermissions.PermissionsRules; +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDao; +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Created by ayalaben on 7/9/2017 + */ +public class PermissionsServicesImplTest { + + private static final String ITEM1_ID = "1"; + private static final String PERMISSION = "Owner"; + private static final String USER2_ID = "testUser2"; + private static final String USER1_ID = "testUser1"; + private static final String ACTION_SUBMIT = "Submit_Item"; + private static final String CHANGE_PERMISSIONS = "Change_Item_Permissions"; + + static { + SessionContextProviderFactory.getInstance().createInterface().create("testUser1"); + } + + @Mock + private ItemPermissionsDao permissionsDaoMock; + @Mock + private PermissionsRules permissionsRules; + @InjectMocks + @Spy + private PermissionsServicesImpl permissionsServices; + + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testListItemPermissionsWhenNone() { + Collection permissions = + permissionsServices.listItemPermissions(ITEM1_ID); + Assert.assertEquals(permissions.size(), 0); + } + + + @Test + public void testListItemPermissions(){ + doReturn(Arrays.asList( + createPermissionEntity(ITEM1_ID, USER1_ID, PERMISSION), + createPermissionEntity(ITEM1_ID, USER2_ID, PERMISSION))) + .when(permissionsDaoMock).listItemPermissions(anyObject()); + + Collection actual = + permissionsServices.listItemPermissions(ITEM1_ID); + Assert.assertEquals(actual.size(), 2); + } + + + @Test + public void testIsAllowed(){ + when(permissionsDaoMock.getUserItemPermiission(ITEM1_ID,USER1_ID)).thenReturn(PERMISSION); + when(permissionsRules.isAllowed(PERMISSION,ACTION_SUBMIT)).thenReturn(true); + + Boolean result = permissionsServices.isAllowed(ITEM1_ID,USER1_ID,ACTION_SUBMIT); + + Assert.assertTrue(result); + + } + @Test + public void testUpdatePermissions(){ + + Set addedUsers = new HashSet(); + addedUsers.add(USER2_ID); + + permissionsServices.updateItemPermissions(ITEM1_ID,PERMISSION,addedUsers, + new HashSet()); + + verify(permissionsRules).executeAction(ITEM1_ID,USER1_ID,CHANGE_PERMISSIONS); + verify(permissionsRules).updatePermission(ITEM1_ID,USER1_ID,PERMISSION,addedUsers,new HashSet()); + verify(permissionsDaoMock).updateItemPermissions(ITEM1_ID,PERMISSION,addedUsers,new + HashSet()); + } + + + public static ItemPermissionsEntity createPermissionEntity(String itemId, String + userId, String permission) { + ItemPermissionsEntity permissionsEntity = new ItemPermissionsEntity(); + permissionsEntity.setItemId(itemId); + permissionsEntity.setUserId(userId); + permissionsEntity.setPermission(permission); + return permissionsEntity; + } + +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/pom.xml b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/pom.xml new file mode 100644 index 0000000000..0a3bf6eb9d --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + + org.openecomp.sdc + openecomp-item-permissions-lib + 1.2.0-SNAPSHOT + .. + + openecomp-item-permissions-impl + + + + org.openecomp.sdc + openecomp-item-permissions-api + ${project.version} + + + org.openecomp.sdc + openecomp-item-permissions-core + ${project.version} + runtime + + + \ No newline at end of file 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 new file mode 100644 index 0000000000..c74907ce03 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesFactoryImpl.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.itempermissions.impl; + +import org.openecomp.sdc.itempermissions.PermissionsRules; +import org.openecomp.sdc.itempermissions.PermissionsRulesFactory; + +/** + * Created by ayalaben on 6/26/2017. + */ +public class PermissionsRulesFactoryImpl extends PermissionsRulesFactory { + + @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 new file mode 100644 index 0000000000..22d81a73dc --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImpl.java @@ -0,0 +1,126 @@ +package org.openecomp.sdc.itempermissions.impl; + +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.itempermissions.PermissionsRules; +import org.openecomp.sdc.itempermissions.PermissionsServicesFactory; +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.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; + } + try { + PermissionTypes.valueOf(permission); + } 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: + if (permission.equals(PermissionTypes.Contributor.name()) || permission.equals + (PermissionTypes.Owner.name())) { + return true; + } + break; + case Commit_Item: + 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; + + case Submit_Item: + 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; + } + + @Override + public void executeAction(String itemId, String userId, String action) { + try { + switch (PermissionActionTypes.valueOf(action)) { + case Create_Item: + caseCreateItem(userId,itemId); + break; + + case Change_Item_Permissions: + break; + + case Edit_Item: + break; + + case Submit_Item: + break; + + default: + } + } catch (IllegalArgumentException ex) { + throw new CoreException(new PermissionsErrorMessagesBuilder(INVALID_ACTION_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 (permission.equals(PermissionTypes.Owner.name())) { + + HashSet currentOwner = new HashSet(); + currentOwner.add(currentUserId); + + PermissionsServicesFactory.getInstance().createInterface() + .updateItemPermissions(itemId,PermissionTypes.Contributor.name(), + currentOwner,new HashSet()); + } + } + + protected void caseCreateItem(String userId,String itemId) { + HashSet ownerId = new HashSet(); + ownerId.add(userId); + PermissionsServicesFactory.getInstance().createInterface() + .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 new file mode 100644 index 0000000000..3d1b8a82d7 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionActionTypes.java @@ -0,0 +1,14 @@ +package org.openecomp.sdc.itempermissions.impl.types; + +/** + * Created by ayalaben on 6/26/2017 + */ +public enum PermissionActionTypes { + + Create_Item, + Change_Item_Permissions, + Edit_Item, + Commit_Item, + Submit_Item; + +} 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 new file mode 100644 index 0000000000..e3c93c5e6e --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionTypes.java @@ -0,0 +1,9 @@ +package org.openecomp.sdc.itempermissions.impl.types; + +/** + * Created by ayalaben on 6/26/2017. + */ +public enum PermissionTypes { + Owner, + Contributor +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..a3d3dae5c5 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/resources/factoryConfiguration.json @@ -0,0 +1,3 @@ +{ + "org.openecomp.sdc.itempermissions.PermissionsRulesFactory": "org.openecomp.sdc.itempermissions.impl.PermissionsRulesFactoryImpl" +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImplTest.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImplTest.java new file mode 100644 index 0000000000..635a0b2a25 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImplTest.java @@ -0,0 +1,101 @@ +package org.openecomp.sdc.itempermissions.impl; + +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.itempermissions.dao.impl.PermissionsServicesImpl; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.HashSet; + + +/** + * Created by ayalaben on 7/10/2017 + */ +public class PermissionsRulesImplTest { + + private static final String ITEM1_ID = "1"; + private static final String USER1_ID = "testUser1"; + private static final String PERMISSION_OWNER = "Owner"; + private static final String PERMISSION_CONTRIBUTOR = "Contributor"; + private static final String INVALID_PERMISSION = "Invalid_Permission"; + private static final String SUBMIT_ACTION = "Submit_Item"; + private static final String EDIT_ACTION = "Edit_Item"; + private static final String CHANGE_PERMISSIONS_ACTION = "Change_Item_Permissions"; + private static final String INVALID_ACTION = "Invalid_Action"; + + @Mock + private PermissionsServicesImpl permissionsServices; + + @InjectMocks + @Spy + private PermissionsRulesImpl permissionsRules; + + + @BeforeMethod + public void setUp() throws Exception { + + MockitoAnnotations.initMocks(this); + } + + @Test(expectedExceptions = CoreException.class,expectedExceptionsMessageRegExp = + "Invalid permission type") + public void testIsAllowedWhenInvalidPermission() { + permissionsRules.isAllowed(INVALID_PERMISSION, EDIT_ACTION); + } + + @Test(expectedExceptions = CoreException.class,expectedExceptionsMessageRegExp = + "Invalid action type") + public void testIsAllowedWhenInvalidAction() { + permissionsRules.isAllowed(PERMISSION_CONTRIBUTOR, INVALID_ACTION); + } + + @Test + public void testIsAllowedCaseSubmitOwner(){ + Assert.assertTrue(permissionsRules.isAllowed(PERMISSION_OWNER,SUBMIT_ACTION)); + } + + @Test + public void testIsAllowedCaseSubmitNotOwner(){ + Assert.assertFalse(permissionsRules.isAllowed(PERMISSION_CONTRIBUTOR,SUBMIT_ACTION)); + } + + @Test + public void testIsAllowedCaseEditOwner(){ + Assert.assertTrue(permissionsRules.isAllowed(PERMISSION_OWNER,EDIT_ACTION)); + } + + @Test + public void testIsAllowedCaseEditContributer(){ + Assert.assertTrue(permissionsRules.isAllowed(PERMISSION_CONTRIBUTOR,EDIT_ACTION)); + } + + @Test + public void testIsAllowedCaseChangePermissionsContributer(){ + Assert.assertFalse(permissionsRules.isAllowed(PERMISSION_CONTRIBUTOR,CHANGE_PERMISSIONS_ACTION)); + } + + @Test + public void testIsAllowedCaseChangePermissionsOwner(){ + Assert.assertTrue(permissionsRules.isAllowed(PERMISSION_OWNER,CHANGE_PERMISSIONS_ACTION)); + } + + @Test(expectedExceptions = CoreException.class,expectedExceptionsMessageRegExp = + "Invalid permission type") + public void testUpdatePermissionWhenInvalidPermission() { + permissionsRules.updatePermission(ITEM1_ID,USER1_ID,INVALID_PERMISSION,new HashSet(), + new HashSet()); + } + + @Test(expectedExceptions = CoreException.class,expectedExceptionsMessageRegExp = + "Invalid action type") + public void testExecuteActionInvalidAction(){ + permissionsRules.executeAction(ITEM1_ID,USER1_ID,INVALID_ACTION); + } + + +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/resources/logback.xml b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/resources/logback.xml new file mode 100644 index 0000000000..c1932e31e8 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/resources/logback.xml @@ -0,0 +1,15 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/pom.xml b/openecomp-be/lib/openecomp-item-permissions-lib/pom.xml new file mode 100644 index 0000000000..fbf8ca5ab4 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + + + openecomp-sdc-lib + org.openecomp.sdc + 1.2.0-SNAPSHOT + .. + + + openecomp-item-permissions-lib + pom + + + + openecomp-item-permissions-api + openecomp-item-permissions-impl + openecomp-item-permissions-core + + + \ No newline at end of file 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 98e1c6938a..9ca574a3da 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 @@ -20,6 +20,10 @@ package org.openecomp.sdc.action.errors; +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.ACTION_ARTIFACT_ALREADY_EXISTS_CODE; import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_CHECKSUM_ERROR_CODE; @@ -60,10 +64,6 @@ import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE 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; - /** * Mapper class to map Action Library exceptions to corresponding HTTP Response objects. */ 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 0315a31a70..820fb86e79 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 @@ -20,6 +20,18 @@ package org.openecomp.sdc.action.util; +import org.openecomp.sdc.action.logging.CategoryLogLevel; +import org.openecomp.sdc.action.logging.StatusCode; +import org.openecomp.sdc.action.types.ActionLogResponseCode; +import org.openecomp.sdc.action.types.ActionSubOperation; +import org.slf4j.MDC; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.ZoneOffset; +import java.util.Date; +import java.util.TimeZone; + 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; @@ -104,18 +116,6 @@ import static org.openecomp.sdc.action.types.ActionLogResponseCode.UPDATE_NOT_AL 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 org.openecomp.sdc.action.logging.CategoryLogLevel; -import org.openecomp.sdc.action.logging.StatusCode; -import org.openecomp.sdc.action.types.ActionLogResponseCode; -import org.openecomp.sdc.action.types.ActionSubOperation; -import org.slf4j.MDC; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.time.ZoneOffset; -import java.util.Date; -import java.util.TimeZone; - public class ActionUtil { private static final String UTC_DATE_FORMAT = "dd MMM yyyy kk:mm:ss z"; 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 bfa5830b8d..27f0438f4e 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 @@ -20,20 +20,12 @@ package org.openecomp.sdc.action.dao.impl; -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 org.openecomp.core.dao.impl.CassandraBaseDao; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.sdc.action.dao.ActionArtifactDao; @@ -44,10 +36,18 @@ import org.openecomp.sdc.action.logging.StatusCode; import org.openecomp.sdc.action.types.ActionArtifact; import org.openecomp.sdc.action.types.ActionSubOperation; 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.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; + public class ActionArtifactDaoImpl extends CassandraBaseDao implements ActionArtifactDao { 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 b7f4b5c926..a79687f9a4 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 @@ -20,30 +20,6 @@ package org.openecomp.sdc.action.dao.impl; -import static com.datastax.driver.core.querybuilder.QueryBuilder.eq; -import static com.datastax.driver.core.querybuilder.QueryBuilder.in; -import static com.datastax.driver.core.querybuilder.QueryBuilder.set; -import static org.openecomp.core.nosqldb.impl.cassandra.CassandraSessionFactory.getSession; -import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_CATEGORY; -import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_OPEN_ECOMP_COMPONENT; -import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_MODEL; -import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_NAME; -import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_NONE; -import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_VENDOR; -import static org.openecomp.sdc.action.ActionConstants.STATUS; -import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY; -import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY_DB; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER_CODE; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_NOT_EXIST; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_NOT_EXIST_CODE; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_NOT_LOCKED_CODE; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_NOT_LOCKED_MSG; -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.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.Statement; @@ -56,8 +32,6 @@ import com.datastax.driver.mapping.UDTMapper; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; import org.openecomp.core.dao.impl.CassandraBaseDao; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.core.utilities.json.JsonUtil; @@ -73,6 +47,8 @@ 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.action.util.ActionUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.versioning.VersioningManagerFactory; import org.openecomp.sdc.versioning.dao.VersionInfoDao; import org.openecomp.sdc.versioning.dao.VersionInfoDaoFactory; @@ -93,6 +69,30 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import static com.datastax.driver.core.querybuilder.QueryBuilder.eq; +import static com.datastax.driver.core.querybuilder.QueryBuilder.in; +import static com.datastax.driver.core.querybuilder.QueryBuilder.set; +import static org.openecomp.core.nosqldb.impl.cassandra.CassandraSessionFactory.getSession; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_CATEGORY; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_MODEL; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_NAME; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_NONE; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_OPEN_ECOMP_COMPONENT; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_VENDOR; +import static org.openecomp.sdc.action.ActionConstants.STATUS; +import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY; +import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY_DB; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_NOT_EXIST; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_NOT_EXIST_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_NOT_LOCKED_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_NOT_LOCKED_MSG; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_QUERY_FAILURE_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_QUERY_FAILURE_MSG; + public class ActionDaoImpl extends CassandraBaseDao implements ActionDao { private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); 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 9804bfc3c5..6ca1010a2d 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 @@ -18,10 +18,6 @@ package org.openecomp.sdc.activitylog.dao; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; -import org.openecomp.sdc.versioning.dao.types.Version; - -import java.util.Collection; public interface ActivityLogDao extends BaseDao { - Collection getActivityLogListForItem(String itemId, String versionId); } 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 d3ac277d58..1fc7de7cbc 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 @@ -15,8 +15,8 @@ */ package org.openecomp.sdc.activitylog.dao; -import org.openecomp.core.factory.api.AbstractFactory; import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; public abstract class ActivityLogDaoFactory extends AbstractComponentFactory { 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 e84a2be40a..36a4bbcbfd 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 @@ -16,107 +16,130 @@ package org.openecomp.sdc.activitylog.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.Enumerated; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Calendar; import java.util.Date; @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 String type; - private String user; - private Date timestamp; - private boolean success; - private String message; - private String comment; - - public ActivityLogEntity() {} - - public ActivityLogEntity(String itemId, String versionId, String type, String user, boolean success, String message, String comment) { - this.itemId = itemId; - this.versionId = versionId; - this.type = type; - this.user = user; - this.success = success; - this.message = message; - this.comment = comment; - Calendar now = Calendar.getInstance(); - this.timestamp = now.getTime(); - } - - public String getItemId() { return itemId; } - - public void setItemId(String itemId) { - this.itemId = itemId; - } - - public String getVersionId() { - return versionId; - } - - public void setVersionId(String versionId) { - this.versionId = versionId; - } - - 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 getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public Date getTimestamp() { - return timestamp; - } - - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getComment() { - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } + @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; + @Enumerated + private ActivityType type; + private String user; + private Date timestamp; + private boolean success; + private String message; + private String comment; + + public ActivityLogEntity() { + } + + public ActivityLogEntity(String itemId, Version version) { + this.itemId = itemId; + setVersion(version); + } + + 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 String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public Version getVersion() { + return versionId == null ? null : new Version(versionId); + } + + public void setVersion(Version version) { + this.versionId = version == null ? null : version.getId(); + } + + public String getVersionId() { + return versionId; + } + + public void setVersionId(String versionId) { + this.versionId = versionId; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public ActivityType getType() { + return type; + } + + public void setType(ActivityType type) { + this.type = type; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public Date getTimestamp() { + return timestamp; + } + + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } } 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 new file mode 100644 index 0000000000..620113e2b5 --- /dev/null +++ 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 @@ -0,0 +1,13 @@ +package org.openecomp.sdc.activitylog.dao.type; + +public enum ActivityType { + Create, + Create_Version, + Commit, + Submit, + Upload_Artifact, + 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 5772cc16b7..85e0afa90f 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 @@ -26,58 +26,34 @@ import org.openecomp.sdc.activitylog.dao.ActivityLogDao; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import java.util.Collection; -import java.util.Date; -public class ActivityLogDaoCassandraImpl extends CassandraBaseDao implements ActivityLogDao{ - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final Mapper mapper = - noSqlDb.getMappingManager().mapper(ActivityLogEntity.class); - private static final ActivityLogAccessor accessor = - noSqlDb.getMappingManager().createAccessor(ActivityLogAccessor.class); - - @Override - protected Mapper getMapper() { - return mapper; - } - - @Override - protected Object[] getKeys(ActivityLogEntity entity) { - return new Object[0]; - } - - @Override - public Collection list(ActivityLogEntity entity) { - return accessor.list().all(); - } - - @Override - public void create(ActivityLogEntity activityLogEntity) { - accessor.create(activityLogEntity.getItemId(), activityLogEntity.getVersionId(),activityLogEntity.getId(), - activityLogEntity.getType(),activityLogEntity.getUser(), activityLogEntity.getTimestamp(), activityLogEntity.isSuccess(), - activityLogEntity.getMessage(), activityLogEntity.getComment()); - } - - @Override - public Collection getActivityLogListForItem(String itemId, String versionId) { - return accessor.getForItem(itemId, versionId).all(); - } - - - @Accessor - interface ActivityLogAccessor { - @Query("select item_id, version_id, activity_id, type, user, timestamp, success, message, comment" - + " from activity_log") - Result list(); - - @Query("select item_id, version_id, activity_id, type, user, timestamp, success, message, comment" - + " from activity_log where item_id=? and version_id=?") - Result getForItem(String itemId, String versionId); - - @Query("insert into activity_log " + - " (item_id, version_id, activity_id, type, user, timestamp, success, message, comment)" + - " values (?,?,?,?,?,?,?,?,?)") - Result create(String itemId, String versionId, String id, String type, - String user, Date timestamp, boolean success, - String message, String comment); - } +public class ActivityLogDaoCassandraImpl extends CassandraBaseDao + implements ActivityLogDao { + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static final Mapper mapper = + noSqlDb.getMappingManager().mapper(ActivityLogEntity.class); + private static final ActivityLogAccessor accessor = + noSqlDb.getMappingManager().createAccessor(ActivityLogAccessor.class); + + @Override + protected Mapper getMapper() { + return mapper; + } + + @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(); + } + + @Accessor + interface ActivityLogAccessor { + + @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 98e4cc2ed2..02c8a71b0e 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,10 @@ 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(); + private static final ActivityLogDao INSTANCE = new ActivityLogDaoCassandraImpl(); - @Override - public ActivityLogDao createInterface() { - return INSTANCE; - } + @Override + public ActivityLogDao createInterface() { + return INSTANCE; + } } 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 new file mode 100644 index 0000000000..19d5656036 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ElementType.java @@ -0,0 +1,31 @@ +package org.openecomp.sdc.datatypes.model; + +public enum ElementType { + itemVersion, + + VendorLicenseModel, + LicenseAgreements, LicenseAgreement, + FeatureGroups, FeatureGroup, + LicenseKeyGroups, LicenseKeyGroup, + EntitlementPools, EntitlementPool, + Limits, Limit, + + VendorSoftwareProduct, + VSPQuestionnaire, + + VspModel, NetworkPackage, + OrchestrationTemplateCandidate, OrchestrationTemplateCandidateContent, + // todo - remove OrchestrationTemplateContent + OrchestrationTemplate, OrchestrationTemplateValidationData, 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 +} 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 new file mode 100644 index 0000000000..892351ac4d --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ItemType.java @@ -0,0 +1,6 @@ +package org.openecomp.sdc.datatypes.model; + +public enum ItemType { + vlm, + vsp +} 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 06b157b92c..6610ec5f86 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 @@ -22,12 +22,12 @@ package org.openecomp.sdc.enrichment.impl; import org.openecomp.core.enrichment.api.EnrichmentManager; import org.openecomp.core.enrichment.types.EntityInfo; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.enrichment.EnrichmentInfo; import org.openecomp.sdc.enrichment.factory.EnricherHandlerFactory; import org.openecomp.sdc.enrichment.inter.Enricher; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.versioning.dao.types.Version; diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/test/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImplTest.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/test/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImplTest.java index 1b9e119fbf..acd25dd7bc 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/test/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/test/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImplTest.java @@ -20,8 +20,6 @@ package org.openecomp.sdc.enrichment.impl; -import static org.junit.Assert.assertEquals; - import org.openecomp.core.enrichment.factory.EnrichmentManagerFactory; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.logging.api.Logger; @@ -50,6 +48,8 @@ import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import static org.junit.Assert.assertEquals; + public class EnrichmentManagerImplTest { 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 a5eeece2b3..c9d89ee38f 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 @@ -20,12 +20,12 @@ package org.openecomp.sdc.enrichment.impl; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.enrichment.impl.external.artifact.ExternalArtifactEnricher; import org.openecomp.sdc.enrichment.impl.tosca.ToscaEnricher; import org.openecomp.sdc.enrichment.inter.Enricher; 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; 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 a5f6529bbb..828de7244c 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 @@ -10,10 +10,10 @@ import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.enrichment.EnrichmentInfo; import org.openecomp.sdc.enrichment.inter.ExternalArtifactEnricherInterface; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessType; @@ -28,7 +28,7 @@ import java.util.Map; public class ProcessArtifactEnricher implements ExternalArtifactEnricherInterface { - private VendorSoftwareProductDao vendorSoftwareProductDao; + private ComponentDao componentDao; //private ProcessArtifactDao processArtifactDao; private ProcessDao processDao; private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); @@ -41,10 +41,9 @@ public class ProcessArtifactEnricher implements ExternalArtifactEnricherInterfac Version version = enrichmentInfo.getVersion(); Collection components = - getVendorSoftwareProductDao().listComponents(vspId, version); - components.stream() - .forEach(componentEntry -> errors.putAll(enrichComponent(componentEntry, - vspId, version))); + getComponentDao().list(new ComponentEntity(vspId, version, null)); + components.forEach(componentEntry -> errors.putAll(enrichComponent(componentEntry, + vspId, version))); return errors; } @@ -79,10 +78,9 @@ public class ProcessArtifactEnricher implements ExternalArtifactEnricherInterfac ProcessArtifactEntity artifactEntity = new ProcessArtifactEntity(vspId, version, componentId, entity.getId());*/ - processes.stream() - .forEach(entity -> { - ProcessEntity artifactEntity = new ProcessEntity(vspId, version, - componentId, entity.getId()); + processes.forEach(entity -> { + ProcessEntity artifactEntity = new ProcessEntity(vspId, version, + componentId, entity.getId()); ProcessEntity artifactProcessEntity = getProcessDao().get(artifactEntity); //ProcessArtifactEntity artifact = getProcessArtifactDao().get(artifactEntity); @@ -105,7 +103,7 @@ public class ProcessArtifactEnricher implements ExternalArtifactEnricherInterfac } }); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } void enrichServiceArtifact(ComponentProcessInfo componentProcessInfo, @@ -113,19 +111,19 @@ public class ProcessArtifactEnricher implements ExternalArtifactEnricherInterfac Map> errors) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); processServiceArtifact.setName(componentProcessInfo.getName()); processServiceArtifact.setContentData(FileUtils.toByteArray(componentProcessInfo.getContent())); getEnrichedServiceModelDao().storeExternalArtifact(processServiceArtifact); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } - private VendorSoftwareProductDao getVendorSoftwareProductDao() { - if (vendorSoftwareProductDao == null) { - vendorSoftwareProductDao = VendorSoftwareProductDaoFactory.getInstance().createInterface(); + private ComponentDao getComponentDao() { + if (componentDao == null) { + componentDao = ComponentDaoFactory.getInstance().createInterface(); } - return vendorSoftwareProductDao; + return componentDao; } private ProcessDao getProcessDao() { 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 b7da22bdfb..9e46a5c33d 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 @@ -32,8 +32,6 @@ import org.openecomp.sdc.enrichment.EnrichmentInfo; import org.openecomp.sdc.enrichment.inter.ExternalArtifactEnricherInterface; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; @@ -61,8 +59,6 @@ public class VspInformationArtifactEnricher implements ExternalArtifactEnricherI EnrichedServiceModelDaoFactory.getInstance().createInterface(); private VendorSoftwareProductInfoDao vspInfoDao = VendorSoftwareProductInfoDaoFactory .getInstance().createInterface(); - private OrchestrationTemplateDao orchestrationTemplateDataDao = - OrchestrationTemplateDaoFactory.getInstance().createInterface(); public VspInformationArtifactEnricher() { } @@ -81,7 +77,7 @@ public class VspInformationArtifactEnricher implements ExternalArtifactEnricherI throws IOException { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); Map> errors = new HashMap<>(); ByteBuffer infoArtifactByteBuffer = ByteBuffer.wrap(informationArtifactGenerator.generate( @@ -94,13 +90,13 @@ public class VspInformationArtifactEnricher implements ExternalArtifactEnricherI vspId, version.toString()))); //TODO: add error to map (what is the key?) - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); return errors; } enrichInformationArtifact(vspId, version, infoArtifactByteBuffer); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); return errors; } @@ -108,10 +104,7 @@ public class VspInformationArtifactEnricher implements ExternalArtifactEnricherI ByteBuffer infoArtifactByteBuffer) { ServiceArtifact infoArtifactServiceArtifact = new ServiceArtifact(); - VspDetails vspDetails = getVspDetails(vspId, version); - - String vspName = vspDetails.getName(); - + String vspName = vspInfoDao.get(new VspDetails(vspId, version)).getName(); infoArtifactServiceArtifact.setVspId(vspId); infoArtifactServiceArtifact.setVersion(version); @@ -126,9 +119,5 @@ public class VspInformationArtifactEnricher implements ExternalArtifactEnricherI enrichedServiceModelDao.storeExternalArtifact(infoArtifactServiceArtifact); } - public VspDetails getVspDetails(String vspId,Version version){ - VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId,version)); - vspDetails.setValidationData(orchestrationTemplateDataDao.getValidationData(vspId,version)); - return vspDetails; - } + } 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 f49c53d79b..9ebe9e5e67 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 @@ -26,36 +26,35 @@ import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.MIN_INS import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.VFC_NAMING_CODE; - public class ComponentQuestionnaireData { ComponentDao componentDao = ComponentDaoFactory.getInstance().createInterface(); - ComponentDependencyModelDao componentDependencyModelDao = ComponentDependencyModelDaoFactory.getInstance() - .createInterface(); + ComponentDependencyModelDao componentDependencyModelDao = + ComponentDependencyModelDaoFactory.getInstance().createInterface(); - private Map sourceToTargetComponent; + private Map sourceToTargetComponent; - public Map getSourceToTargetComponent() { + public Map getSourceToTargetComponent() { return sourceToTargetComponent; } - public void setSourceToTargetComponent(Map sourceToTargetComponent) { + public void setSourceToTargetComponent(Map sourceToTargetComponent) { this.sourceToTargetComponent = sourceToTargetComponent; } public Map> getPropertiesfromCompQuestionnaire(String key, Version version) { - Map> componentProperties = - new HashMap>(); + Map> componentProperties = + new HashMap>(); ComponentEntity entity = new ComponentEntity(key, version, null); final Collection componentEntities = componentDao.listCompositionAndQuestionnaire(key, version); - Map sourceToTarget = new HashMap(); + Map sourceToTarget = new HashMap<>(); for (ComponentEntity component : componentEntities) { - Map questionnaireParams = new HashMap(); + Map questionnaireParams = new HashMap<>(); final ComponentQuestionnaire componentQuestionnaire = JsonUtil.json2Object(component.getQuestionnaireData(), ComponentQuestionnaire.class); @@ -77,7 +76,7 @@ public class ComponentQuestionnaireData { questionnaireParams.put(EnrichmentConstants.VFC_FUNCTION, vfcDescription); - if (componentQuestionnaire.getHighAvailabilityAndLoadBalancing() != null ) { + if (componentQuestionnaire.getHighAvailabilityAndLoadBalancing() != null) { String mandatory = componentQuestionnaire.getHighAvailabilityAndLoadBalancing() .getIsComponentMandatory(); questionnaireParams.put(MANDATORY, mandatory); @@ -91,19 +90,20 @@ public class ComponentQuestionnaireData { final Integer maxVms = componentQuestionnaire.getCompute() != null ? (componentQuestionnaire.getCompute() .getNumOfVMs() != null ? componentQuestionnaire.getCompute().getNumOfVMs() - .getMaximum(): null) : null; + .getMaximum() : null) : null; final Integer minVms = componentQuestionnaire.getCompute() != null ? (componentQuestionnaire.getCompute() .getNumOfVMs() != null ? componentQuestionnaire.getCompute().getNumOfVMs() - .getMinimum(): null) : null; + .getMinimum() : null) : null; - questionnaireParams.put(MIN_INSTANCES,minVms != null && minVms == 0 ? null : minVms); - questionnaireParams.put(MAX_INSTANCES,maxVms != null && maxVms == 0 ? null : maxVms); + questionnaireParams.put(MIN_INSTANCES, minVms != null && minVms == 0 ? null : minVms); + questionnaireParams.put(MAX_INSTANCES, maxVms != null && maxVms == 0 ? null : maxVms); - if (! questionnaireParams.isEmpty()) + if (!questionnaireParams.isEmpty()) { componentProperties.put(JsonUtil.json2Object(component.getCompositionData(), ComponentData.class).getDisplayName(), questionnaireParams); + } } setSourceToTargetComponent(sourceToTarget); @@ -111,12 +111,12 @@ public class ComponentQuestionnaireData { return componentProperties; } - public Map> populateDependencies(String vspId, Version version, Map componentNameData) { + public Map> populateDependencies(String vspId, Version version, Map componentNameData) { Collection componentDependencies = componentDependencyModelDao.list(new ComponentDependencyModelEntity(vspId, version, null)); - Map> sourceToTargetComponent = new HashMap>(); + Map> sourceToTargetComponent = new HashMap>(); List targetComponents = null; for (ComponentDependencyModelEntity dependency : componentDependencies) { String sourceComponentName = componentNameData.get(dependency.getSourceComponentId()); 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 705773d1fc..a855a7477f 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 @@ -1,9 +1,5 @@ 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 org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.sdc.datatypes.error.ErrorMessage; @@ -39,6 +35,10 @@ import java.util.Optional; import java.util.Set; 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 { //Map of service template file name and map of all port node template ids, node template private Map> portNodeTemplates = new HashMap<>(); 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 090c3ae101..5ea1176e48 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 @@ -20,11 +20,13 @@ 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.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -45,13 +47,19 @@ public class ToscaEnricher extends Enricher { private Map> enrichAbstractSubstitute() { mdcDataDebugMessage.debugEntryMessage(null, null); - Map> enrichErrors; + Map> enrichErrors = new HashMap<>(); ToscaServiceModel toscaModel = (ToscaServiceModel) model; AbstractSubstituteToscaEnricher abstractSubstituteToscaEnricher = new AbstractSubstituteToscaEnricher(); - enrichErrors = abstractSubstituteToscaEnricher.enrich(toscaModel, data.getKey(), - data.getVersion()); + + try { + enrichErrors = abstractSubstituteToscaEnricher.enrich(toscaModel, data.getKey(), + data.getVersion()); + }catch (Exception e){ + enrichErrors.put("Tosca Enrich", Arrays.asList(new ErrorMessage(ErrorLevel.ERROR, e + .getMessage()))); + } mdcDataDebugMessage.debugExitMessage(null, null); return enrichErrors; @@ -59,10 +67,16 @@ public class ToscaEnricher extends Enricher { private Map> enrichPortMirroring() { mdcDataDebugMessage.debugEntryMessage(null, null); - Map> enrichErrors; + Map> enrichErrors = new HashMap<>(); ToscaServiceModel toscaModel = (ToscaServiceModel) model; PortMirroringEnricher portMirroringEnricher = new PortMirroringEnricher(); - enrichErrors = portMirroringEnricher.enrich(toscaModel); + + try { + enrichErrors = portMirroringEnricher.enrich(toscaModel); + }catch (Exception e){ + enrichErrors.put("Tosca Enrich", Arrays.asList(new ErrorMessage(ErrorLevel.ERROR, e + .getMessage()))); + } mdcDataDebugMessage.debugExitMessage(null, null); return enrichErrors; } 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 49b424ef05..bd250bb8f4 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 @@ -32,5 +32,5 @@ import java.util.Map; * Created by Talio on 11/24/2016. */ public interface ExternalArtifactEnricherInterface { - public Map> enrich(EnrichmentInfo enrichmentInfo) throws IOException; + Map> enrich(EnrichmentInfo enrichmentInfo) throws IOException; } diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/MonitoringMibEnricherTest.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/MonitoringMibEnricherTest.java index 3730a15465..c01f986ab1 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/MonitoringMibEnricherTest.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/MonitoringMibEnricherTest.java @@ -35,7 +35,6 @@ import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; import org.openecomp.sdc.versioning.dao.types.Version; @@ -60,8 +59,6 @@ public class MonitoringMibEnricherTest { @Mock private EnrichedServiceModelDao enrichedServiceModelDaoMock; @Mock - private VendorSoftwareProductDao vendorSoftwareProductDaoMock; - @Mock private ComponentDao componentDaoMock; @InjectMocks @@ -157,7 +154,7 @@ public class MonitoringMibEnricherTest { private ByteBuffer getMibByteBuffer(String fileName) { byte[] mibBytes = FileUtils.readViaInputStream(this.getClass().getResource(fileName), - stream -> FileUtils.toByteArray(stream)); + stream -> FileUtils.toByteArray(stream)); return ByteBuffer.wrap(mibBytes); } diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricherTest.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricherTest.java index 0bd84a4e30..59931a1a11 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricherTest.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricherTest.java @@ -1,46 +1,15 @@ package org.openecomp.sdc.enrichment.impl.external.artifact; -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.openecomp.core.enrichment.types.ArtifactCategory; -import org.openecomp.core.model.dao.EnrichedServiceModelDao; -import org.openecomp.core.model.types.ServiceArtifact; -import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.sdc.enrichment.EnrichmentInfo; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; -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 org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.io.File; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; - -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.when; - public class ProcessArtifactEnricherTest { /*@Mock ProcessDao processDaoMock; @Mock EnrichedServiceModelDao enrichedServiceModelDaoMock; @Mock - VendorSoftwareProductDao vendorSoftwareProductDaoMock; - + ComponentDao componentDaoMock; @InjectMocks ProcessArtifactEnricher processArtifactEnricher; - @BeforeMethod(alwaysRun = true) public void injectDoubles() { MockitoAnnotations.initMocks(this); @@ -65,11 +34,11 @@ public class ProcessArtifactEnricherTest { processEntity.setArtifactName("artifact_1kb.txt"); processEntity.setArtifact(getMibByteBuffer("/mock/enrichProcess/artifact_1kb.txt")); - Collection componentList = new ArrayList(); + Collection componentList = new ArrayList<>(); componentList.add(componentEntity); - when(vendorSoftwareProductDaoMock.listComponents(vspId, version)).thenReturn(componentList); + when(componentDaoMock.list(anyObject())).thenReturn(componentList); - Collection list = new ArrayList(); + Collection list = new ArrayList<>(); list.add(processEntity); when(processDaoMock.list(entity)).thenReturn(list); @@ -111,7 +80,7 @@ public class ProcessArtifactEnricherTest { private ByteBuffer getMibByteBuffer(String fileName) { byte[] mibBytes = FileUtils.readViaInputStream(this.getClass().getResource(fileName), - stream -> FileUtils.toByteArray(stream)); + stream -> FileUtils.toByteArray(stream)); return ByteBuffer.wrap(mibBytes); }*/ } diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/BaseToscaEnrichmentTest.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/BaseToscaEnrichmentTest.java index 0001cdf404..363e171c6c 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/BaseToscaEnrichmentTest.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/BaseToscaEnrichmentTest.java @@ -25,12 +25,18 @@ import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; import org.openecomp.sdc.tosca.services.ToscaFileOutputService; import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl; -import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; -import java.io.*; +import java.io.BufferedInputStream; +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.net.URL; import java.nio.file.NotDirectoryException; import java.util.Collection; diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireDataTest.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireDataTest.java index 73732575f3..d6810d92b0 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireDataTest.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireDataTest.java @@ -1,31 +1,5 @@ package org.openecomp.sdc.enrichment.impl.tosca; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.mockito.Mockito.doReturn; -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.VFC_CODE; -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.VFC_FUNCTION; -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.VFC_NAMING_CODE; - public class ComponentQuestionnaireDataTest { /*private static String VSP_ID = "vspId"; public static final Version VERSION01 = new Version(0, 1); diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricherTest.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricherTest.java index 0a8fe432b0..b48fd8d8d7 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricherTest.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricherTest.java @@ -2,8 +2,6 @@ package org.openecomp.sdc.enrichment.impl.tosca; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerServiceName.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerServiceName.java index 08c957a58e..1a9d327414 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerServiceName.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerServiceName.java @@ -161,8 +161,14 @@ public enum LoggerServiceName { CREATE_COMPONENT_DEPENDENCY_MODEL, GET_COMPONENT_DEPENDENCY_MODEL, - - Health_check + GET_LIST_COMPONENT_DEPENDENCY, + CREATE_COMPONENT_DEPENDENCY, + UPDATE_COMPONENT_DEPENDENCY, + DELETE_COMPONENT_DEPENDENCY, + GET_COMPONENT_DEPENDENCY, + + Health_check, + notifications ; public static String getServiceName(LoggerServiceName serviceName) { diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerTragetServiceName.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerTragetServiceName.java index 33573a5572..ab7292a485 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerTragetServiceName.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerTragetServiceName.java @@ -128,6 +128,8 @@ public class LoggerTragetServiceName { public static final String CREATE_TRANSLATED_FILE = "Create Translated File"; public static final String CREATE_PACKAGE = "Create Package"; + public static final String CREATE_VERSION = "Create Version"; + public static final String SELF_HEALING = "Self Healing"; public static final String WRITE_ARTIFACT_XML = "Write Artifact To XML File"; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/LoggerFactoryTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/LoggerFactoryTest.java index aa04c50210..4b3a1ba7c7 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/LoggerFactoryTest.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/LoggerFactoryTest.java @@ -21,7 +21,9 @@ import org.testng.annotations.Test; import java.lang.reflect.Field; import java.util.ServiceLoader; -import static org.testng.Assert.*; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; /** * @author evitaliy diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/context/TaskFactoryTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/context/TaskFactoryTest.java index 61e1819b3b..f5c2187024 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/context/TaskFactoryTest.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/context/TaskFactoryTest.java @@ -4,7 +4,9 @@ import org.testng.annotations.Test; import java.util.ServiceLoader; -import static org.testng.Assert.*; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; /** * @author evitaliy diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/servlet/LoggingFilter.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/servlet/LoggingFilter.java index f34d09e882..0ca550a20a 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/servlet/LoggingFilter.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/servlet/LoggingFilter.java @@ -20,7 +20,12 @@ import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.slf4j.MDC; -import javax.servlet.*; +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 java.io.IOException; import java.net.InetAddress; @@ -58,7 +63,7 @@ public class LoggingFilter implements Filter { private static final HostAddressCache HOST_ADDRESS = new HostAddressCache(); private static final String UNKNOWN = "UNKNOWN"; - private final static Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class); + private static final Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class); public void destroy() { } @@ -80,7 +85,8 @@ public class LoggingFilter implements Filter { InetAddress host = HOST_ADDRESS.get(); - String ipAddress, hostName; + String ipAddress; + String hostName; if (host == null) { ipAddress = UNKNOWN; hostName = UNKNOWN; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/context/MDCPropagationFactoryTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/context/MDCPropagationFactoryTest.java index 8502d95023..1fda9e85b3 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/context/MDCPropagationFactoryTest.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/context/MDCPropagationFactoryTest.java @@ -22,7 +22,9 @@ import org.testng.annotations.Test; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; -import static org.testng.Assert.*; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; /** * @author evitaliy diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/servlet/LoggingFilterTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/servlet/LoggingFilterTest.java index 57911a368f..95a5421be0 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/servlet/LoggingFilterTest.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/servlet/LoggingFilterTest.java @@ -20,7 +20,13 @@ import org.slf4j.MDC; import org.testng.Assert; import org.testng.annotations.Test; -import javax.servlet.*; +import javax.servlet.FilterChain; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; 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 aa8cbee7d4..3e5975dd13 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 @@ -22,9 +22,6 @@ package org.openecomp.core.model.dao; 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.List; public interface EnrichedServiceModelDao extends VersionableDao,ServiceModelDao{ 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 d3d125b849..8736f369c7 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 @@ -16,14 +16,12 @@ package org.openecomp.core.model.types; -import com.google.common.io.ByteStreams; - 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.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; 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 c837a70c36..f60c8922cd 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 @@ -16,14 +16,12 @@ package org.openecomp.core.model.types; -import com.google.common.io.ByteStreams; - 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.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; 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 8385a5da48..ddff54b436 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 @@ -16,13 +16,12 @@ package org.openecomp.core.model.types; -import com.google.common.io.ByteStreams; - 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.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; 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 4897c2f076..8f886c2e74 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 @@ -20,14 +20,12 @@ package org.openecomp.core.model.types; -import com.google.common.io.ByteStreams; - 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.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/EnrichedServiceModelDaoImpl.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/EnrichedServiceModelDaoImpl.java index 14eda9ee4d..348a8addbd 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/EnrichedServiceModelDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/EnrichedServiceModelDaoImpl.java @@ -23,13 +23,10 @@ package org.openecomp.sdc.model.impl; import org.openecomp.core.model.dao.EnrichedServiceArtifactDaoFactory; import org.openecomp.core.model.dao.EnrichedServiceModelDao; import org.openecomp.core.model.dao.EnrichedServiceTemplateDaoFactory; -import org.openecomp.core.model.types.ServiceArtifact; import org.openecomp.core.model.types.ServiceElement; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.List; - public class EnrichedServiceModelDaoImpl extends AbstractServiceModelDao implements EnrichedServiceModelDao { public EnrichedServiceModelDaoImpl() { 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 d018c9a87c..3bd2881117 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 @@ -1,7 +1,6 @@ package org.openecomp.sdc.model.impl.zusammen; 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; @@ -11,10 +10,13 @@ import org.openecomp.core.model.types.ServiceElement; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; 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 { @@ -23,28 +25,31 @@ public class EnrichedServiceModelDaoZusammenImpl extends ServiceModelDaoZusammen public EnrichedServiceModelDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { super(zusammenAdaptor); - this.name = StructureElement.EnrichedServiceModel.name(); + this.elementType = ElementType.EnrichedServiceModel; } @Override public void storeExternalArtifact(ServiceArtifact serviceArtifact) { - ZusammenElement artifactElement = buildArtifactElement(serviceArtifact.getName(), + ZusammenElement artifact = buildArtifactElement(serviceArtifact.getName(), FileUtils.toByteArray(serviceArtifact.getContent()), Action.CREATE); - ZusammenElement artifactsElement = - buildStructuralElement(StructureElement.Artifacts.name(), null); - artifactsElement.addSubElement(artifactElement); + ZusammenElement artifacts = buildStructuralElement(ElementType.Artifacts, Action.IGNORE); + artifacts.addSubElement(artifact); + + ZusammenElement enrichedServiceModel = buildStructuralElement(elementType, Action.IGNORE); + enrichedServiceModel.addSubElement(artifacts); - ZusammenElement enrichedServiceModelElement = buildStructuralElement(name, null); - enrichedServiceModelElement.addSubElement(artifactsElement); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(enrichedServiceModel); SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(serviceArtifact.getVspId()); - ElementContext elementContext = new ElementContext(itemId, getFirstVersionId(context, itemId)); + ElementContext elementContext = + new ElementContext(serviceArtifact.getVspId(), serviceArtifact.getVersion().getId()); zusammenAdaptor - .saveElement(context, elementContext, enrichedServiceModelElement, "add service artifact."); + .saveElement(context, elementContext, vspModel, "add service external artifact."); - logger.info("Finished adding artifact to service model for vsp id -> " + + 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 b5e3627e61..4ae9353f42 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 @@ -8,7 +8,6 @@ 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 com.amdocs.zusammen.datatypes.item.ItemVersion; import org.apache.commons.io.IOUtils; import org.openecomp.core.model.dao.ServiceModelDao; import org.openecomp.core.model.errors.RetrieveServiceTemplateFromDbErrorBuilder; @@ -17,14 +16,14 @@ import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.api.ZusammenUtil; import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionStatus; -import org.openecomp.core.converter.datatypes.Constants; +import org.openecomp.types.ElementPropertyName; import java.io.ByteArrayInputStream; import java.util.Collection; @@ -33,16 +32,20 @@ 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 String name; + protected ElementType elementType; public ServiceModelDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { this.zusammenAdaptor = zusammenAdaptor; - this.name = StructureElement.ServiceModel.name(); + this.elementType = ElementType.ServiceModel; } @Override @@ -53,98 +56,59 @@ public class ServiceModelDaoZusammenImpl @Override public ToscaServiceModel getServiceModel(String vspId, Version version) { SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, getFirstVersionId(context, itemId), - version.getStatus() == VersionStatus.Locked ? null : version.toString()); - - Optional serviceModelElement = zusammenAdaptor - .getElementInfoByName(context, elementContext, null, name); - - if (serviceModelElement.isPresent()) { - String entryDefinitionServiceTemplate = - serviceModelElement.get().getInfo().getProperty("base"); - Id serviceModelElementId = serviceModelElement.get().getId(); - Map serviceTemplates = - getTemplates(context, elementContext, serviceModelElementId); - if (serviceTemplates == null) { - return null; - } - FileContentHandler artifacts = getArtifacts(context, elementContext, serviceModelElementId); - + ElementContext elementContext = new ElementContext(vspId, version.getId()); - return new ToscaServiceModel( - artifacts, serviceTemplates, entryDefinitionServiceTemplate); - } else { + Optional serviceModel = getServiceModelElementInfo(context, elementContext); + if (!serviceModel.isPresent()) { return null; } - } - - protected Map getTemplates(SessionContext context, - ElementContext elementContext, - Id serviceModelElementId) { - Optional templatesElementInfo = zusammenAdaptor.getElementInfoByName( - context, elementContext, serviceModelElementId, StructureElement.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)); + Id serviceModelElementId = serviceModel.get().getId(); + Map serviceTemplates = + getTemplates(context, elementContext, serviceModelElementId); + if (serviceTemplates == null) { + return null; } - return null; - } - - protected FileContentHandler getArtifacts(SessionContext context, ElementContext elementContext, - Id serviceModelElementId) { - Optional artifactsElement = zusammenAdaptor.getElementInfoByName( - context, elementContext, serviceModelElementId, StructureElement.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; - } + FileContentHandler artifacts = getArtifacts(context, elementContext, serviceModelElementId); + String entryDefinitionServiceTemplate = + serviceModel.get().getInfo().getProperty(BASE_PROPERTY); - return null; + return new ToscaServiceModel(artifacts, serviceTemplates, entryDefinitionServiceTemplate); } @Override public void storeServiceModel(String vspId, Version version, ToscaServiceModel serviceModel) { - logger.info("Storing service model for vsp id -> " + vspId); + logger.info("Storing service model for VendorSoftwareProduct id -> {}", vspId); - ZusammenElement templatesElement = - buildStructuralElement(StructureElement.Templates.name(), null); + ZusammenElement templatesElement = buildStructuralElement(ElementType.Templates, Action.UPDATE); serviceModel.getServiceTemplates().entrySet().forEach(entry -> templatesElement.addSubElement( buildServiceTemplateElement(entry.getKey(), entry.getValue(), serviceModel.getEntryDefinitionServiceTemplate(), Action.CREATE))); - ZusammenElement artifactsElement = - buildStructuralElement(StructureElement.Artifacts.name(), Action.UPDATE); + ZusammenElement artifactsElement = buildStructuralElement(ElementType.Artifacts, Action.UPDATE); if (Objects.nonNull(serviceModel.getArtifactFiles())) { - serviceModel.getArtifactFiles().getFiles().entrySet().forEach(entry -> artifactsElement - .addSubElement(buildArtifactElement(entry.getKey(), entry.getValue(), Action.CREATE))); + serviceModel.getArtifactFiles().getFiles().entrySet() + .forEach(entry -> artifactsElement.addSubElement( + buildArtifactElement(entry.getKey(), entry.getValue(), Action.CREATE))); } - ZusammenElement serviceModelElement = buildStructuralElement(name, Action.UPDATE); + ZusammenElement serviceModelElement = buildStructuralElement(elementType, Action.UPDATE); serviceModelElement.getInfo() - .addProperty("base", serviceModel.getEntryDefinitionServiceTemplate()); + .addProperty(BASE_PROPERTY, serviceModel.getEntryDefinitionServiceTemplate()); serviceModelElement.addSubElement(templatesElement); serviceModelElement.addSubElement(artifactsElement); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(serviceModelElement); + SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, getFirstVersionId(context, itemId)); - zusammenAdaptor - .saveElement(context, elementContext, serviceModelElement, "Store service model"); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + zusammenAdaptor.saveElement(context, elementContext, vspModel, "Store service model"); - logger.info("Finished storing service model for vsp id -> " + vspId); + logger + .info("Finished storing {} for VendorSoftwareProduct id -> {}", elementType.name(), vspId); } @Override @@ -154,65 +118,132 @@ public class ServiceModelDaoZusammenImpl @Override public void deleteAll(String vspId, Version version) { - logger.info("started deleting service model for vsp id -> " + vspId); + logger.info("Started deleting content of Templates and Artifacts of {} of vsp {} version {}", + elementType.name(), vspId, version.getId()); + SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, getFirstVersionId(context, itemId)); + 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); + } + } - ZusammenElement zusammenElement = ZusammenUtil.buildStructuralElement(name, Action.DELETE); - zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "delete:" + name + "."); - logger.info("Finished deleting service model for vsp id -> " + vspId); + 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()); } - protected ZusammenElement buildArtifactElement(String name, byte[] artifact, Action action) { - ZusammenElement artifactElement = new ZusammenElement(); - artifactElement.setAction(action); - Info info = new Info(); - info.setName(name); - info.addProperty("type", ElementType.Artifact.name()); - artifactElement.setInfo(info); - artifactElement.setData(new ByteArrayInputStream(artifact)); + private Optional getServiceModelElementInfo(SessionContext context, + ElementContext elementContext) { + Collection vspModelSubs = zusammenAdaptor + .listElementsByName(context, elementContext, null, ElementType.VspModel.name()); - return artifactElement; + return vspModelSubs.stream() + .filter(elementInfo -> elementInfo.getInfo() != null + && elementType.name().equals(elementInfo.getInfo().getName())) + .findFirst(); } - private ServiceTemplate elementToServiceTemplate(Element element){ + private Map getTemplates(SessionContext context, + ElementContext elementContext, + Id serviceModelElementId) { + Optional templatesElementInfo = zusammenAdaptor.getElementInfoByName( + context, elementContext, serviceModelElementId, ElementType.Templates.name()); - 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()); + 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 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; } private Element buildServiceTemplateElement(String name, ServiceTemplate serviceTemplate, String entryDefinitionServiceTemplate, Action action) { - ZusammenElement zusammenElement = new ZusammenElement(); - zusammenElement.setAction(action); + ZusammenElement zusammenElement = buildElement(null, action); Info info = new Info(); info.setName(name); info.setDescription(serviceTemplate.getDescription()); - info.addProperty("type", ElementType.Servicetemplate.name()); - info.addProperty("base", entryDefinitionServiceTemplate); + 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 Id getFirstVersionId(SessionContext context, Id vspId) { - Optional itemVersionOptional = zusammenAdaptor.getFirstVersion(context, vspId); - ItemVersion itemVersion = itemVersionOptional.orElseThrow(() -> - new RuntimeException(String.format("Vsp %s does not contain any version.", vspId))); //todo - return itemVersion.getId(); + 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; } - protected ZusammenElement buildStructuralElement(String structureElement, Action action) { - return ZusammenUtil.buildStructuralElement(structureElement, action); + + 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-notification-lib/openecomp-sdc-notification-api/pom.xml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/pom.xml new file mode 100644 index 0000000000..8e1c293e16 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/pom.xml @@ -0,0 +1,20 @@ + + 4.0.0 + + openecomp-sdc-notification-api + openecomp-sdc-notification-api + + org.openecomp.sdc + openecomp-sdc-lib + 1.2.0-SNAPSHOT + ../.. + + + + org.openecomp.sdc.core + openecomp-nosqldb-core + ${project.version} + + + 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 new file mode 100644 index 0000000000..0c6dfc8580 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/destinationprovider/DestinationProvider.java @@ -0,0 +1,11 @@ +package org.openecomp.sdc.destinationprovider; + +import java.util.List; + +/** + * @author avrahamg + * @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 new file mode 100644 index 0000000000..f0bf7e8874 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/LastNotificationDao.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.dao; + +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); + +} 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 new file mode 100644 index 0000000000..6542d70158 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/NotificationsDao.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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; + + +public interface NotificationsDao extends BaseDao { + + int DEFAULT_LIMIT_OF_RESULTS_FOR_OWNER_NOTIFICATIONS = 1000; + + List getNotificationsByOwnerId(String ownerId, int limit); + + List getNewNotificationsByOwnerId(String ownerId, UUID eventId); + + List getNewNotificationsByOwnerId(String ownerId, UUID eventId, int limit); + + NotificationsStatus getNotificationsStatus(String ownerId, UUID lastSeenNotification, int numOfRecordsToReturn); + + NotificationsStatus getNotificationsStatus(String ownerId, UUID lastSeenNotification, int numOfRecordsToReturn, UUID prevLastNotification); + + 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 new file mode 100644 index 0000000000..3daf165efc --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/SubscribersDao.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.dao; + +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); + + 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 new file mode 100644 index 0000000000..d6e717d1b3 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/LastSeenNotificationEntity.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +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.Objects; +import java.util.UUID; + +@Table(keyspace = "dox", name = "last_notification") +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; + + public LastSeenNotificationEntity() { + } + + /** + * Instantiates a new Notification entity. + * + * @param ownerId the owner id + * @param lastEventId the last event id + */ + public LastSeenNotificationEntity(String ownerId, UUID lastEventId) { + this.ownerId = ownerId; + this.lastEventId = lastEventId; + } + + public String getOwnerId() { + return ownerId; + } + + public void setOwnerId(String ownerId) { + this.ownerId = ownerId; + } + + public UUID getLastEventId() { + return lastEventId; + } + + public void setLastEventId(UUID lastEventId) { + this.lastEventId = lastEventId; + } + + @Override + public boolean equals(Object other) { + if (Objects.equals(this, other)) { + return true; + } + + if (Objects.equals(getClass(), other.getClass())) { + return false; + } + + LastSeenNotificationEntity that = (LastSeenNotificationEntity) other; + + if (Objects.equals(ownerId, that.ownerId)) { + return false; + } + + return !Objects.equals(lastEventId, that.lastEventId); + } + + @Override + public int hashCode() { + int result = ownerId != null ? ownerId.hashCode() : 0; + result = 31 * result + (lastEventId != null ? lastEventId.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "LastSeenNotificationEntity {" + + "ownerId='" + ownerId + '\'' + + '}'; + } +} 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 new file mode 100644 index 0000000000..52377077cf --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/NotificationEntity.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +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.Objects; +import java.util.UUID; + +@Table(keyspace = "dox", name = "notifications") +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; + + public NotificationEntity() { + } + + public NotificationEntity(String ownerId) { + this.ownerId = ownerId; + } + + /** + * Instantiates a new Notification entity. + * + * @param ownerId the owner id + * @param eventId the event id + * @param eventType the event type + * @param originatorId the originator id + */ + public NotificationEntity(String ownerId, UUID eventId, String eventType, String originatorId, boolean read, String eventAttributes) { + this.ownerId = ownerId; + this.read = read; + this.eventId = eventId; + this.eventType = eventType; + this.originatorId = originatorId; + this.eventAttributes = eventAttributes; + } + + public NotificationEntity(String ownerId, UUID eventId, String eventType, String originatorId) { + this(ownerId, eventId, eventType, originatorId, false, null); + } + + public NotificationEntity(String ownerId, UUID eventId) { + this(ownerId, eventId, null, null); + } + + public String getOwnerId() { + return ownerId; + } + + public void setOwnerId(String ownerId) { + this.ownerId = ownerId; + } + + 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 String getEventAttributes() { + return eventAttributes; + } + + public void setEventAttributes(String eventAttributes) { + this.eventAttributes = eventAttributes; + } + + public String getOriginatorId() { + return originatorId; + } + + public void setOriginatorId(String originatorId) { + this.originatorId = originatorId; + } + + @Override + public boolean equals(Object other) { + if (Objects.equals(this, other)) { + return true; + } + + if (Objects.equals(getClass(), other.getClass())) { + return false; + } + + NotificationEntity that = (NotificationEntity) other; + + if (Objects.equals(ownerId, that.ownerId)) { + return false; + } + if (read != that.read) { + return false; + } + if (Objects.equals(eventId, that.eventId)) { + return false; + } + if (Objects.equals(eventType, that.eventType)) { + return false; + } + if (Objects.equals(eventAttributes, that.eventAttributes)) { + return false; + } + if (Objects.equals(originatorId, that.originatorId)) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = ownerId != null ? ownerId.hashCode() : 0; + result = 31 * result + (eventId != null ? eventId.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "NotificationEntity {" + + "ownerId='" + ownerId + '\'' + + ", state='" + (read ? "Read" : "Noread") + '\'' + + ", originatorId='" + originatorId + '\'' + + ", eventId='" + eventId + '\'' + + ", eventType='" + eventType + '\'' + + ", eventAttributes='" + eventAttributes + '\'' + + '}'; + } +} 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 new file mode 100644 index 0000000000..d858cbd9eb --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/SubscribersEntity.java @@ -0,0 +1,68 @@ +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.Objects; +import java.util.Set; + +import static java.util.Objects.hash; + +@Table(keyspace = "dox", name = "notification_subscribers") +public class SubscribersEntity { + + @PartitionKey + @Column(name = "entity_id") + private String entityId; + + @Column(name = "subscribers") + private Set subscribers; + + + public SubscribersEntity() { + } + + public SubscribersEntity(String entityId, Set subscribers) { + this.entityId = entityId; + this.subscribers = subscribers; + } + + public String getEntityId() { + return entityId; + } + + public void setEntityId(String entityId) { + this.entityId = entityId; + } + + public Set getSubscribers() { + return subscribers; + } + + public void setSubscribers(Set subscribers) { + this.subscribers = subscribers; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SubscribersEntity that = (SubscribersEntity) o; + return Objects.equals(entityId, that.entityId) && + Objects.equals(subscribers, that.subscribers); + } + + @Override + public int hashCode() { + return hash(entityId, subscribers); + } + + @Override + public String toString() { + return "SubscribersEntity{" + + "entityId='" + entityId + '\'' + + ", subscribers=" + subscribers + + '}'; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/Event.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/Event.java new file mode 100644 index 0000000000..f7a181e5e6 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/Event.java @@ -0,0 +1,14 @@ +package org.openecomp.sdc.notification.dtos; + +import java.util.Map; + +public interface Event { + + String getEventType(); + + String getOriginatorId(); + + Map getAttributes(); + + String getEntityId(); +} 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 new file mode 100644 index 0000000000..1620569ec5 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/NotificationsStatus.java @@ -0,0 +1,24 @@ +package org.openecomp.sdc.notification.dtos; + +import org.openecomp.sdc.notification.dao.types.NotificationEntity; + +import java.util.List; +import java.util.UUID; + +/** + * @author Avrahamg + * @since June 26, 2017 + */ +public interface NotificationsStatus { + + List getNotifications(); + + List getNewEntries(); + + UUID getLastScanned(); + + 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 new file mode 100644 index 0000000000..90e53ea69a --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/exceptons/NotificationNotExistException.java @@ -0,0 +1,18 @@ +package org.openecomp.sdc.notification.exceptons; + +/** + * @author avrahamg + * @since July 02, 2017 + */ +public class NotificationNotExistException extends Exception { + private 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 new file mode 100644 index 0000000000..6e6f9f063a --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/LastNotificationDaoFactory.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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); + } + +} 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 new file mode 100644 index 0000000000..356055e26c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationPropagationManagerFactory.java @@ -0,0 +1,15 @@ +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.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 new file mode 100644 index 0000000000..341af7e296 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsDaoFactory.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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); + } + +} 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 new file mode 100644 index 0000000000..eab26188c1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsServiceFactory.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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); + } + +} 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 new file mode 100644 index 0000000000..e82783c40c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/PropagationServiceFactory.java @@ -0,0 +1,15 @@ +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.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 new file mode 100644 index 0000000000..33b62e2f5d --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscribersDaoFactory.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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 new file mode 100644 index 0000000000..3e789c22a7 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscriptionServiceFactory.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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 new file mode 100644 index 0000000000..7a1596eb95 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationPropagationManager.java @@ -0,0 +1,12 @@ +package org.openecomp.sdc.notification.services; + +import org.openecomp.sdc.notification.dtos.Event; + +/** + * @author avrahamg + * @since July 09, 2017 + */ +public interface NotificationPropagationManager { + 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 new file mode 100644 index 0000000000..17cfac1e5d --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationsService.java @@ -0,0 +1,31 @@ +package org.openecomp.sdc.notification.services; + +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); + + NotificationsStatus getNotificationsStatus(String ownerId, UUID lastDelivered, int numOfRecordsToReturn, UUID endOfPage); + + void updateLastSeenNotification(String ownerId, UUID eventId); + + 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/PropagationService.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/PropagationService.java new file mode 100644 index 0000000000..c084aa8015 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/PropagationService.java @@ -0,0 +1,9 @@ +package org.openecomp.sdc.notification.services; + +import org.openecomp.sdc.destinationprovider.DestinationProvider; +import org.openecomp.sdc.notification.dtos.Event; + +public interface PropagationService { + + void notify(Event event, DestinationProvider destinationProvider); +} 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 new file mode 100644 index 0000000000..98cd458ca2 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/SubscriptionService.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.notification.services; + +import java.util.Set; + +/** + * @author avrahamg + * @since July 09, 2017 + */ +public interface SubscriptionService { + void subscribe(String ownerId, String entityId); + + void unsubscribe(String ownerId, String entityId); + + Set getSubscribers(String entityId); +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/pom.xml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/pom.xml new file mode 100644 index 0000000000..4fe33ea1c3 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/pom.xml @@ -0,0 +1,42 @@ + + 4.0.0 + + openecomp-sdc-notification-core + openecomp-sdc-notification-core + + + + org.openecomp.sdc + openecomp-sdc-lib + 1.2.0-SNAPSHOT + ../.. + + + + org.openecomp.sdc + openecomp-sdc-notification-api + ${project.version} + + + org.mockito + mockito-all + test + 1.10.19 + + + junit + junit + test + ${junit.version} + + + org.powermock + powermock-module-junit4 + 1.6.5 + test + + + + 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 new file mode 100644 index 0000000000..431f9c18d6 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestination.java @@ -0,0 +1,44 @@ +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; + +/** + * @author avrahamg + * @since July 09, 2017 + */ +public class MulticastDestination implements DestinationProvider { + + private String entityId; + private SubscriptionService subscriptionService; + private String[] excludedSubscribers; + + public MulticastDestination(String entityId, SubscriptionService subscriptionService, + String... excludedSubscribers) { + this.entityId = entityId; + this.excludedSubscribers = excludedSubscribers; + this.subscriptionService = subscriptionService; + } + + public List getSubscribers() { + ArrayList subscribers = new ArrayList<>(subscriptionService.getSubscribers(entityId)); + if (ArrayUtils.isNotEmpty(excludedSubscribers)) { + subscribers.removeAll(Arrays.asList(excludedSubscribers)); + } + return Collections.unmodifiableList(subscribers); + } + + public String getEntityId() { + return entityId; + } + + public void setEntityId(String entityId) { + this.entityId = entityId; + } +} 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 new file mode 100644 index 0000000000..693c816d01 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/UnicastDestination.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.destinationprovider.impl; + +import org.openecomp.sdc.destinationprovider.DestinationProvider; + +import java.util.Collections; +import java.util.List; + +/** + * @author avrahamg + * @since July 09, 2017 + */ +public class UnicastDestination implements DestinationProvider { + + private String originatorId; + + public UnicastDestination(String originatorId) { + this.originatorId = originatorId; + } + + public List getSubscribers() { + return Collections.unmodifiableList(Collections.singletonList(originatorId)); + } +} 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 new file mode 100644 index 0000000000..0bfd6a314d --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/LastNotificationDaoCassandraImpl.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.dao.impl; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +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 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); + } + +} 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 new file mode 100644 index 0000000000..151c2c81d9 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/NotificationsDaoCassandraImpl.java @@ -0,0 +1,287 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.dao.impl; + +import com.datastax.driver.core.BatchStatement; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Statement; +import com.datastax.driver.core.utils.UUIDs; +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 org.apache.commons.collections.CollectionUtils; +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.NotificationsDao; +import org.openecomp.sdc.notification.dao.types.NotificationEntity; +import org.openecomp.sdc.notification.dtos.NotificationsStatus; + +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 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 { + + 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); + + @Override + protected Mapper getMapper() { + return mapper; + } + + @Override + protected Object[] getKeys(NotificationEntity entity) { + return new Object[]{entity.getOwnerId(), entity.getEventId()}; + } + + @Override + public List list(NotificationEntity entity) { + return accessor.list(entity.getOwnerId()).all(); + } + + @Override + public List getNotificationsByOwnerId(String ownerId, int limit) { + return accessor.getNotifications(ownerId, limit).all(); + } + + @Override + public List getNewNotificationsByOwnerId(String ownerId, UUID eventId) { + return getNewNotificationsByOwnerId(ownerId, eventId, + DEFAULT_LIMIT_OF_RESULTS_FOR_OWNER_NOTIFICATIONS); + } + + @Override + public List getNewNotificationsByOwnerId(String ownerId, UUID eventId, int limit) { + if (Objects.isNull(eventId)) { + return getNotificationsByOwnerId(ownerId, limit); + } + return accessor.getNewNotifications(ownerId, eventId, limit).all(); + } + + @Override + public void markNotificationAsRead(String ownerId, Collection eventIds) { + eventIds.forEach(eventId -> accessor.markAsRead(ownerId, eventId)); + } + + @Override + public NotificationsStatus getNotificationsStatus(String ownerId, UUID lastScannedEventId, int numOfRecordsToReturn) { + 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)); + } + return notificationsStatus; + } + + private void populateNewNotifications(NotificationsStatusImpl notificationsStatus, List entities, long lastSeen) { + for (NotificationEntity entity : entities) { + UUID eventId = entity.getEventId(); + notificationsStatus.addNotification(entity); + if (UUIDs.unixTimestamp(eventId) > lastSeen) { + notificationsStatus.addNewNotificationUUID(eventId); + } + } + } + + @Override + 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); + populateNewNotifications(notificationsStatus, entities, lastSeen); + } + 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()); + } + notificationsStatus.addNotification(notification); + }); + + Optional latestNotification = notificationEntities.stream().findFirst(); + latestNotification.ifPresent(e -> notificationsStatus.setLastScanned(e.getEventId())); + return notificationsStatus; + } + + 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()); + batch.addAll(statements); + getSession().execute(batch); + } + + @Accessor + interface NotificationsAccessor { + + @Query("select * from notifications where owner_id=?") + Result list(String ownerId); + + @Query("select * from notifications where owner_id=? limit ?") + Result getNotifications(String ownerId, int limit); + + @Query("select * from notifications where owner_id=? and event_id > ? limit ?") + Result getNewNotifications(String ownerId, UUID lastScannedEventId, int limit); + + @Query("select * from notifications where owner_id=? and event_id < ? limit ?") + Result getPrevNotifications(String ownerId, UUID prevLastScannedEventId, int limit); + + @Query("select count(*) from notifications where owner_id=? and event_id > ? and event_id <= ?") + ResultSet getNewNotificationsCount(String ownerId, UUID lastScannedEventId, UUID firstScannedEventId); + + @Query("update notifications set read=true where owner_id=? and event_id=?") + ResultSet markAsRead(String ownerId, UUID eventId); + } + + private class NotificationsStatusImpl implements NotificationsStatus { + + private List notifications = new ArrayList<>(); + private List newEntries = new ArrayList<>(); + private UUID lastScanned; + private UUID endOfPage; + private long numOfNotSeenNotifications = 0; + + void addNotification(NotificationEntity notification) { + notifications.add(notification); + endOfPage = notification.getEventId(); + } + + void addNewNotificationUUID(UUID notificationUuid) { + newEntries.add(notificationUuid); + } + + @Override + public List getNotifications() { + return Collections.unmodifiableList(notifications); + } + + @Override + public List getNewEntries() { + return Collections.unmodifiableList(newEntries); + } + + @Override + public UUID getLastScanned() { + return lastScanned; + } + + void setLastScanned(UUID lastScanned) { + this.lastScanned = lastScanned; + } + + @Override + public UUID getEndOfPage() { + return endOfPage; + } + + @Override + public long getNumOfNotSeenNotifications() { + return numOfNotSeenNotifications; + } + + void setNumOfNotSeenNotifications(long numOfNotSeenNotifications) { + this.numOfNotSeenNotifications = numOfNotSeenNotifications; + } + } + +/* + private List fetchMoreIfNeeded(String ownerId, + List notificationEntities, + int numOfRecordsToReturn, UUID lastEventId) { + + if (numOfRecordsToReturn <= notificationEntities.size() || Objects.isNull(lastEventId)) { + return notificationEntities; + } + + int multiplier = 2; + while (numOfRecordsToReturn > notificationEntities.size()) { + + int bring = notificationEntities.size() + + (numOfRecordsToReturn - notificationEntities.size()) * multiplier; + notificationEntities = getNotificationsByOwnerId(ownerId, bring); + + if (notificationEntities.size() < bring) { + return notificationEntities; + } + multiplier++; + } + return notificationEntities; + } +*/ + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/SubscribersDaoCassandraImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/SubscribersDaoCassandraImpl.java new file mode 100644 index 0000000000..8e8cf9b181 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/SubscribersDaoCassandraImpl.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.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 com.google.common.collect.Sets; +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.SubscribersDao; +import org.openecomp.sdc.notification.dao.types.SubscribersEntity; + +import java.util.Collection; +import java.util.Collections; +import java.util.Objects; +import java.util.Set; + +import static java.util.Objects.isNull; + +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); + + + @Override + protected Object[] getKeys(SubscribersEntity entity) { + return new Object[]{entity.getEntityId()}; + } + + @Override + protected Mapper getMapper() { + return mapper; + } + + @Override + public void subscribe(String ownerId, String entityId) { + Objects.requireNonNull(ownerId); + Objects.requireNonNull(entityId); + accessor.subscribe(Sets.newHashSet(ownerId), entityId); + } + + @Override + @Deprecated + public Collection list(SubscribersEntity entity) { + throw new UnsupportedOperationException(); + } + + @Override + public void unsubscribe(String ownerId, String entityId) { + Objects.requireNonNull(ownerId); + Objects.requireNonNull(entityId); + accessor.unsubscribe(Sets.newHashSet(ownerId), entityId); + } + + @Override + public Set getSubscribers(String entityId) { + Objects.requireNonNull(entityId); + SubscribersEntity subscribersEntity = accessor.getSubscribers(entityId).one(); + if (isNull(subscribersEntity)) { + return Collections.emptySet(); + } + return subscribersEntity.getSubscribers(); + } + + @Accessor + interface SubscribersAccessor { + + @Query("select * from notification_subscribers where entity_id=?") + Result getSubscribers(String entityId); + + @Query("update notification_subscribers set subscribers=subscribers+? WHERE entity_id=?") + void subscribe(Set ownerId, String entityId); + + @Query("update notification_subscribers set subscribers=subscribers-? WHERE entity_id=?") + void unsubscribe(Set 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 new file mode 100644 index 0000000000..7ac9e00967 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/LastNotificationDaoFactoryImpl.java @@ -0,0 +1,19 @@ +package org.openecomp.sdc.notification.factories.impl; + +import org.openecomp.sdc.notification.dao.LastNotificationDao; +import org.openecomp.sdc.notification.dao.impl.LastNotificationDaoCassandraImpl; +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; + } +} 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 new file mode 100644 index 0000000000..7b9e51e8c9 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationPropagationManagerFactoryImpl.java @@ -0,0 +1,19 @@ +package org.openecomp.sdc.notification.factories.impl; + +import org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory; +import org.openecomp.sdc.notification.factories.PropagationServiceFactory; +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 { + private static final NotificationPropagationManager INSTANCE = new NotificationPropagationManagerImpl( + PropagationServiceFactory.getInstance().createInterface(), SubscriptionServiceFactory + .getInstance().createInterface()); + + @Override + public NotificationPropagationManager 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/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 new file mode 100644 index 0000000000..edb020637b --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsDaoFactoryImpl.java @@ -0,0 +1,18 @@ +package org.openecomp.sdc.notification.factories.impl; + +import org.openecomp.sdc.notification.dao.NotificationsDao; +import org.openecomp.sdc.notification.dao.impl.NotificationsDaoCassandraImpl; +import org.openecomp.sdc.notification.factories.NotificationsDaoFactory; + +/** + * @author Avrahamg + * @since June 20, 2017 + */ +public class NotificationsDaoFactoryImpl extends NotificationsDaoFactory { + 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 new file mode 100644 index 0000000000..ac265e3c8c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsServiceFactoryImpl.java @@ -0,0 +1,22 @@ +package org.openecomp.sdc.notification.factories.impl; + +import org.openecomp.sdc.notification.factories.LastNotificationDaoFactory; +import org.openecomp.sdc.notification.factories.NotificationsDaoFactory; +import org.openecomp.sdc.notification.factories.NotificationsServiceFactory; +import org.openecomp.sdc.notification.services.NotificationsService; +import org.openecomp.sdc.notification.services.impl.NotificationsServiceImpl; + +/** + * @author Avrahamg + * @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; + } +} 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 new file mode 100644 index 0000000000..e5987fe266 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/PropagationServiceFactoryImpl.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.notification.factories.impl; + +import org.openecomp.sdc.notification.factories.NotificationsDaoFactory; +import org.openecomp.sdc.notification.factories.PropagationServiceFactory; +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()); + + @Override + public PropagationService 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/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 new file mode 100644 index 0000000000..fb87b944f9 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscribersDaoFactoryImpl.java @@ -0,0 +1,15 @@ +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 + public SubscribersDao 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/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 new file mode 100644 index 0000000000..604cff0b5e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscriptionServiceFactoryImpl.java @@ -0,0 +1,17 @@ +package org.openecomp.sdc.notification.factories.impl; + +import org.openecomp.sdc.notification.factories.SubscribersDaoFactory; +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()); + + @Override + public SubscriptionService createInterface() { + return INSTANCE; + } +} \ 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/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 new file mode 100644 index 0000000000..d381268b3f --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImpl.java @@ -0,0 +1,35 @@ +package org.openecomp.sdc.notification.services.impl; + +import org.openecomp.sdc.destinationprovider.impl.MulticastDestination; +import org.openecomp.sdc.destinationprovider.impl.UnicastDestination; +import org.openecomp.sdc.notification.dtos.Event; +import org.openecomp.sdc.notification.services.NotificationPropagationManager; +import org.openecomp.sdc.notification.services.PropagationService; +import org.openecomp.sdc.notification.services.SubscriptionService; + +/** + * @author avrahamg + * @since July 10, 2017 + */ +public class NotificationPropagationManagerImpl implements NotificationPropagationManager { + + private PropagationService propagationService; + private 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)); + } + + @Override + public void directNotification(Event event, String destinationId) { + propagationService.notify(event, new UnicastDestination(destinationId)); + } +} 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 new file mode 100644 index 0000000000..8a7ab8bdae --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImpl.java @@ -0,0 +1,92 @@ +package org.openecomp.sdc.notification.services.impl; + +import org.openecomp.sdc.notification.dao.LastNotificationDao; +import org.openecomp.sdc.notification.dao.NotificationsDao; +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 org.openecomp.sdc.notification.services.NotificationsService; + +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +/** + * @author Avrahamg + * @since June 26, 2017 + */ +public class NotificationsServiceImpl implements NotificationsService { + + private LastNotificationDao lastNotificationDao; + private 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)); + } + + @Override + 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 + 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))); + if (Objects.isNull(notificationEntity)) { + throw new NotificationNotExistException( + "Notification '" + notificationId + "' is not related to ownerId" + + " '" + ownerId + "'"); + } + notificationEntity.setRead(true); + notificationsDao.update(notificationEntity); + } + + @Override + public List getNotificationsByOwnerId(String ownerId, int limit) { + return notificationsDao.getNotificationsByOwnerId(ownerId, limit); + } + + @Override + public List getNewNotificationsByOwnerId(String ownerId, UUID eventId) { + return notificationsDao.getNewNotificationsByOwnerId(ownerId, eventId); + } + + @Override + public List getNewNotificationsByOwnerId(String ownerId, UUID eventId, int 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 new file mode 100644 index 0000000000..99d35b3726 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImpl.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.services.impl; + +import com.datastax.driver.core.utils.UUIDs; +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.core.utilities.json.JsonUtil; +import org.openecomp.sdc.destinationprovider.DestinationProvider; +import org.openecomp.sdc.notification.dao.NotificationsDao; +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; + + public PropagationServiceImpl(NotificationsDao notificationsDao) { + this.notificationsDao = notificationsDao; + } + + + @Override + public void notify(Event event, DestinationProvider destinationProvider) { + requireNonNull(event.getEventType()); + requireNonNull(event.getOriginatorId()); + List subscribers = destinationProvider.getSubscribers(); + 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)) { + notificationsDao.createBatch(notificationEntities); + } + } + + private NotificationEntity createNotificationEntity(String eventType, String subscriber, + String originatorId, + Map attributes, + UUID eventId) { + 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 new file mode 100644 index 0000000000..2a12463fae --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/SubscriptionServiceImpl.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.services.impl; + +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; + + public SubscriptionServiceImpl(SubscribersDao subscribersDao) { + this.subscribersDao = subscribersDao; + } + + @Override + public void subscribe(String ownerId, String entityId) { + subscribersDao.subscribe(ownerId, entityId); + } + + @Override + public void unsubscribe(String ownerId, String entityId) { + subscribersDao.unsubscribe(ownerId, entityId); + } + + @Override + 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-core/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..3f1bdf3656 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/resources/factoryConfiguration.json @@ -0,0 +1,9 @@ +{ + "org.openecomp.sdc.notification.factories.LastNotificationDaoFactory": "org.openecomp.sdc.notification.factories.impl.LastNotificationDaoFactoryImpl", + "org.openecomp.sdc.notification.factories.NotificationsDaoFactory": "org.openecomp.sdc.notification.factories.impl.NotificationsDaoFactoryImpl", + "org.openecomp.sdc.notification.factories.NotificationsServiceFactory": "org.openecomp.sdc.notification.factories.impl.NotificationsServiceFactoryImpl", + "org.openecomp.sdc.notification.factories.SubscribersDaoFactory": "org.openecomp.sdc.notification.factories.impl.SubscribersDaoFactoryImpl", + "org.openecomp.sdc.notification.factories.PropagationServiceFactory": "org.openecomp.sdc.notification.factories.impl.PropagationServiceFactoryImpl", + "org.openecomp.sdc.notification.factories.SubscriptionServiceFactory": "org.openecomp.sdc.notification.factories.impl.SubscriptionServiceFactoryImpl", + "org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory": "org.openecomp.sdc.notification.factories.impl.NotificationPropagationManagerFactoryImpl" +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestinationTest.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestinationTest.java new file mode 100644 index 0000000000..a0dd00632e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestinationTest.java @@ -0,0 +1,67 @@ +package org.openecomp.sdc.destinationprovider.impl; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.notification.services.SubscriptionService; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; + +/** + * @author avrahamg + * @since July 13, 2017 + */ +public class MulticastDestinationTest { + @Mock + private SubscriptionService subscriptionServiceMock; + + private final String excludedSubscriber = "excluded"; + private Set subscribers = new HashSet<>(Arrays.asList("a", "b", excludedSubscriber)); + private MulticastDestination multicastDestination; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void shouldReturnAllSubscribersIfNoExcludedProvided() throws Exception { + doReturn(subscribers).when(subscriptionServiceMock).getSubscribers(any()); + multicastDestination = new MulticastDestination("aa", subscriptionServiceMock); + assertEquals(subscribers.size(), multicastDestination.getSubscribers().size()); + List actualSubscribers = multicastDestination.getSubscribers(); + assertTrue(actualSubscribers.containsAll(subscribers)); + } + + @Test + public void shouldReturnAllSubscribersExceptExcluded() throws Exception { + doReturn(subscribers).when(subscriptionServiceMock).getSubscribers(any()); + multicastDestination = + new MulticastDestination("aa", subscriptionServiceMock, excludedSubscriber); + List actualSubscribers = multicastDestination.getSubscribers(); + assertNotEquals(this.subscribers.size(), actualSubscribers.size()); + assertFalse(actualSubscribers.containsAll(subscribers)); + assertFalse(actualSubscribers.contains(excludedSubscriber)); + } + + @Test(expected = UnsupportedOperationException.class) + public void shouldThrowUnsupportedOperationExceptionWhenTryingToChangeSubscribersList() throws + Exception { + doReturn(subscribers).when(subscriptionServiceMock).getSubscribers(any()); + multicastDestination = + new MulticastDestination("aa", subscriptionServiceMock, excludedSubscriber); + List actualSubscribers = multicastDestination.getSubscribers(); + actualSubscribers.add("sss"); + } +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImplTest.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImplTest.java new file mode 100644 index 0000000000..0eb2b6235c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImplTest.java @@ -0,0 +1,64 @@ +package org.openecomp.sdc.notification.services.impl; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.sdc.destinationprovider.DestinationProvider; +import org.openecomp.sdc.destinationprovider.impl.MulticastDestination; +import org.openecomp.sdc.destinationprovider.impl.UnicastDestination; +import org.openecomp.sdc.notification.dtos.Event; +import org.openecomp.sdc.notification.services.PropagationService; +import org.openecomp.sdc.notification.services.SubscriptionService; + +import static org.mockito.Mockito.verify; + + +/** + * @author avrahamg + * @since July 13, 2017 + */ +public class NotificationPropagationManagerImplTest { + @Mock + private PropagationService propagationServiceMock; + @Mock + private SubscriptionService subscriptionServiceMock; + @Mock + private Event eventMock; + @Captor + private ArgumentCaptor destinationProviderCaptor; + + @Spy + @InjectMocks + private NotificationPropagationManagerImpl notificationPropagationManager; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void shouldCallPropagationServiceNotifyWithMulticastDestinationWhenNotifySubscribers() + throws Exception { + notificationPropagationManager.notifySubscribers(eventMock); + verify(propagationServiceMock).notify(Matchers.eq(eventMock), destinationProviderCaptor + .capture()); + Assert.assertTrue(destinationProviderCaptor.getValue() instanceof MulticastDestination); + + } + + @Test + public void shouldCallPropagationServiceNotifyWithUnicastDestinationWhenDirectNotification() + throws Exception { + notificationPropagationManager.directNotification(eventMock, "aaa"); + verify(propagationServiceMock).notify(Matchers.eq(eventMock), destinationProviderCaptor + .capture()); + Assert.assertTrue(destinationProviderCaptor.getValue() instanceof UnicastDestination); + } +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImplTest.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImplTest.java new file mode 100644 index 0000000000..a20d0cce45 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImplTest.java @@ -0,0 +1,50 @@ +package org.openecomp.sdc.notification.services.impl; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.sdc.notification.dao.LastNotificationDao; +import org.openecomp.sdc.notification.dao.NotificationsDao; +import org.openecomp.sdc.notification.dao.types.NotificationEntity; +import org.openecomp.sdc.notification.exceptons.NotificationNotExistException; + +import java.util.UUID; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +/** + * @author avrahamg + * @since July 13, 2017 + */ +public class NotificationsServiceImplTest { + @Mock + private LastNotificationDao lastNotificationDao; + @Mock + private NotificationsDao notificationsDao; + @Spy + @InjectMocks + private NotificationsServiceImpl notificationsService; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + public void shouldCallNotificationsDaoIfNotificationEntityExist() throws Exception { + doReturn(new NotificationEntity()).when(notificationsDao).get(any()); + notificationsService.markAsRead("ownerId", UUID.randomUUID().toString()); + verify(notificationsDao, times(1)).update(any()); + } + + @Test(expected = NotificationNotExistException.class) + public void shouldThrowExceptionIfOwnerIdAndNotificationIdDontRelate() throws Exception { + doReturn(null).when(notificationsDao).get(any()); + notificationsService.markAsRead("ownerId", UUID.randomUUID().toString()); + } +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImplTest.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImplTest.java new file mode 100644 index 0000000000..866dec0d6d --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImplTest.java @@ -0,0 +1,96 @@ +package org.openecomp.sdc.notification.services.impl; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.sdc.destinationprovider.DestinationProvider; +import org.openecomp.sdc.notification.dao.NotificationsDao; +import org.openecomp.sdc.notification.dtos.Event; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import static org.mockito.Matchers.anyList; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +/** + * @author avrahamg + * @since July 13, 2017 + */ +public class PropagationServiceImplTest { + @Mock + private NotificationsDao notificationsDaoMock; + @Mock + private Event eventMock; + @Mock + private DestinationProvider destinationProviderMock; + @Captor + private ArgumentCaptor createBatchCaptor; + + @Rule + public ExpectedException thrown= ExpectedException.none(); + + @InjectMocks + @Spy + private PropagationServiceImpl propagationService; + private List subscribersList = Arrays.asList("A1, A2, A3");; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + initEventMock(); + } + + @Test + public void shouldCallToNotificationsDaoWithCreateBatchWithNotificationEntitiesAsNumberOfSubscribers() + throws Exception { + doReturn(subscribersList).when(destinationProviderMock).getSubscribers(); + propagationService.notify(eventMock, destinationProviderMock); + verify(notificationsDaoMock).createBatch(createBatchCaptor.capture()); + Assert.assertEquals(createBatchCaptor.getValue().size(), subscribersList.size()); + } + + @Test + public void shouldNotCallNotificationDaoIfSubscriberIsNull() throws Exception { + doReturn(Collections.EMPTY_LIST).when(destinationProviderMock).getSubscribers(); + verify(notificationsDaoMock,never()).createBatch(anyList()); + } + + @Test + public void shouldThrowExceptionIfEventTypeIsNull() throws Exception { + doReturn(null).when(eventMock).getEventType(); + callToNotify(); + } + + @Test + public void shouldThrowExceptionIfOriginatorIdIsNull() throws Exception { + doReturn(null).when(eventMock).getOriginatorId(); + callToNotify(); + } + + private void callToNotify() { + thrown.expect(NullPointerException.class); + propagationService.notify(eventMock, destinationProviderMock); + } + + private void initEventMock() { + doReturn("eventType").when(eventMock).getEventType(); + doReturn("originator").when(eventMock).getOriginatorId(); + doReturn("entity").when(eventMock).getEntityId(); + doReturn(new HashMap<>()).when(eventMock).getAttributes(); + } + + +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/pom.xml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/pom.xml new file mode 100644 index 0000000000..abff87f1ad --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/pom.xml @@ -0,0 +1,34 @@ + + 4.0.0 + + openecomp-sdc-notification-websocket + openecomp-sdc-notification-websocket + + + org.openecomp.sdc + openecomp-sdc-lib + 1.2.0-SNAPSHOT + ../.. + + + + + org.openecomp.sdc + openecomp-sdc-notification-worker + ${project.version} + + + org.springframework + spring-websocket + 4.3.4.RELEASE + + + com.google.code.gson + gson + 2.3.1 + + + + 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 new file mode 100644 index 0000000000..1e424631f7 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/src/main/java/org/openecomp/sdc/notification/websocket/NotificationWebsocketHandler.java @@ -0,0 +1,130 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.websocket; + +import com.google.gson.Gson; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.notification.types.NotificationsStatusDto; +import org.openecomp.sdc.notification.workers.NotificationWorker; +import org.springframework.http.HttpHeaders; +import org.springframework.web.socket.CloseStatus; +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; + + public NotificationWebsocketHandler(NotificationWorker worker) { + super(); + this.worker = Objects.requireNonNull(worker, "NotificationWorker object is not initialized."); + } + + @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); + } + + @Override + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { + 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 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; + } + + 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) { + + String[] value = nameValuePair.split("="); + if (value[0].equals(name)) { + return Optional.of(value[1]); + } + } + + return Optional.empty(); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/pom.xml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/pom.xml new file mode 100644 index 0000000000..fb55d28017 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/pom.xml @@ -0,0 +1,73 @@ + + 4.0.0 + + openecomp-sdc-notification-worker + openecomp-sdc-notification-worker + + + org.openecomp.sdc + openecomp-sdc-lib + 1.2.0-SNAPSHOT + ../.. + + + + + org.openecomp.sdc.core + openecomp-utilities-lib + ${project.version} + + + org.codehaus.jackson + jackson-jaxrs + ${org.codehaus.jackson.version} + + + org.codehaus.jackson + jackson-core-asl + ${org.codehaus.jackson.version} + + + org.springframework + spring-websocket + 4.3.4.RELEASE + + + com.google.code.gson + gson + 2.3.1 + + + com.googlecode.json-simple + json-simple + 1.1 + + + org.apache.httpcomponents + httpclient + 4.4.1 + provided + + + org.apache.httpcomponents + httpcore + 4.4.1 + provided + + + com.datastax.cassandra + cassandra-driver-core + 2.0.1 + test + + + junit + junit + test + ${junit.version} + + + + 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 new file mode 100644 index 0000000000..d960b8b9dc --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/config/ConfigurationManager.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.config; + +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.tosca.services.YamlUtil; + +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; + +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 ConfigurationManager() { + initConfiguration(); + } + + 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"); + } + }); + } + + 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)) { + 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); + 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 new file mode 100644 index 0000000000..a415d9e081 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationEntityDto.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.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; + } + + @Override + public String toString() { + return "NotificationEntityDto {" + + ", state='" + (read ? "Read" : "Noread") + '\'' + + ", dateTime='" + dateTime + '\'' + + ", eventId='" + eventId + '\'' + + ", eventType='" + eventType + '\'' + + ", eventAttributes='" + eventAttributes + '\'' + + '}'; + } + +} 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 new file mode 100644 index 0000000000..fd8d32090e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationsStatusDto.java @@ -0,0 +1,72 @@ +package org.openecomp.sdc.notification.types; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * @author avrahamg + * @since June 29, 2017 + */ +public class NotificationsStatusDto { + private List notifications; + private List newEntries = new ArrayList<>(); + private UUID lastScanned; + private UUID endOfPage; + private long numOfNotSeenNotifications; + + public NotificationsStatusDto() { + } + + public List getNotifications() { + return notifications; + } + + public void setNotifications( + List notifications) { + this.notifications = notifications; + } + + public List getNewEntries() { + return newEntries; + } + + public void setNewEntries(List newEntries) { + this.newEntries = newEntries; + } + + public UUID getLastScanned() { + return lastScanned; + } + + public void setLastScanned(UUID lastScanned) { + this.lastScanned = lastScanned; + } + + public UUID getEndOfPage() { + return endOfPage; + } + + public void setEndOfPage(UUID endOfPage) { + this.endOfPage = endOfPage; + } + + public long getNumOfNotSeenNotifications() { + return numOfNotSeenNotifications; + } + + public void setNumOfNotSeenNotifications(long numOfNotSeenNotifications) { + this.numOfNotSeenNotifications = numOfNotSeenNotifications; + } + + @Override + public String toString() { + return "NotificationsStatusDto{" + + "notifications=" + notifications + + ", newEntries=" + newEntries + + ", lastScanned=" + lastScanned + + ", endOfPage=" + endOfPage + + ", numOfNotSeenNotifications=" + numOfNotSeenNotifications + + '}'; + } +} 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 new file mode 100644 index 0000000000..75b9f5c786 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NewNotificationsReader.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.workers; + +import org.openecomp.sdc.notification.types.NotificationsStatusDto; + +import java.util.UUID; + +public interface NewNotificationsReader { + 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 new file mode 100644 index 0000000000..ee802640c4 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationReceiver.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.workers; + +import org.openecomp.sdc.notification.types.NotificationsStatusDto; + +import java.util.UUID; +import java.util.function.Consumer; + + + +public class NotificationReceiver { + + public String ownerId = null; + public Consumer notesProcessor = null; + public UUID lastEventId = null; + + NotificationReceiver(String ownerId, UUID lastEventId, Consumer notesProcessor) { + this.ownerId = ownerId; + this.lastEventId = lastEventId; + this.notesProcessor = notesProcessor; + } + + NotificationReceiver(String ownerId, Consumer notesProcessor) { + this(ownerId, null, notesProcessor); + } + + public void setOwnerId(String ownerId) { + this.ownerId = ownerId; + } + + public String getOwnerId() { + return this.ownerId; + } + + public void setNotesProcessor(Consumer notesProcessor) { + this.notesProcessor = notesProcessor; + } + + public Consumer getNotesProcessor() { + return this.notesProcessor; + } + + public void setLastEventId(UUID lastEventId) { + this.lastEventId = lastEventId; + } + + public UUID getlastEventId() { + return this.lastEventId; + } +} 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 new file mode 100644 index 0000000000..e8c2006d5c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationWorker.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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; + +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 { + public void run() { + try { + while (!stopRunning) { + pollNotifications(); + Thread.sleep(pollingSleepInterval); + } + } + catch (InterruptedException e) { + LOGGER.error("Interrupted Exception during Notification poller launch.", e); + } + } + + 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; + } + +} 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 new file mode 100644 index 0000000000..a332efaf5a --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/impl/NewNotificationsReaderRestImpl.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.workers.impl; + +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 org.codehaus.jackson.map.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"; + private static final String LAST_DELIVERED_QUERY_PARAM = "LAST_DELIVERED_EVENT_ID"; + private static final String LIMIT_QUERY_PARAM = "NOTIFICATION_ROWS_LIMIT"; + private static final String BE_HOST = "beHost"; + private static final String BE_PORT = "beHttpPort"; + private static final String DEFAULT_BE_HOST = "localhost"; + 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 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); + beHost = cm.getConfigValue(BE_HOST, DEFAULT_BE_HOST); + } + + 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); + } catch (Exception e) { + LOGGER.error("Failed to execute the request {}", url, e); + return null; + } + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..5f5693fb92 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/factoryConfiguration.json @@ -0,0 +1,3 @@ +{ + "org.openecomp.config.api.ConfigurationManager": "org.openecomp.config.impl.ConfigurationImpl" +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/onboarding_configuration.yaml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/onboarding_configuration.yaml new file mode 100644 index 0000000000..a1b7ba5d9e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/onboarding_configuration.yaml @@ -0,0 +1,5 @@ +notifications: + pollingIntervalMsec: 2000 + selectionSize: 10 + beHost: localhost + beHttpPort: 8080 diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/java/org/openecomp/sdc/notification/workers/NotificationWorkerTest.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/java/org/openecomp/sdc/notification/workers/NotificationWorkerTest.java new file mode 100644 index 0000000000..457ba071cd --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/java/org/openecomp/sdc/notification/workers/NotificationWorkerTest.java @@ -0,0 +1,134 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.workers; + +import com.datastax.driver.core.utils.UUIDs; +import org.junit.BeforeClass; +import org.junit.Test; +import org.openecomp.core.utilities.json.JsonUtil; +import org.openecomp.sdc.notification.types.NotificationEntityDto; +import org.openecomp.sdc.notification.types.NotificationsStatusDto; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.text.DateFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +//import org.junit.Before; + + +public class NotificationWorkerTest { + + private static final String OWNER = "owner_1"; + + private String fileName = null; + private NewNotificationsReader news = this.new SimNewNotificationsReader(); + private NotificationWorker worker = new NotificationWorker(news); + + @BeforeClass + public static void beforeClass() throws Exception { + } + + @Test + public void testBasicResourceCreation() throws IOException, InterruptedException { + + Consumer notesProcessor = this::notifyReceiver; + + fileName = "notification_1.csv"; + + worker.register(OWNER, null, notesProcessor); + worker.register("owner_2", null, notesProcessor); + worker.register("owner_3", null, notesProcessor); + + int pollInterval = 2000; + Thread.sleep(pollInterval); + + worker.unregister("owner_2"); + + fileName = "notification_2.csv"; + + Thread.sleep(pollInterval); + + worker.stopPolling(); + + } + + private void notifyReceiver(NotificationsStatusDto notes) { + if (Objects.nonNull(notes)) { + System.out.println("Received notes:"); + System.out.println(notes); + } + } + + + private class SimNewNotificationsReader implements NewNotificationsReader { + + + private String resourcesDir = "src/test/resources/"; + + public NotificationsStatusDto getNewNotifications(String ownerId, UUID eventId, int limit) { + if (fileName == null) { + return null; + } + String fn = fileName; + fileName = null; + + return getNotifications(fn); + } + + private NotificationsStatusDto getNotifications(String fn) { + NotificationsStatusDto notificationsStatusDto = new NotificationsStatusDto(); + List inputList = new ArrayList<>(); + try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(resourcesDir + fn))))) { + int limit = 10; + inputList = br.lines().skip(1).limit(limit).map(mapToEntity).collect(Collectors.toCollection(ArrayList::new)); + } catch (IOException e) { + System.err.println("getNotifications(): file " + resourcesDir + fn + " open exception: " + e.getMessage()); + } + notificationsStatusDto.setNotifications(inputList); + notificationsStatusDto.setLastScanned(inputList.get(0).getEventId()); + return notificationsStatusDto; + } + + private Function mapToEntity = (line) -> { + String[] p = line.split("\\|"); + NotificationEntityDto entity = new NotificationEntityDto(); + DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT); + entity.setRead(Boolean.parseBoolean(p[1])); + entity.setEventId(UUID.fromString(p[2])); + entity.setEventType(p[4]); + entity.setDateTime(formatter.format(UUIDs.unixTimestamp(entity.getEventId()))); + entity.setEventAttributes(JsonUtil.json2Object(p[5], Map.class)); + return entity; + }; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/logback.xml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/logback.xml new file mode 100644 index 0000000000..c1932e31e8 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/logback.xml @@ -0,0 +1,15 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_1.csv b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_1.csv new file mode 100644 index 0000000000..8b7de38ce5 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_1.csv @@ -0,0 +1,11 @@ +# Owner|Read|EventId|EventType|OriginatorId|EventAttributes +owner_1|false|1dc38a90-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc387d4-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38702-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc385fe-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc384a0-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc383c4-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc3818a-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc380b8-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc37fdc-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc37ee2-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_2.csv b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_2.csv new file mode 100644 index 0000000000..565e80bce8 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_2.csv @@ -0,0 +1,11 @@ +# Owner|Read|EventId|EventType|OriginatorId|EventAttributes +owner_1|false|1dc39346-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc39288-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc391c0-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38f2c-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38e64-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38da6-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38ce8-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38c2a-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38b62-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc37c08-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/onboarding_configuration.yaml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/onboarding_configuration.yaml new file mode 100644 index 0000000000..cc04531c7c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/onboarding_configuration.yaml @@ -0,0 +1,5 @@ +notifications: + pollingIntervalMsec: 3000 + selectionSize: 5 + beHost: localhost + beHttpPort: 8080 diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/pom.xml b/openecomp-be/lib/openecomp-sdc-notification-lib/pom.xml new file mode 100644 index 0000000000..9dc0dcfd3e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/pom.xml @@ -0,0 +1,23 @@ + + 4.0.0 + + openecomp-sdc-notification-lib + openecomp-sdc-notification-lib + + pom + + openecomp-sdc-lib + org.openecomp.sdc + 1.2.0-SNAPSHOT + .. + + + + openecomp-sdc-notification-api + openecomp-sdc-notification-core + openecomp-sdc-notification-worker + openecomp-sdc-notification-websocket + + + 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 6ec7bfca9f..8234179017 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 @@ -1,21 +1,5 @@ package org.openecomp.sdc.generator.core.services; -import static org.openecomp.sdc.generator.util.GeneratorConstants.ALLOWED_FLAVORS_PROPERTY; -import static org.openecomp.sdc.generator.util.GeneratorConstants.DISK_SIZE; -import static org.openecomp.sdc.generator.util.GeneratorConstants.DISK_SIZE_PROP_DESC_PREFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.IMAGES_PROPERTY; -import static org.openecomp.sdc.generator.util.GeneratorConstants.MEM_SIZE; -import static org.openecomp.sdc.generator.util.GeneratorConstants.MEM_SIZE_PROP_DESC_PREFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.NUM_CPUS; -import static org.openecomp.sdc.generator.util.GeneratorConstants.NUM_CPUS_PROP_DESC_PREFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.PORT_NODE_TEMPLATE_ID_SUFFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.PORT_TYPE_EXTERNAL_NODE_TEMPLATE_SUFFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.PORT_TYPE_INTERNAL_NODE_TEMPLATE_SUFFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.RELEASE_VENDOR; -import static org.openecomp.sdc.generator.util.GeneratorConstants.TOSCA_SERVICE_TEMPLATE_FILE_NAME_SUFFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.VNF_CONFIG_NODE_TEMPLATE_ID_SUFFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.VNF_NODE_TEMPLATE_ID_SUFFIX; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.sdc.generator.core.utils.GeneratorUtils; @@ -48,6 +32,22 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import static org.openecomp.sdc.generator.util.GeneratorConstants.ALLOWED_FLAVORS_PROPERTY; +import static org.openecomp.sdc.generator.util.GeneratorConstants.DISK_SIZE; +import static org.openecomp.sdc.generator.util.GeneratorConstants.DISK_SIZE_PROP_DESC_PREFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.IMAGES_PROPERTY; +import static org.openecomp.sdc.generator.util.GeneratorConstants.MEM_SIZE; +import static org.openecomp.sdc.generator.util.GeneratorConstants.MEM_SIZE_PROP_DESC_PREFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.NUM_CPUS; +import static org.openecomp.sdc.generator.util.GeneratorConstants.NUM_CPUS_PROP_DESC_PREFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.PORT_NODE_TEMPLATE_ID_SUFFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.PORT_TYPE_EXTERNAL_NODE_TEMPLATE_SUFFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.PORT_TYPE_INTERNAL_NODE_TEMPLATE_SUFFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.RELEASE_VENDOR; +import static org.openecomp.sdc.generator.util.GeneratorConstants.TOSCA_SERVICE_TEMPLATE_FILE_NAME_SUFFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.VNF_CONFIG_NODE_TEMPLATE_ID_SUFFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.VNF_NODE_TEMPLATE_ID_SUFFIX; + /** * The type Manual vsp tosca generator. */ @@ -329,7 +329,6 @@ public class ManualVspToscaGenerationService { ToscaServiceModel toscaServiceModel, String substitutionNodeTypeId, String componentName) { - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); ServiceTemplate globalSubstitutionServiceTemplate = fetchGlobalSubstitutionServiceTemplate(); NodeType substitutionNodeType = createGlobalSubstitutionNodeType(substitutionServiceTemplate, componentName); 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 7e493f2151..129929ae30 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 @@ -1,7 +1,5 @@ package org.openecomp.sdc.generator.core.utils; -import static org.openecomp.sdc.tosca.services.DataModelUtil.addSubstitutionNodeTypeRequirements; - import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; @@ -29,6 +27,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import static org.openecomp.sdc.tosca.services.DataModelUtil.addSubstitutionNodeTypeRequirements; + /** * The type Generator utils. */ 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 3686a516b3..87c578cd5d 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 @@ -20,7 +20,6 @@ package org.openecomp.sdc.translator.datatypes.heattotosca; -import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.openecomp.config.api.Configuration; import org.openecomp.config.api.ConfigurationManager; 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 d3f2a721c9..628186e9d7 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 @@ -3,7 +3,6 @@ package org.openecomp.sdc.translator.services.heattotosca; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; 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 895b3f9670..9d875d20f4 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 @@ -27,10 +27,9 @@ import org.openecomp.core.translator.datatypes.TranslatorOutput; import org.openecomp.core.translator.factory.HeatToToscaTranslatorFactory; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.sdc.common.togglz.ToggleableFeature; -import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.core.validation.util.MessageContainerUtil; import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.togglz.ToggleableFeature; import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; @@ -73,9 +72,10 @@ import org.openecomp.sdc.tosca.datatypes.model.TopologyTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; import org.openecomp.sdc.tosca.services.ToscaUtil; +import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; -import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedPropertyVal; import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; import org.openecomp.sdc.translator.datatypes.heattotosca.ReferenceType; 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 244434c1b8..bd0fbcb47a 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 @@ -20,12 +20,6 @@ package org.openecomp.sdc.translator.services.heattotosca; -import static org.openecomp.sdc.tosca.services.DataModelUtil.getClonedObject; -import static org.openecomp.sdc.translator.services.heattotosca.Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX; -import static org.openecomp.sdc.translator.services.heattotosca.Constants.COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX; -import static org.openecomp.sdc.translator.services.heattotosca.Constants.COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX; -import static org.openecomp.sdc.translator.services.heattotosca.Constants.PORT_IDENTICAL_VALUE_PROPERTY_PREFIX; - import org.apache.commons.collections.map.HashedMap; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; @@ -94,6 +88,12 @@ import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; +import static org.openecomp.sdc.tosca.services.DataModelUtil.getClonedObject; +import static org.openecomp.sdc.translator.services.heattotosca.Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX; +import static org.openecomp.sdc.translator.services.heattotosca.Constants.COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX; +import static org.openecomp.sdc.translator.services.heattotosca.Constants.COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX; +import static org.openecomp.sdc.translator.services.heattotosca.Constants.PORT_IDENTICAL_VALUE_PROPERTY_PREFIX; + public class UnifiedCompositionService { protected static Logger logger = 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 531de16998..dff208f101 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 @@ -5,8 +5,8 @@ import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; +import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.translator.utils.ResourceWalker; import java.util.HashMap; 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 ef75f315f6..87bf36b9d5 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 @@ -20,8 +20,6 @@ package org.openecomp.sdc.translator.services.heattotosca.helper; -import static org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE; - import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; @@ -45,6 +43,8 @@ import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; +import static org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE; + public class VolumeTranslationHelper { private final Logger logger; private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); 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 48d564227e..1d35795e4c 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 @@ -21,7 +21,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.heat.services.HeatConstants; @@ -29,6 +28,7 @@ import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.datatypes.model.Template; +import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.EntityConsolidationData; import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants; 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 bc0926c9d0..374f8a9ebe 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 @@ -30,8 +30,8 @@ import org.openecomp.sdc.tosca.datatypes.model.Template; import org.openecomp.sdc.tosca.services.ToscaConstants; import org.openecomp.sdc.tosca.services.ToscaFileOutputService; import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl; -import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import java.util.ArrayList; import java.util.HashMap; 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 877659ee10..184aa52424 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 @@ -25,9 +25,9 @@ import org.openecomp.sdc.heat.datatypes.model.HeatPseudoParameters; import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.datatypes.model.Template; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; -import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import java.util.ArrayList; import java.util.HashMap; 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 b2d11e3804..ce160cee49 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 @@ -23,8 +23,8 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslati import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.datatypes.model.Template; -import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import org.openecomp.sdc.translator.services.heattotosca.helper.FunctionTranslationHelper; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; 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 b0094b0a7c..459c44e117 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 @@ -21,7 +21,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.apache.commons.collections4.MapUtils; -import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; @@ -44,6 +43,7 @@ import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; +import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; import org.openecomp.sdc.translator.datatypes.heattotosca.to.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/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 231190a16f..3a3a7c7817 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 @@ -20,7 +20,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import org.openecomp.sdc.common.utils.CommonUtil; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; @@ -32,7 +31,6 @@ import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; 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 72739d3f51..e439935517 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 @@ -22,7 +22,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslati import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Resource; 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 4cf817bcae..ea8f78a20a 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 @@ -20,8 +20,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil.getResource; - import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.datatypes.error.ErrorLevel; @@ -56,6 +54,8 @@ import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatT import java.util.List; import java.util.Optional; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil.getResource; + public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTranslationBase { protected static Logger logger = (Logger) LoggerFactory.getLogger(ResourceTranslationCinderVolumeAttachmentImpl.class); 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 d729c04cca..90206cf7c7 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 @@ -20,11 +20,11 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; @@ -32,9 +32,9 @@ import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; -import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaConstants; import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; 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 71efc18816..d12075de27 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 @@ -20,7 +20,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import org.openecomp.sdc.common.utils.CommonUtil; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; 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 875903f8a2..9ed59e04db 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 @@ -24,9 +24,9 @@ import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.datatypes.ToscaGroupType; import org.openecomp.sdc.tosca.datatypes.ToscaPolicyType; +import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition; import org.openecomp.sdc.tosca.datatypes.model.PolicyDefinition; -import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; 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; 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 96c105c04a..2a2ecf919e 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 @@ -44,14 +44,12 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; - import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil; import org.openecomp.sdc.translator.services.heattotosca.Constants; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; - import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; import java.util.ArrayList; @@ -398,28 +396,23 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { private void manageNovaServerNetwork(TranslateTo translateTo, NodeTemplate novaNodeTemplate) { + mdcDataDebugMessage.debugEntryMessage(null, null); - - String heatFileName = translateTo.getHeatFileName(); - ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); - HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo - .getHeatOrchestrationTemplate(); Resource resource = translateTo.getResource(); String translatedId = translateTo.getTranslatedId(); - TranslationContext context = translateTo.getContext(); - - mdcDataDebugMessage.debugEntryMessage(null, null); if (resource.getProperties() == null) { return; } - List> heatNetworkList = - (List>) resource.getProperties().get("networks"); - - if (CollectionUtils.isEmpty(heatNetworkList)) { + Object networks = resource.getProperties().get("networks"); + if(Objects.isNull(networks) + || !(networks instanceof List)){ return; } + List> heatNetworkList = + (List>) networks; + for (Map heatNetwork : heatNetworkList) { getOrTranslatePortTemplate(translateTo, heatNetwork.get( Constants.PORT_PROPERTY_NAME), translatedId, novaNodeTemplate); 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 3d183b1ad9..b32ea2d9de 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 @@ -21,7 +21,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.openecomp.sdc.heat.datatypes.manifest.FileData; - import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; import org.openecomp.sdc.heat.datatypes.model.Resource; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/TestUtils.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/TestUtils.java index 27298ff9b4..c7d3931961 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/TestUtils.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/TestUtils.java @@ -36,7 +36,19 @@ import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.*; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.EntityConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileComputeConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileNestedConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FilePortConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.GetAttrFuncData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedConsolidationData; +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.RequirementAssignmentData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.TypeComputeConsolidationData; import java.io.File; import java.io.FileInputStream; @@ -45,7 +57,13 @@ import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.NotDirectoryException; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; public class TestUtils { private static final String MANIFEST_NAME = SdcCommon.MANIFEST_NAME; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/impl/heattotosca/resources/OSNovaServerTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/impl/heattotosca/resources/OSNovaServerTest.java index ebb34503bb..9743483d42 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/impl/heattotosca/resources/OSNovaServerTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/impl/heattotosca/resources/OSNovaServerTest.java @@ -20,9 +20,6 @@ package org.openecomp.sdc.translator.impl.heattotosca.resources; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_PORT_POSITIVE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_VOLUME_POSITIVE; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; @@ -30,6 +27,9 @@ import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslatio import java.io.IOException; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_PORT_POSITIVE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_VOLUME_POSITIVE; + public class OSNovaServerTest extends BaseResourceTranslationTest { @Override diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtilTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtilTest.java index 019d143792..3f294eb924 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtilTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtilTest.java @@ -1,6 +1,7 @@ package org.openecomp.sdc.translator.services.heattotosca; import org.testng.annotations.Test; + import static org.testng.Assert.assertEquals; public class ConsolidationDataUtilTest { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationServiceTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationServiceTest.java index 085c329e7f..4af2415381 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationServiceTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationServiceTest.java @@ -1,39 +1,5 @@ package org.openecomp.sdc.translator.services.heattotosca; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; -import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.TestUtils; -import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionMode; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.GetAttrFuncData; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * Created by TALIO on 3/7/2017. */ diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionServiceTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionServiceTest.java index 69db1b2d84..7de9ae5588 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionServiceTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionServiceTest.java @@ -1,9 +1,5 @@ package org.openecomp.sdc.translator.services.heattotosca; -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; - import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.junit.Before; @@ -13,22 +9,40 @@ import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy; -import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; +import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.translator.TestUtils; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionEntity; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedSubstitutionData; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.*; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.EntityConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.GetAttrFuncData; +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.RequirementAssignmentData; import org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition.UnifiedCompositionSingleSubstitution; import java.io.IOException; import java.net.URL; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +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 static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; public class UnifiedCompositionServiceTest { private static final String BASE_DIRECTORY = "/mock/services/heattotosca/unifiedComposition/"; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/buildconsolidationdata/ConsolidationDataTestUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/buildconsolidationdata/ConsolidationDataTestUtil.java index dd48e618d4..bb1f898dc4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/buildconsolidationdata/ConsolidationDataTestUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/buildconsolidationdata/ConsolidationDataTestUtil.java @@ -1,19 +1,5 @@ package org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.MAIN_SERVICE_TEMPLATE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_INVALID_DEPENDENCY_CANDIDATE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_MULTIPLE_COMPUTE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_IN; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_IN_AND_OUT; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_OUT; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NO_DEPENDENCY; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_MULTIPLE_MULTI_LEVEL_NESTED_RESOURCE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_MULTIPLE_NESTED_RESOURCE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SECURITY_RULE_PORT_MULTI_LEVEL_NESTED_CONNECTION; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SECURITY_RULE_PORT_MULTI_LEVEL_NESTED_SHARED_PORT; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SECURITY_RULE_PORT_NESTED_CONNECTION; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SINGLE_NESTED_RESOURCE; - import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.collections4.CollectionUtils; import org.junit.Assert; @@ -51,6 +37,20 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.MAIN_SERVICE_TEMPLATE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_INVALID_DEPENDENCY_CANDIDATE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_MULTIPLE_COMPUTE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_IN; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_IN_AND_OUT; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_OUT; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NO_DEPENDENCY; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_MULTIPLE_MULTI_LEVEL_NESTED_RESOURCE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_MULTIPLE_NESTED_RESOURCE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SECURITY_RULE_PORT_MULTI_LEVEL_NESTED_CONNECTION; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SECURITY_RULE_PORT_MULTI_LEVEL_NESTED_SHARED_PORT; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SECURITY_RULE_PORT_NESTED_CONNECTION; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SINGLE_NESTED_RESOURCE; + public class ConsolidationDataTestUtil { public static void validateVolumeInConsolidationData(String computeNodeTemplateId, diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelperTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelperTest.java index 9b4a59b01f..1a108ce42f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelperTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelperTest.java @@ -31,7 +31,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * @author SHIRIA diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImplTest.java index b79671d763..2a633da55b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImplTest.java @@ -28,8 +28,8 @@ import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.services.ToscaConstants; import org.openecomp.sdc.tosca.services.ToscaFileOutputService; import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl; -import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; import java.util.HashMap; import java.util.List; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImplTest.java index 981c061e0a..860074ba70 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImplTest.java @@ -30,7 +30,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; public class FunctionTranslationGetParamImplTest extends BaseResourceTranslationTest { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImplTest.java index 9fdd2db4cb..9a249d7b29 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImplTest.java @@ -23,7 +23,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor; import org.junit.Assert; import org.junit.Test; import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor.NameExtractorContrailComputeImpl; import java.util.HashMap; import java.util.Map; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImplTest.java index 58237975b6..3095b528e3 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImplTest.java @@ -23,7 +23,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor; import org.junit.Test; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.translator.services.heattotosca.Constants; -import org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor.NameExtractorNovaServerImpl; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationNovaServerImpl; import java.util.Arrays; @@ -31,7 +30,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; /** * @author SHIRIA diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceTranslationTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceTranslationTest.java index 528db5ee77..dcfe1270ea 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceTranslationTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceTranslationTest.java @@ -20,19 +20,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.junit.Assert.assertEquals; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateComputeConnectivityIn; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateComputeConnectivityOut; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateDependsOnInConsolidationData; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateGetAttr; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateGroupsInConsolidationData; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateNestedConsolidationData; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validatePortConnectivityIn; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validatePortConnectivityOut; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validatePortsInConsolidationData; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateNestedConsolidationDataNodeTemplateIds; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateVolumeInConsolidationData; - import org.apache.commons.collections4.MapUtils; import org.junit.AfterClass; import org.junit.Assert; @@ -86,6 +73,19 @@ import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import static org.junit.Assert.assertEquals; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateComputeConnectivityIn; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateComputeConnectivityOut; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateDependsOnInConsolidationData; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateGetAttr; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateGroupsInConsolidationData; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateNestedConsolidationData; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateNestedConsolidationDataNodeTemplateIds; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validatePortConnectivityIn; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validatePortConnectivityOut; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validatePortsInConsolidationData; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateVolumeInConsolidationData; + public class BaseResourceTranslationTest { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/DependsOnResourceBaseTranslationlTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/DependsOnResourceBaseTranslationlTest.java index 117dd0cd59..9c4c3a40c4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/DependsOnResourceBaseTranslationlTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/DependsOnResourceBaseTranslationlTest.java @@ -20,6 +20,12 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; + +import java.io.IOException; + import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_INVALID_DEPENDENCY_CANDIDATE; import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_MULTIPLE_COMPUTE; import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_IN; @@ -28,12 +34,6 @@ import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidati import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODE_TEMPLATE_TRANSLATION_ORDER_INVARIANCE; import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NO_DEPENDENCY; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; - -import java.io.IOException; - public class DependsOnResourceBaseTranslationlTest extends BaseResourceTranslationTest { @Override diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImplTest.java index 786b613d0f..637b131712 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImplTest.java @@ -20,15 +20,15 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_VOLUME_NEGATIVE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_VOLUME_POSITIVE; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; import java.io.IOException; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_VOLUME_NEGATIVE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_VOLUME_POSITIVE; + public class ResourceTranslationCinderVolumeAttachmentImplTest extends BaseResourceTranslationTest { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImplTest.java index 3e69ed17c0..74a6ce5a5b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImplTest.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_CONNECTIVITY_POSITIVE; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; import java.io.IOException; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_CONNECTIVITY_POSITIVE; + /** * @author Avrahamg * @since August 10, 2016 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImplTest.java index 854a2632b3..97a59c3934 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImplTest.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_CONNECTIVITY_POSITIVE; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; import java.io.IOException; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_CONNECTIVITY_POSITIVE; + public class ResourceTranslationNeutronPortImplTest extends BaseResourceTranslationTest { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImplTest.java index 03b9402e01..6767db4217 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImplTest.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_GROUP_POSITIVE; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; import java.io.IOException; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_GROUP_POSITIVE; + public class ResourceTranslationNovaServerGroupsImplTest extends BaseResourceTranslationTest { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnectionTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnectionTest.java index 724f6247af..15bf0f28bc 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnectionTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnectionTest.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateNestedNodesConnectedInSecurityRuleToPort; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants; import java.io.IOException; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateNestedNodesConnectedInSecurityRuleToPort; + public class SecurityRulesToPortResourceConnectionTest extends BaseResourceTranslationTest { @Override 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 bc401d4a45..97da6ef631 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 @@ -22,9 +22,9 @@ 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 org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.MdcUtil; import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; 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 acb4eed448..2f5a8ce399 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 @@ -21,13 +21,13 @@ package org.openecomp.sdc.validation.impl; import org.apache.commons.collections4.CollectionUtils; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.core.validation.api.ValidationManager; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.core.validation.types.MessageContainer; import org.openecomp.sdc.datatypes.error.ErrorMessage; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.services.ValidationFactory; import java.util.HashMap; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/test/java/org/openecomp/sdc/heat/services/tree/HeatTreeManagerTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/test/java/org/openecomp/sdc/heat/services/tree/HeatTreeManagerTest.java index e3464db8d8..e5d1a88821 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/test/java/org/openecomp/sdc/heat/services/tree/HeatTreeManagerTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/test/java/org/openecomp/sdc/heat/services/tree/HeatTreeManagerTest.java @@ -20,7 +20,6 @@ package org.openecomp.sdc.heat.services.tree; -import org.openecomp.config.ConfigurationUtils; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.heat.datatypes.structure.HeatStructureTree; @@ -33,9 +32,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; public class HeatTreeManagerTest { 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 90750a48ec..e437892758 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 @@ -17,13 +17,15 @@ package org.openecomp.sdc.validation.impl.util; import org.apache.commons.collections4.CollectionUtils; -import org.openecomp.sdc.heat.datatypes.model.*; -import org.openecomp.sdc.tosca.services.YamlUtil; 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.DefinedHeatParameterTypes; +import org.openecomp.sdc.heat.datatypes.model.Environment; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.Parameter; +import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; @@ -32,10 +34,18 @@ import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.validation.impl.validators.HeatValidator; import java.io.InputStream; -import java.util.*; +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 { 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 5045c80d11..eb23930216 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 @@ -22,9 +22,7 @@ package org.openecomp.sdc.validation.impl.validators; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.validation.ErrorMessageCode; -import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.datatypes.error.ErrorLevel; @@ -39,6 +37,8 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.services.YamlUtil; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.tos.ContrailResourcesMappingTo; import org.openecomp.sdc.validation.util.ValidationUtil; @@ -62,7 +62,7 @@ public class ContrailValidator implements Validator { ManifestContent manifestContent; try { - manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + manifestContent = ValidationUtil.validateManifest(globalContext); } catch (Exception exception) { logger.debug("",exception); return; 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 2dad766c45..2107825c6c 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 @@ -63,7 +63,7 @@ public class ForbiddenResourceGuideLineValidator implements Validator { public void validate(GlobalValidationContext globalContext) { ManifestContent manifestContent; try { - manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + manifestContent = ValidationUtil.validateManifest(globalContext); } catch (Exception exception) { log.debug("",exception); return; 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 10cfe352f6..89e96efa36 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 @@ -14,7 +14,6 @@ import org.openecomp.sdc.heat.services.HeatStructureUtil; import org.openecomp.sdc.heat.services.manifest.ManifestUtil; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.base.ResourceBaseValidator; import org.openecomp.sdc.validation.type.ConfigConstants; @@ -31,8 +30,7 @@ import java.util.Objects; import java.util.Set; public class HeatResourceValidator extends ResourceBaseValidator { - public static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private static Logger logger = (Logger) LoggerFactory.getLogger(ResourceBaseValidator.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ResourceBaseValidator.class); private static final ErrorMessageCode ERROR_CODE_HTR_1 = new ErrorMessageCode("HTR1"); @Override @@ -42,14 +40,14 @@ public class HeatResourceValidator extends ResourceBaseValidator { @Override public ValidationContext createValidationContext(String fileName, - String envFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { + String envFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { ManifestContent manifestContent = new ManifestContent(); try { - manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + manifestContent = ValidationUtil.validateManifest(globalContext); } catch (Exception exception) { - logger.debug("",exception); + LOGGER.debug("", exception); } Set baseFiles = ManifestUtil.getBaseFiles(manifestContent); String baseFileName = CollectionUtils.isEmpty(baseFiles) ? null : baseFiles.iterator().next(); @@ -58,7 +56,7 @@ public class HeatResourceValidator extends ResourceBaseValidator { ValidationUtil.checkHeatOrchestrationPreCondition(baseFileName, globalContext); Set securityGroupsNamesFromBaseFileOutputs = baseFileName == null ? new HashSet<>() : checkForBaseFilePortsExistenceAndReturnSecurityGroupNamesFromOutputsIfNot - (baseFileName, baseHot, globalContext); + (baseHot); Map resourcesMap = heatOrchestrationTemplate.getResources() == null ? new HashMap<>() @@ -86,7 +84,7 @@ public class HeatResourceValidator extends ResourceBaseValidator { GlobalValidationContext globalContext) { initTypeRelationsMapFromResourcesMap - (fileName, resourceMap, securityGroupsNamesFromBaseFileOutputs, + (fileName, resourceMap, typeToPointingResourcesMap, globalContext); initTypeRelationsMapFromOutputsMap @@ -133,13 +131,13 @@ public class HeatResourceValidator extends ResourceBaseValidator { private void initTypeRelationsMapFromResourcesMap(String fileName, Map resourceMap, - Set securityGroupsNamesFromBaseFileOutputs, Map>>> typeToPointingResourcesMap, GlobalValidationContext globalContext) { for (Map.Entry resourceEntry : resourceMap.entrySet()) { Resource pointingResource = resourceEntry.getValue(); Map properties = - pointingResource.getProperties() == null ? new HashMap<>() : pointingResource.getProperties(); + pointingResource.getProperties() == null ? new HashMap<>() + : pointingResource.getProperties(); Set referencedResourcesByGetResource = getResourcesIdsPointedByCurrentResource(fileName, ResourceReferenceFunctions.GET_RESOURCE, @@ -231,9 +229,9 @@ public class HeatResourceValidator extends ResourceBaseValidator { (pointingResourceType, new ArrayList<>()); } - private Set handleGetAttrBetweenResources(Map properties){ + private Set handleGetAttrBetweenResources(Map properties) { Set referencedResourcesByGetAttr = new HashSet<>(); - for(Map.Entry proprtyEntry : properties.entrySet()){ + for (Map.Entry proprtyEntry : properties.entrySet()) { referencedResourcesByGetAttr.addAll(getGetAttrReferencesInCaseOfContrail(proprtyEntry .getValue())); } @@ -242,7 +240,7 @@ public class HeatResourceValidator extends ResourceBaseValidator { } - private Set getGetAttrReferencesInCaseOfContrail(Object propertyValue){ + private Set getGetAttrReferencesInCaseOfContrail(Object propertyValue) { Object value; Set getAttrReferences = new HashSet<>(); @@ -255,11 +253,11 @@ public class HeatResourceValidator extends ResourceBaseValidator { getAttrReferences.add((String) ((List) value).get(0)); return getAttrReferences; } else { - logger.warn("invalid format of 'get_attr' function - " + propertyValue.toString()); + LOGGER.warn("invalid format of 'get_attr' function - " + propertyValue.toString()); } } } - }else { + } else { Collection valCollection = ((Map) propertyValue).values(); for (Object entryValue : valCollection) { getAttrReferences.addAll(getGetAttrReferencesInCaseOfContrail(entryValue)); @@ -294,8 +292,7 @@ public class HeatResourceValidator extends ResourceBaseValidator { } private Set checkForBaseFilePortsExistenceAndReturnSecurityGroupNamesFromOutputsIfNot( - String baseFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { + HeatOrchestrationTemplate heatOrchestrationTemplate) { Set securityGroupsNamesFromOutputsMap = new HashSet<>(); if (heatOrchestrationTemplate != null) { 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 da87a13eb4..8064c6f20a 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 @@ -23,11 +23,6 @@ package org.openecomp.sdc.validation.impl.validators; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.validation.ErrorMessageCode; -import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; -import org.openecomp.sdc.logging.types.LoggerConstants; -import org.openecomp.sdc.logging.types.LoggerErrorCode; -import org.openecomp.sdc.tosca.services.YamlUtil; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; @@ -48,13 +43,24 @@ import org.openecomp.sdc.heat.services.manifest.ManifestUtil; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.services.YamlUtil; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.impl.util.HeatValidationService; import org.openecomp.sdc.validation.util.ValidationUtil; import java.io.InputStream; -import java.util.*; +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; public class HeatValidator implements Validator { public static final MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); @@ -126,91 +132,91 @@ public class HeatValidator implements Validator { : heatOrchestrationTemplate.getResources().values(); Collection outputsValues = heatOrchestrationTemplate.getOutputs() == null ? null : heatOrchestrationTemplate.getOutputs().values(); - checkResourceExistenceFromResourcesMap(fileName, resourcesNames, resourcesValues, - globalContext); - checkResourceExistenceFromResourcesMap(fileName, resourcesNames, outputsValues, - globalContext); + checkResourceExistenceFromResourcesMap(fileName, resourcesNames, resourcesValues, + globalContext); + checkResourceExistenceFromResourcesMap(fileName, resourcesNames, outputsValues, + globalContext); mdcDataDebugMessage.debugExitMessage("file", fileName); } - private static void checkResourceExistenceFromResourcesMap(String fileName, - Set resourcesNames, - Collection valuesToSearchIn, - GlobalValidationContext globalContext) { - - mdcDataDebugMessage.debugEntryMessage("file", fileName); - - 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 checkResourceExistenceFromResourcesMap(String fileName, + Set resourcesNames, + Collection valuesToSearchIn, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + 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) { Resource resource = value; Collection resourcePropertiesValues = - resource.getProperties() == null ? null : resource.getProperties() - .values(); + resource.getProperties() == null ? null : resource.getProperties() + .values(); if (CollectionUtils.isNotEmpty(resourcePropertiesValues)) { - for (Object propertyValue : resourcePropertiesValues) { - handleReferencedResources(fileName, propertyValue, resourcesNames, - globalContext); - } + for (Object propertyValue : resourcePropertiesValues) { + handleReferencedResources(fileName, propertyValue, resourcesNames, + globalContext); + } } } private static void handleReferencedResources(String fileName, Object valueToSearchReferencesIn, - Set resourcesNames, - GlobalValidationContext globalContext) { - - - mdcDataDebugMessage.debugEntryMessage("file", fileName); - 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); - } + Set resourcesNames, + GlobalValidationContext globalContext) { + - mdcDataDebugMessage.debugExitMessage("file", fileName); + mdcDataDebugMessage.debugEntryMessage("file", fileName); + 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) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + private static void checkIfResourceReferenceExist(String fileName, + Set referencedResourcesNames, + Set referencedResources, + GlobalValidationContext globalContext) { - mdcDataDebugMessage.debugEntryMessage("file", fileName); - 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), - LoggerTragetServiceName.VALIDATE_RESOURCE_REFERENCE_EXISTENCE, - LoggerErrorDescription.RESOURCE_NOT_FOUND); - }); + mdcDataDebugMessage.debugEntryMessage("file", fileName); - mdcDataDebugMessage.debugExitMessage("file", fileName); - } + 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), + LoggerTragetServiceName.VALIDATE_RESOURCE_REFERENCE_EXISTENCE, + LoggerErrorDescription.RESOURCE_NOT_FOUND); + }); + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } /* validation 16 */ @@ -294,79 +300,79 @@ public class HeatValidator implements Validator { mdcDataDebugMessage.debugExitMessage("file", fileName); } - private static void loopOverOutputMapAndValidateGetAttrFromNested(String fileName, - Map outputMap, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - GlobalValidationContext - globalContext) { - for (Output output : outputMap.values()) { - Object outputValue = output.getValue(); - if (outputValue != null && outputValue instanceof Map) { - Map outputValueMap = (Map) outputValue; - List getAttrValue = - (List) outputValueMap.get( - ResourceReferenceFunctions.GET_ATTR.getFunction()); - if (!CollectionUtils.isEmpty(getAttrValue)) { - String resourceName = getAttrValue.get(0); - Object attNameObject = getAttrValue.get(1); - if (!(attNameObject instanceof String)) { - return; - } - String attName = getAttrValue.get(1); - String resourceType = - getResourceTypeFromResourcesMap(resourceName, heatOrchestrationTemplate); - - if (Objects.nonNull(resourceType) - && HeatValidationService.isNestedResource(resourceType)) { - handleGetAttrNestedResource(fileName, globalContext, resourceName, attName, - 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 { - MdcDataErrorMessage - .createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, - LoggerTragetServiceName.VALIDATE_GET_ATTR_FROM_NESTED, - ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), - LoggerErrorDescription.EMPTY_FILE); - throw new Exception("The file '" + resourceType + "' has no content"); - } - } catch (Exception exception) { - logger.debug("",exception); + private static void loopOverOutputMapAndValidateGetAttrFromNested(String fileName, + Map outputMap, + HeatOrchestrationTemplate + heatOrchestrationTemplate, + GlobalValidationContext + globalContext) { + for (Output output : outputMap.values()) { + Object outputValue = output.getValue(); + if (outputValue != null && outputValue instanceof Map) { + Map outputValueMap = (Map) outputValue; + List getAttrValue = + (List) outputValueMap.get( + ResourceReferenceFunctions.GET_ATTR.getFunction()); + if (!CollectionUtils.isEmpty(getAttrValue)) { + String resourceName = getAttrValue.get(0); + Object attNameObject = getAttrValue.get(1); + if (!(attNameObject instanceof String)) { return; + } + String attName = getAttrValue.get(1); + String resourceType = + getResourceTypeFromResourcesMap(resourceName, heatOrchestrationTemplate); + + if (Objects.nonNull(resourceType) + && HeatValidationService.isNestedResource(resourceType)) { + handleGetAttrNestedResource(fileName, globalContext, resourceName, attName, + resourceType); + } } - 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), - LoggerTragetServiceName.VALIDATE_GET_ATTR_FROM_NESTED, - LoggerErrorDescription.GET_ATTR_NOT_FOUND); - } + 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 { + MdcDataErrorMessage + .createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, + LoggerTragetServiceName.VALIDATE_GET_ATTR_FROM_NESTED, + ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), + LoggerErrorDescription.EMPTY_FILE); + throw new Exception("The file '" + resourceType + "' has no content"); + } + } catch (Exception exception) { + logger.debug("",exception); + return; } + nestedOutputMap = nestedHeatOrchestrationTemplate.getOutputs(); - private static String getResourceTypeFromResourcesMap(String resourceName, - HeatOrchestrationTemplate - heatOrchestrationTemplate) { - return heatOrchestrationTemplate.getResources().get(resourceName).getType(); + 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), + LoggerTragetServiceName.VALIDATE_GET_ATTR_FROM_NESTED, + LoggerErrorDescription.GET_ATTR_NOT_FOUND); } + } + + private static String getResourceTypeFromResourcesMap(String resourceName, + HeatOrchestrationTemplate + heatOrchestrationTemplate) { + return heatOrchestrationTemplate.getResources().get(resourceName).getType(); + } /* validation 17 + */ private static void validateEnvFile(String fileName, String envFileName, @@ -416,7 +422,7 @@ public class HeatValidator implements Validator { if (parametersNames != null && !parametersNames.contains(envParameter)) { globalContext.addMessage(envFile, ErrorLevel.ERROR, ErrorMessagesFormatBuilder .getErrorWithParameters( - ERROR_CODE_HOT_3,Messages. + ERROR_CODE_HOT_3,Messages. ENV_INCLUDES_PARAMETER_NOT_IN_HEAT.getErrorMessage(), envFile, envParameter), LoggerTragetServiceName.VALIDATE_ENV_FILE, LoggerErrorDescription.ENV_PARAMETER_NOT_IN_HEAT); @@ -459,7 +465,7 @@ public class HeatValidator implements Validator { if (!isValueMatchDefault) { globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder .getErrorWithParameters( - ERROR_CODE_HOT_4,Messages. + ERROR_CODE_HOT_4,Messages. PARAMETER_DEFAULT_VALUE_NOT_ALIGN_WITH_TYPE.getErrorMessage(), parameterEntry.getKey(), parameterType), LoggerTragetServiceName.VALIDATE_PARAMTER_DEFAULT_MATCH_TYPE, @@ -495,7 +501,7 @@ public class HeatValidator implements Validator { .isValueIsFromGivenType(parameterEnvValue, parameterType)) { globalContext.addMessage(envFile, ErrorLevel.ERROR, ErrorMessagesFormatBuilder .getErrorWithParameters( - ERROR_CODE_HOT_5,Messages. + ERROR_CODE_HOT_5,Messages. PARAMETER_ENV_VALUE_NOT_ALIGN_WITH_TYPE.getErrorMessage(), parameterName), LoggerTragetServiceName.VALIDATE_ENV_PARAMETER_MATCH_TYPE, LoggerErrorDescription.PARAMETER_DEFAULT_VALUE_NOT_ALIGNED_WITH_TYPE); @@ -513,7 +519,7 @@ public class HeatValidator implements Validator { mdcDataDebugMessage.debugEntryMessage(null, null); ManifestContent manifestContent; try { - manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + manifestContent = ValidationUtil.validateManifest(globalContext); } catch (Exception exception) { logger.debug("",exception); return; @@ -546,9 +552,9 @@ public class HeatValidator implements Validator { .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()), + ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_11, + Messages.ARTIFACT_FILE_NOT_REFERENCED.getErrorMessage()), LoggerTragetServiceName.CHECK_FOR_ORPHAN_ARTIFACTS, LoggerErrorDescription.ARTIFACT_NOT_REFERENCED)); @@ -567,10 +573,10 @@ public class HeatValidator implements Validator { private void validate(String fileName, String envFileName, String baseFileName, Set artifacts, Set securityGroupsNamesFromBaseFileOutputs, GlobalValidationContext globalContext) { - globalContext.setMessageCode(ERROR_CODE_HOT_12); + globalContext.setMessageCode(ERROR_CODE_HOT_12); HeatOrchestrationTemplate heatOrchestrationTemplate = ValidationUtil.checkHeatOrchestrationPreCondition( - fileName, globalContext); + fileName, globalContext); if (heatOrchestrationTemplate != null) { 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 2ad2f9afb4..e3a35af6dc 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 @@ -22,7 +22,6 @@ package org.openecomp.sdc.validation.impl.validators; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.validation.ErrorMessageCode; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; @@ -38,6 +37,7 @@ import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.Validator; import java.io.InputStream; import java.util.ArrayList; 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 724b7e4735..43e8e9404f 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 @@ -1,8 +1,8 @@ package org.openecomp.sdc.validation.impl.validators; -import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.base.ResourceBaseValidator; import org.openecomp.sdc.validation.type.ConfigConstants; import org.openecomp.sdc.validation.type.NamingConventionValidationContext; 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 424f8d3517..fb7d6a2c97 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 @@ -3,13 +3,10 @@ package org.openecomp.sdc.validation.impl.validators; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.validation.ErrorMessageCode; -import org.openecomp.sdc.common.utils.SdcCommon; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.validation.Validator; 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.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; @@ -18,9 +15,12 @@ import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; import org.openecomp.sdc.heat.services.HeatStructureUtil; import org.openecomp.sdc.heat.services.manifest.ManifestUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.util.ValidationUtil; import java.util.HashSet; @@ -44,7 +44,7 @@ public class SharedResourceGuideLineValidator implements Validator { public void validate(GlobalValidationContext globalContext) { ManifestContent manifestContent; try { - manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + manifestContent = ValidationUtil.validateManifest(globalContext); } catch (Exception exception) { log.debug("",exception); return; 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 c0468f8b5a..ab2e427f23 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 @@ -21,8 +21,6 @@ package org.openecomp.sdc.validation.impl.validators; import org.openecomp.core.validation.ErrorMessageCode; -import org.openecomp.sdc.tosca.services.YamlUtil; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; @@ -32,6 +30,8 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.services.YamlUtil; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.impl.util.YamlValidatorUtil; import java.io.InputStream; 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 9c9f4bcdc0..33d20d5714 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 @@ -2,7 +2,6 @@ package org.openecomp.sdc.validation.impl.validators.heatresource; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.validation.ErrorMessageCode; -import org.openecomp.sdc.validation.ResourceValidator; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; @@ -15,6 +14,7 @@ import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.ResourceValidator; import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.type.HeatResourceValidationContext; 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 b98b6d6600..795bdf0f9f 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 @@ -1,7 +1,5 @@ package org.openecomp.sdc.validation.impl.validators.namingconvention; -import static java.util.Objects.nonNull; - import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; @@ -36,6 +34,8 @@ import java.util.Map; import java.util.Objects; import java.util.TreeMap; +import static java.util.Objects.nonNull; + public class NovaServerNamingConventionGuideLineValidator implements ResourceValidator { private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private static final ErrorMessageCode ERROR_CODE_NNS1 = new ErrorMessageCode("NNS1"); diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ContrailValidatorTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ContrailValidatorTest.java index f921102957..96db0fd19d 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ContrailValidatorTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ContrailValidatorTest.java @@ -20,9 +20,9 @@ package org.openecomp.sdc.validation.impl.validators; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.types.MessageContainer; import org.openecomp.sdc.datatypes.error.ErrorMessage; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.util.ValidationTestUtil; import org.testng.Assert; import org.testng.annotations.Test; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ErrorMessagesTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ErrorMessagesTest.java index 64b3d2bb3c..5c2c0c0bf0 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ErrorMessagesTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ErrorMessagesTest.java @@ -21,10 +21,10 @@ package org.openecomp.sdc.validation.impl.validators; import org.junit.Test; +import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.sdc.common.errors.Messages; import org.testng.Assert; -import org.openecomp.core.validation.ErrorMessageCode; public class ErrorMessagesTest { diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/HeatValidatorTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/HeatValidatorTest.java index a523627081..2ec119e665 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/HeatValidatorTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/HeatValidatorTest.java @@ -21,8 +21,8 @@ package org.openecomp.sdc.validation.impl.validators; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.types.MessageContainer; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.util.ValidationTestUtil; import org.testng.Assert; import org.testng.annotations.Test; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidatorTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidatorTest.java index e7c2d37d32..58400b91da 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidatorTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidatorTest.java @@ -1,7 +1,7 @@ package org.openecomp.sdc.validation.impl.validators; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.types.MessageContainer; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.util.ValidationTestUtil; import org.testng.Assert; import org.testng.annotations.Test; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidatorTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidatorTest.java index 681c54b12e..0db8c221b9 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidatorTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidatorTest.java @@ -1,9 +1,8 @@ package org.openecomp.sdc.validation.impl.validators.namingconvention; -import org.openecomp.sdc.validation.impl.validators.HeatResourceValidator; - import org.openecomp.core.validation.types.MessageContainer; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.validation.impl.validators.HeatResourceValidator; import org.openecomp.sdc.validation.util.ValidationTestUtil; import org.testng.Assert; import org.testng.annotations.Test; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidatorTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidatorTest.java index 1a7b6081d1..3837f3b260 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidatorTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidatorTest.java @@ -1,9 +1,8 @@ package org.openecomp.sdc.validation.impl.validators.namingconvention; -import org.openecomp.sdc.validation.impl.validators.NamingConventionGuideLineValidator; - import org.openecomp.core.validation.types.MessageContainer; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.validation.impl.validators.NamingConventionGuideLineValidator; import org.openecomp.sdc.validation.util.ValidationTestUtil; import org.testng.Assert; import org.testng.annotations.Test; 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 c4d6f88074..68c1b74c99 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 @@ -4,7 +4,9 @@ import org.apache.commons.collections4.MapUtils; import org.openecomp.core.utilities.CommonMethods; 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.configuration.ImplementationConfiguration; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; @@ -12,15 +14,13 @@ import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.heat.services.HeatStructureUtil; import org.openecomp.sdc.heat.services.manifest.ManifestUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; import org.openecomp.sdc.validation.ResourceValidator; import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.Validator; -import org.openecomp.core.validation.types.GlobalValidationContext; -import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.validation.type.ConfigConstants; import org.openecomp.sdc.validation.util.ValidationUtil; @@ -54,7 +54,7 @@ public class ResourceBaseValidator implements Validator { public void validate(GlobalValidationContext globalContext) { ManifestContent manifestContent; try { - manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + manifestContent = ValidationUtil.validateManifest(globalContext); } catch (Exception exception) { logger.debug("",exception); return; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationTestUtil.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationTestUtil.java index 2b58a30e50..08a3548a7d 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationTestUtil.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationTestUtil.java @@ -25,7 +25,6 @@ import org.testng.Assert; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.StringWriter; import java.net.URL; @@ -97,7 +96,7 @@ public class ValidationTestUtil { String resourceTypeToValidate, String path) { GlobalValidationContext globalContext = createGlobalContextFromPath(path); - ManifestContent manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + ManifestContent manifestContent = ValidationUtil.validateManifest(globalContext); Map fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); Map fileEnvMap = ManifestUtil.getFileAndItsEnv(manifestContent); 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 d9e0351578..76b4aff1f5 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 @@ -6,6 +6,7 @@ import org.openecomp.core.utilities.json.JsonUtil; 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.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; @@ -176,7 +177,7 @@ public class ValidationUtil { return false; } - public static ManifestContent checkValidationPreCondition(GlobalValidationContext globalContext) { + public static ManifestContent validateManifest(GlobalValidationContext globalContext) { Optional manifest = globalContext.getFileContent(SdcCommon.MANIFEST_NAME); if (!manifest.isPresent()) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, @@ -192,7 +193,7 @@ public class ValidationUtil { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.VALIDATE_MANIFEST_CONTENT, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_MANIFEST); - throw new RuntimeException("Can't load manifest file for Heat Validator"); + throw new SdcRuntimeException("Can't load manifest file for Heat Validator"); } return manifestContent; 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 new file mode 100644 index 0000000000..3ee326af4c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseUtil.java @@ -0,0 +1,28 @@ +package org.openecomp.sdc.vendorlicense; + +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; + +import java.text.ParseException; +import java.text.SimpleDateFormat; + +public class VendorLicenseUtil { + + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + public static String getIsoFormatDate(String inputDate) { + mdcDataDebugMessage.debugEntryMessage("inputDate date", inputDate); + String isoFormatDate = null; + 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 { + isoFormatDate = isoDateFormat.format(inputDateFormat.parse(inputDate)); + } catch (ParseException e) { + mdcDataDebugMessage.debugExitMessage("parsing error", isoFormatDate); + isoFormatDate = null; + } + + mdcDataDebugMessage.debugExitMessage("formatted date", isoFormatDate); + return isoFormatDate; + } +} 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 2b7b3a6ded..6c4ba90d96 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 @@ -26,6 +26,9 @@ import com.datastax.driver.mapping.annotations.Enumerated; 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.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.vendorlicense.VendorLicenseUtil; 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; @@ -40,6 +43,8 @@ import java.util.Set; @Table(keyspace = "dox", name = "entitlement_pool") public class EntitlementPoolEntity implements VersionableEntity { + + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private static final String ENTITY_TYPE = "Entitlement Pool"; @PartitionKey @@ -201,7 +206,7 @@ public class EntitlementPoolEntity implements VersionableEntity { } public void setOperationalScope(MultiChoiceOrOther operationalScope) { - if(operationalScope != null) { + if (operationalScope != null) { operationalScope.resolveEnum(OperationalScope.class); } this.operationalScope = operationalScope; @@ -220,7 +225,8 @@ public class EntitlementPoolEntity implements VersionableEntity { } /** - * Gets version for artifact. + * Gets version for artifact. + * * @return version in format suitable for artifact */ public String getVersionForArtifact() { @@ -251,17 +257,18 @@ public class EntitlementPoolEntity implements VersionableEntity { this.limits = limits; } - public LimitForXml getSPLimits(){ - if(limits != null){ + public LimitForXml getSPLimits() { + if (limits != null) { Set hs = new HashSet<>(); - for(LimitEntity obj : limits){ - if(obj.getType().equals(LimitType.ServiceProvider)){ + 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.setAggregationFunction( + obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); xmlObj.setTime(obj.getTime()); hs.add(xmlObj); } @@ -274,17 +281,18 @@ public class EntitlementPoolEntity implements VersionableEntity { return null; } - public LimitForXml getVendorLimits(){ - if(limits != null){ + public LimitForXml getVendorLimits() { + if (limits != null) { Set hs = new HashSet<>(); - for(LimitEntity obj : limits){ - if(obj.getType().equals(LimitType.Vendor)){ + 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.setAggregationFunction( + obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); xmlObj.setTime(obj.getTime()); hs.add(xmlObj); } @@ -324,7 +332,9 @@ public class EntitlementPoolEntity implements VersionableEntity { && Objects.equals(operationalScope, that.operationalScope) && Objects.equals(referencingFeatureGroups, that.referencingFeatureGroups) && Objects.equals(startDate, that.startDate) - && Objects.equals(expiryDate, that.expiryDate); + && Objects.equals(expiryDate, that.expiryDate) + && Objects.equals(manufacturerReferenceNumber, that.manufacturerReferenceNumber) + && Objects.equals(version, that.version); } @Override @@ -354,7 +364,7 @@ public class EntitlementPoolEntity implements VersionableEntity { public OperationalScopeForXml getOperationalScopeForArtifact() { OperationalScopeForXml obj = new OperationalScopeForXml(); if (operationalScope != null) { - if(operationalScope.getResults().size() > 0) { + if (operationalScope.getResults().size() > 0) { obj.setValue(operationalScope.getResults()); } } @@ -369,4 +379,27 @@ public class EntitlementPoolEntity implements VersionableEntity { public String getManufacturerReferenceNumber() { return manufacturerReferenceNumber; } + + public String getIsoFormatStartDate() { + mdcDataDebugMessage.debugEntryMessage("start date", startDate); + String isoFormatStartDate = null; + if (!StringUtils.isEmpty(startDate)) { + isoFormatStartDate = VendorLicenseUtil.getIsoFormatDate(startDate); + mdcDataDebugMessage.debugExitMessage("start date", "iso format start date", startDate, + isoFormatStartDate); + } + return isoFormatStartDate; + } + + + public String getIsoFormatExpiryDate() { + mdcDataDebugMessage.debugEntryMessage("expiry date", expiryDate); + String isoFormatExpDate = null; + if (!StringUtils.isEmpty(expiryDate)) { + isoFormatExpDate = VendorLicenseUtil.getIsoFormatDate(expiryDate); + mdcDataDebugMessage.debugExitMessage("expiry date", "iso format expiry date", expiryDate, + isoFormatExpDate); + } + 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/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 364a240498..7794aaf275 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 @@ -26,9 +26,12 @@ import com.datastax.driver.mapping.annotations.Enumerated; 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.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.vendorlicense.VendorLicenseUtil; import org.openecomp.sdc.vendorlicense.dao.types.xml.LicenseKeyTypeForXml; -import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitXml; 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; @@ -41,6 +44,8 @@ import java.util.Set; @Table(keyspace = "dox", name = "license_key_group") public class LicenseKeyGroupEntity implements VersionableEntity { + + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private static final String ENTITY_TYPE = "License Key Group"; @PartitionKey @@ -164,7 +169,7 @@ public class LicenseKeyGroupEntity implements VersionableEntity { } public void setOperationalScope(MultiChoiceOrOther operationalScope) { - if(operationalScope != null) { + if (operationalScope != null) { operationalScope.resolveEnum(OperationalScope.class); } this.operationalScope = operationalScope; @@ -217,17 +222,18 @@ public class LicenseKeyGroupEntity implements VersionableEntity { this.limits = limits; } - public LimitForXml getSPLimits(){ - if(limits != null){ + public LimitForXml getSPLimits() { + if (limits != null) { Set hs = new HashSet<>(); - for(LimitEntity obj : limits){ - if(obj.getType().equals(LimitType.ServiceProvider)){ + 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.setAggregationFunction( + obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); xmlObj.setTime(obj.getTime()); hs.add(xmlObj); } @@ -240,17 +246,18 @@ public class LicenseKeyGroupEntity implements VersionableEntity { return null; } - public LimitForXml getVendorLimits(){ - if(limits != null){ + public LimitForXml getVendorLimits() { + if (limits != null) { Set hs = new HashSet<>(); - for(LimitEntity obj : limits){ - if(obj.getType().equals(LimitType.Vendor)){ + 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.setAggregationFunction( + obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); xmlObj.setTime(obj.getTime()); hs.add(xmlObj); } @@ -297,6 +304,7 @@ public class LicenseKeyGroupEntity implements VersionableEntity { } 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) @@ -307,7 +315,8 @@ public class LicenseKeyGroupEntity implements VersionableEntity { && Objects.equals(expiryDate, that.expiryDate) && Objects.equals(thresholdValue, that.thresholdValue) && Objects.equals(thresholdUnits, that.thresholdUnits) - && Objects.equals(increments, that.increments); + && Objects.equals(increments, that.increments) + && Objects.equals(manufacturerReferenceNumber, that.manufacturerReferenceNumber); } @Override @@ -337,7 +346,7 @@ public class LicenseKeyGroupEntity implements VersionableEntity { public OperationalScopeForXml getOperationalScopeForArtifact() { OperationalScopeForXml obj = new OperationalScopeForXml(); if (operationalScope != null) { - if(operationalScope.getResults().size() > 0) { + if (operationalScope.getResults().size() > 0) { obj.setValue(operationalScope.getResults()); } } @@ -346,6 +355,7 @@ public class LicenseKeyGroupEntity implements VersionableEntity { /** * Gets version for artifact. + * * @return version in format suitable for artifact */ public String getVersionForArtifact() { @@ -375,4 +385,29 @@ public class LicenseKeyGroupEntity implements VersionableEntity { public void setManufacturerReferenceNumber(String manufacturerReferenceNumber) { this.manufacturerReferenceNumber = manufacturerReferenceNumber; } + + public String getIsoFormatStartDate() { + mdcDataDebugMessage.debugEntryMessage("start date", startDate); + String isoFormatStartDate = null; + if (!StringUtils.isEmpty(startDate)) { + isoFormatStartDate = VendorLicenseUtil.getIsoFormatDate(startDate); + mdcDataDebugMessage.debugExitMessage("start date", "iso format start date", startDate, + isoFormatStartDate); + } + return isoFormatStartDate; + } + + + public String getIsoFormatExpiryDate() { + mdcDataDebugMessage.debugEntryMessage("expiry date", expiryDate); + String isoFormatExpDate = null; + if (!StringUtils.isEmpty(expiryDate)) { + isoFormatExpDate = VendorLicenseUtil.getIsoFormatDate(expiryDate); + mdcDataDebugMessage.debugExitMessage("expiry date", "iso format expiry date", expiryDate, + isoFormatExpDate); + } + 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/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 58ccd5e608..0860c243b0 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 @@ -47,7 +47,7 @@ public class LimitEntity implements VersionableEntity { } public void setAggregationFunction( - AggregationFunction aggregationFunction) { + AggregationFunction aggregationFunction) { this.aggregationFunction = aggregationFunction; } @@ -159,7 +159,7 @@ public class LimitEntity implements VersionableEntity { @Override public int hashCode() { return Objects.hash(vendorLicenseModelId, version, epLkgId, id, name, description, type, - metric, unit, time, aggregationFunction, value); + metric, unit, time, aggregationFunction, value); } @Override @@ -172,35 +172,35 @@ public class LimitEntity implements VersionableEntity { } 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); + && 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 - - + '}'; + + "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/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 b57b850f60..05cc78f855 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 @@ -45,6 +45,7 @@ public class VendorLicenseModelEntity implements VersionableEntity { @Column(name = "vendor_name") private String vendorName; private String description; + private String oldVersion; @Column(name = "icon") private String iconRef; @@ -111,6 +112,15 @@ public class VendorLicenseModelEntity implements VersionableEntity { 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); 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 3d27de3a88..dda42eeff3 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 @@ -29,72 +29,52 @@ 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.vendorlicense.types.VersionedVendorLicenseModel; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; import java.util.Collection; public interface VendorLicenseFacade { - Version checkin(String vendorLicenseModelId, String user); - - Version submit(String vendorLicenseModelId, String user); - - FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup, String user); - - FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup, String user); - LicenseAgreementEntity getLicenseAgreement(String vlmId, Version version, - String licenseAgreementId, String user); + String licenseAgreementId); LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, - String licenseAgreementId, String user); + String licenseAgreementId); + + LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement); - EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool, String user); + Collection listFeatureGroups(String vlmId, Version version); - void updateEntitlementPool(EntitlementPoolEntity entitlementPool, String user); + FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup); - Collection listLicenseKeyGroups(String vlmId, Version version, - String user); + FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup); - Collection listEntitlementPools(String vlmId, Version version, - String user); + FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup); - void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, String user); + Collection listEntitlementPools(String vlmId, Version version); - LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, String user); + EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool); + void updateEntitlementPool(EntitlementPoolEntity entitlementPool); - VersionedVendorLicenseModel getVendorLicenseModel(String vlmId, Version version, String user); + Collection listLicenseKeyGroups(String vlmId, Version version); - VendorLicenseModelEntity createVendorLicenseModel( - VendorLicenseModelEntity vendorLicenseModelEntity, String user); + LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); + void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); - LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement, - String user); + Collection listLimits(String vlmId, Version version, String epLkgId); - Collection listFeatureGroups(String vlmId, Version version, - String user); + LimitEntity createLimit(LimitEntity limit); - FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup, String user); + void updateLimit(LimitEntity limit); + + VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version); Collection validateLicensingData(String vlmId, Version vlmVersion, String licenseAgreementId, Collection featureGroupIds); - VersionInfo getVersionInfo(String vendorLicenseModelId, VersionableEntityAction action, - String user); - - void updateVlmLastModificationTime(String vendorLicenseModelId, Version version); - - LimitEntity createLimit(LimitEntity limit, String user); - - Collection listLimits(String vlmId, Version version, String epLkgId - ,String user); - - void updateLimit(LimitEntity limit, String user); + 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/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 6ae2de1a63..a3a5b7263f 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 @@ -24,7 +24,7 @@ import org.openecomp.sdc.versioning.dao.types.VersionableEntity; public interface HealingService { - VersionableEntity heal(VersionableEntity toHeal, String user); + VersionableEntity heal(VersionableEntity toHeal); 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 c0610a99cd..66ac7ab33f 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 @@ -28,5 +28,5 @@ import java.util.List; public interface VendorLicenseArtifactsService { FileContentHandler createLicenseArtifacts(String vspId, String vlmId, Version vlmVersion, - List featureGroups, String user); + List featureGroups); } 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/FeatureGroupCassandraDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/FeatureGroupCassandraDaoImpl.java index 2568d719e2..dd22397760 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/FeatureGroupCassandraDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/FeatureGroupCassandraDaoImpl.java @@ -20,8 +20,6 @@ package org.openecomp.sdc.vendorlicense.dao.impl; -import static org.openecomp.core.utilities.CommonMethods.toSingleElementSet; - import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.UDTValue; import com.datastax.driver.mapping.Mapper; @@ -47,6 +45,8 @@ import java.util.Collections; import java.util.HashSet; import java.util.Set; +import static org.openecomp.core.utilities.CommonMethods.toSingleElementSet; + public class FeatureGroupCassandraDaoImpl extends CassandraBaseDao implements FeatureGroupDao { 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 b880c67cbc..35182a3502 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 @@ -10,25 +10,20 @@ import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDao; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToEntitlementPoolConvertor; import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; -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 org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.util.ArrayList; import java.util.Collection; -import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Set; import java.util.stream.Collectors; -/** - * Created by ayalaben on 3/28/2017. - */ +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; + public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { private ZusammenAdaptor zusammenAdaptor; @@ -48,18 +43,22 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { buildEntitlementPoolElement(entitlementPool, Action.CREATE); ZusammenElement entitlementPoolsElement = - VlmZusammenUtil.buildStructuralElement(StructureElement.EntitlementPools, null); + ZusammenUtil.buildStructuralElement(ElementType.EntitlementPools, Action.IGNORE); + + ZusammenElement limitsElement = + ZusammenUtil.buildStructuralElement(ElementType.Limits, Action.CREATE); + entitlementPoolElement.addSubElement(limitsElement); entitlementPoolsElement.addSubElement(entitlementPoolElement); SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - Optional savedElement = zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + Element epsSavedElement = zusammenAdaptor.saveElement(context, + new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()), entitlementPoolsElement, "Create entitlement pool"); - savedElement.ifPresent(element -> entitlementPool - .setId(element.getSubElements().iterator().next().getElementId().getValue())); + entitlementPool + .setId(epsSavedElement.getSubElements().iterator().next().getElementId().getValue()); } @Override @@ -68,9 +67,8 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { buildEntitlementPoolElement(entitlementPool, Action.UPDATE); SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); Optional epFromDb = zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())); @@ -84,35 +82,33 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { } } - zusammenAdaptor.saveElement(context,elementContext, entitlmentpoolElement, + zusammenAdaptor.saveElement(context, elementContext, entitlmentpoolElement, String.format("Update entitlement pool with id %s", entitlementPool.getId())); } @Override public EntitlementPoolEntity get(EntitlementPoolEntity entitlementPool) { SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(entitlementPool.getVersion())); - + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); + ElementToEntitlementPoolConvertor convertor = new ElementToEntitlementPoolConvertor(); return zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())) - .map(elementInfo -> mapElementInfoToEntitlementPool( - entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion(), elementInfo)) + .map(elementInfo -> { + EntitlementPoolEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(entitlementPool.getVendorLicenseModelId()); + entity.setVersion(entitlementPool.getVersion()); + return entity; + }) .orElse(null); } @Override public void delete(EntitlementPoolEntity entitlementPool) { - SessionContext context = ZusammenUtil.createSessionContext(); - ZusammenElement zusammenElement = new ZusammenElement(); - zusammenElement.setAction(Action.DELETE); - zusammenElement.setElementId(new Id(entitlementPool.getId())); + ZusammenElement zusammenElement = buildElement(new Id(entitlementPool.getId()), Action.DELETE); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = - new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "delete entitlement pool. id:" + entitlementPool.getId() + "."); } @@ -120,28 +116,27 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { @Override public Collection list(EntitlementPoolEntity entitlementPool) { SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(entitlementPool.getVersion())); - + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); + ElementToEntitlementPoolConvertor convertor = new ElementToEntitlementPoolConvertor(); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.EntitlementPools.name()) - .stream().map(elementInfo -> mapElementInfoToEntitlementPool( - entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion(), elementInfo)) - .collect(Collectors.toList()); + .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(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(entitlementPool.getVersion())); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.EntitlementPools.name()) + .listElementsByName(context, elementContext, null, ElementType.EntitlementPools.name()) .size(); } @@ -149,9 +144,8 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { public void removeReferencingFeatureGroup(EntitlementPoolEntity entitlementPool, String referencingFeatureGroupId) { SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())); @@ -173,9 +167,8 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { public void addReferencingFeatureGroup(EntitlementPoolEntity entitlementPool, String referencingFeatureGroupId) { SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())); @@ -199,17 +192,32 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { //not supported } - private ZusammenElement buildEntitlementPoolElement(EntitlementPoolEntity entitlementPool, - Action action) { + @Override + public String getManufacturerReferenceNumber(EntitlementPoolEntity entitlementPoolEntity) { + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = + new ElementContext(entitlementPoolEntity.getVendorLicenseModelId(), + entitlementPoolEntity.getVersion().getId()); - ZusammenElement entitlementPoolElement = new ZusammenElement(); - entitlementPoolElement.setAction(action); - if (entitlementPool.getId() != null) { - entitlementPoolElement.setElementId(new Id(entitlementPool.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"); } + 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("thresholdValue", entitlementPool.getThresholdValue()); info.addProperty("threshold_unit", entitlementPool.getThresholdUnit()); @@ -219,8 +227,8 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { info.addProperty("expiryDate", entitlementPool.getExpiryDate()); entitlementPoolElement.setInfo(info); - if (entitlementPool.getReferencingFeatureGroups() != null - && entitlementPool.getReferencingFeatureGroups().size() > 0) { + if (entitlementPool.getReferencingFeatureGroups() != null + && entitlementPool.getReferencingFeatureGroups().size() > 0) { entitlementPoolElement.setRelations(entitlementPool.getReferencingFeatureGroups().stream() .map(rel -> VlmZusammenUtil .createRelation(RelationType.EntitlmentPoolToReferencingFeatureGroup, rel)) @@ -229,62 +237,5 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { return entitlementPoolElement; } - private EntitlementPoolEntity mapElementInfoToEntitlementPool(String vlmId, Version version, - ElementInfo elementInfo) { - EntitlementPoolEntity entitlmentPool = - new EntitlementPoolEntity(vlmId, version, elementInfo.getId().getValue()); - entitlmentPool.setName(elementInfo.getInfo().getName()); - entitlmentPool.setDescription(elementInfo.getInfo().getDescription()); - entitlmentPool.setVersionUuId(elementInfo.getInfo().getProperty("version_uuid")); - entitlmentPool - .setThresholdValue(elementInfo.getInfo().getProperty("thresholdValue") != null - ? VlmZusammenUtil.toInteger(elementInfo.getInfo().getProperty("thresholdValue")) : null); - - Object threshold_unit = elementInfo.getInfo().getProperty("threshold_unit"); - entitlmentPool.setThresholdUnit( threshold_unit != null ? - ThresholdUnit.valueOf(elementInfo.getInfo().getProperty("threshold_unit")) : null); - entitlmentPool.setIncrements(elementInfo.getInfo().getProperty("increments")); - entitlmentPool.setOperationalScope(getOperationalScopeMultiChoiceOrOther( - elementInfo.getInfo().getProperty("operational_scope"))); - entitlmentPool.setStartDate(elementInfo.getInfo().getProperty("startDate")); - entitlmentPool.setExpiryDate(elementInfo.getInfo().getProperty("expiryDate")); - - if (elementInfo.getRelations() != null && elementInfo.getRelations().size() > 0) { - entitlmentPool - .setReferencingFeatureGroups(elementInfo.getRelations().stream().map(relation -> relation - .getEdge2().getElementId().getValue()).collect(Collectors.toSet())); - } - return entitlmentPool; - } - - private MultiChoiceOrOther getOperationalScopeMultiChoiceOrOther - (Map - operationalScope) { - if(operationalScope != null && !operationalScope.isEmpty()) { - Set choices = new HashSet<>(); - ((List) operationalScope.get("choices")). - forEach(choice -> choices.add(OperationalScope.valueOf(choice))); - - return new MultiChoiceOrOther<>(choices, operationalScope.get("other")==null?null: - (String) operationalScope.get("other")); - } - return null; - } - - @Override - public String getManufacturerReferenceNumber(EntitlementPoolEntity entitlementPoolEntity){ - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPoolEntity.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(entitlementPoolEntity.getVersion())); - 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; - } } 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 aa9e6c7ae0..8dcc964e7d 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 @@ -10,21 +10,22 @@ import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.datatypes.item.Relation; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDao; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToFeatureGroupConvertor; import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; -import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.util.ArrayList; import java.util.Collection; -import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; -/** - * Created by ayalaben on 3/27/2017. - */ +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; + public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { private ZusammenAdaptor zusammenAdaptor; @@ -40,88 +41,86 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { @Override public void create(FeatureGroupEntity featureGroup) { - ZusammenElement featureGroupElement = - buildFeatureGroupElement(featureGroup, Action.CREATE); + ZusammenElement featureGroupElement = buildFeatureGroupElement(featureGroup, Action.CREATE); ZusammenElement featureGroupsElement = - VlmZusammenUtil.buildStructuralElement(StructureElement.FeatureGroups, null); + buildStructuralElement(ElementType.FeatureGroups, Action.IGNORE); featureGroupsElement.addSubElement(featureGroupElement); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - Optional savedElement = zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - featureGroupsElement, "Create feature group"); + SessionContext context = createSessionContext(); + Element featureGroupsSavedElement = zusammenAdaptor.saveElement(context, + new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()), featureGroupsElement, "Create feature group"); - savedElement.ifPresent(element -> featureGroup - .setId(element.getSubElements().iterator().next().getElementId().getValue())); + featureGroup.setId( + featureGroupsSavedElement.getSubElements().iterator().next().getElementId().getValue()); } @Override public void update(FeatureGroupEntity featureGroup) { ZusammenElement featureGroupElement = buildFeatureGroupElement(featureGroup, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), featureGroupElement, + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(featureGroup.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); return zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())) - .map(elementInfo -> mapElementInfoToFeatureGroup( - featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), elementInfo)) + .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) { - SessionContext context = ZusammenUtil.createSessionContext(); - ZusammenElement zusammenElement = new ZusammenElement(); - zusammenElement.setAction(Action.DELETE); - zusammenElement.setElementId(new Id(featureGroup.getId())); - - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(featureGroup.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); + ElementToFeatureGroupConvertor convertor = new ElementToFeatureGroupConvertor(); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.FeatureGroups.name()) - .stream().map(elementInfo -> mapElementInfoToFeatureGroup( - featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), elementInfo)) + .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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(featureGroup.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.FeatureGroups.name()) + .listElementsByName(context, elementContext, null, ElementType.FeatureGroups.name()) .size(); } @@ -138,10 +137,9 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { private void removeRelationToContainedEntity(FeatureGroupEntity featureGroup, String containedEntityId, String containedEntityType) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())); @@ -158,25 +156,23 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { } @Override - public void updateFeatureGroup(FeatureGroupEntity - featureGroup, Set addedEntitlementPools, + public void updateFeatureGroup(FeatureGroupEntity featureGroup, + Set addedEntitlementPools, Set removedEntitlementPools, Set addedLicenseKeyGroups, Set removedLicenseKeyGroups) { ZusammenElement featureGroupElement = buildFeatureGroupElement(featureGroup, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - + 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 = - mapElementInfoToFeatureGroup(featureGroup.getId(), featureGroup.getVersion(), - elementInfo.get()); - - if (!(removedEntitlementPools == null )) { + FeatureGroupEntity currentFeatureGroup = convertor.convert(elementInfo.get()); + currentFeatureGroup.setVendorLicenseModelId(featureGroup.getVendorLicenseModelId()); + currentFeatureGroup.setVersion(featureGroup.getVersion()); + if (!(removedEntitlementPools == null)) { currentFeatureGroup.getEntitlementPoolIds().removeAll(removedEntitlementPools); } if (!(addedEntitlementPools == null)) { @@ -192,22 +188,24 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { .createRelation(RelationType.FeatureGroupToEntitlmentPool, relation)) .collect(Collectors.toList())); - if (! ( removedLicenseKeyGroups == null)) { + if (!(removedLicenseKeyGroups == null)) { currentFeatureGroup.getLicenseKeyGroupIds().removeAll(removedLicenseKeyGroups); } - if (! ( addedLicenseKeyGroups == null)) { + 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())) + 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); @@ -226,10 +224,9 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { @Override public void addReferencingLicenseAgreement(FeatureGroupEntity featureGroup, String licenseAgreementId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())); @@ -247,10 +244,9 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { @Override public void removeReferencingLicenseAgreement(FeatureGroupEntity featureGroup, String licenseAgreementId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())); @@ -268,15 +264,12 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { } private ZusammenElement buildFeatureGroupElement(FeatureGroupEntity featureGroup, Action action) { - - ZusammenElement featureGroupElement = new ZusammenElement(); - featureGroupElement.setAction(action); - if (featureGroup.getId() != null) { - featureGroupElement.setElementId(new Id(featureGroup.getId())); - } + 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()); info.addProperty("manufacturerReferenceNumber", featureGroup.getManufacturerReferenceNumber()); featureGroupElement.setInfo(info); @@ -310,39 +303,5 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { .collect(Collectors.toList())); } return featureGroupElement; - - } - - private FeatureGroupEntity mapElementInfoToFeatureGroup(String vlmId, Version version, - ElementInfo elementInfo) { - FeatureGroupEntity featureGroup = - new FeatureGroupEntity(vlmId, version, elementInfo.getId().getValue()); - featureGroup.setName(elementInfo.getInfo().getName()); - featureGroup.setDescription(elementInfo.getInfo().getDescription()); - featureGroup.setPartNumber(elementInfo.getInfo().getProperty("partNumber")); - featureGroup.setManufacturerReferenceNumber(elementInfo.getInfo() - .getProperty("manufacturerReferenceNumber")); - - Set entitlementPoolIds = new HashSet<>(); - Set licenseAgreements = new HashSet<>(); - Set licenseKeyGroupIds = new HashSet<>(); - - if (elementInfo.getRelations() != null) { - for (Relation relation : elementInfo.getRelations()) { - 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); - - return featureGroup; } } 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 45c831fbd7..0fbac66b58 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 @@ -29,19 +29,21 @@ import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDao; -import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToLicenseAgreementConvertor; import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseTerm; -import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.util.Collection; -import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +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; + public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { @@ -61,16 +63,17 @@ public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { ZusammenElement licenseAgreementElement = buildLicenseAgreementElement(licenseAgreement, Action.CREATE); ZusammenElement licenseAgreementsElement = - VlmZusammenUtil.buildStructuralElement(StructureElement.LicenseAgreements, null); + buildStructuralElement(ElementType.LicenseAgreements, Action.IGNORE); licenseAgreementsElement.addSubElement(licenseAgreementElement); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - Optional savedElement = zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - licenseAgreementsElement, "Create license agreement"); - savedElement.ifPresent(element -> licenseAgreement - .setId(element.getSubElements().iterator().next().getElementId().getValue())); + 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()); } @Override @@ -78,38 +81,36 @@ public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { ZusammenElement licenseAgreementElement = buildLicenseAgreementElement(licenseAgreement, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - licenseAgreementElement, + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(licenseAgreement.getVersion())); - + 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 -> mapElementInfoToLicenseAgreement( - licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion(), elementInfo)) + .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) { - SessionContext context = ZusammenUtil.createSessionContext(); - ZusammenElement zusammenElement = new ZusammenElement(); - zusammenElement.setAction(Action.DELETE); - zusammenElement.setElementId(new Id(licenseAgreement.getId())); - - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + 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() + "."); } @@ -117,30 +118,30 @@ public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { @Override public Collection list(LicenseAgreementEntity licenseAgreement) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(licenseAgreement.getVersion())); - + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId()); + ElementToLicenseAgreementConvertor convertor = new ElementToLicenseAgreementConvertor(); return zusammenAdaptor .listElementsByName(context, elementContext, null, - StructureElement.LicenseAgreements.name()) - .stream().map(elementInfo -> mapElementInfoToLicenseAgreement( - licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion(), elementInfo)) + 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 long count(LicenseAgreementEntity licenseAgreement) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(licenseAgreement.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId()); return zusammenAdaptor.listElementsByName(context, elementContext, null, - StructureElement.LicenseAgreements.name()) + ElementType.LicenseAgreements.name()) .size(); } @@ -151,10 +152,9 @@ public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { @Override public void removeFeatureGroup(LicenseAgreementEntity licenseAgreement, String featureGroupId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId()); Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseAgreement.getId())); @@ -175,23 +175,22 @@ public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { ZusammenElement licenseAgreementElement = buildLicenseAgreementElement(licenseAgreement, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - + 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 = - mapElementInfoToLicenseAgreement(licenseAgreement.getId(), licenseAgreement.getVersion(), - elementInfo.get()); - - if (! (removedFeatureGroupIds == null) ) { + convertor.convert(elementInfo.get()); + currentLicenseAgreement.setVendorLicenseModelId(licenseAgreement.getVendorLicenseModelId()); + currentLicenseAgreement.setVersion(licenseAgreement.getVersion()); + if (!(removedFeatureGroupIds == null)) { currentLicenseAgreement.getFeatureGroupIds().removeAll(removedFeatureGroupIds); } - if (! (addedFeatureGroupIds == null)) { + if (!(addedFeatureGroupIds == null)) { currentLicenseAgreement.getFeatureGroupIds().addAll(addedFeatureGroupIds); } licenseAgreementElement.setRelations(currentLicenseAgreement.getFeatureGroupIds().stream() @@ -203,41 +202,15 @@ public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { } } - private LicenseAgreementEntity mapElementInfoToLicenseAgreement(String vlmId, Version version, - ElementInfo elementInfo) { - LicenseAgreementEntity licenseAgreement = - new LicenseAgreementEntity(vlmId, version, elementInfo.getId().getValue()); - licenseAgreement.setName(elementInfo.getInfo().getName()); - licenseAgreement.setDescription(elementInfo.getInfo().getDescription()); - - licenseAgreement - .setLicenseTerm(getCoiceOrOther(elementInfo.getInfo().getProperty("licenseTerm"))); - licenseAgreement.setRequirementsAndConstrains( - elementInfo.getInfo().getProperty("requirementsAndConstrains")); - if (elementInfo.getRelations() != null && elementInfo.getRelations().size() > 0) { - licenseAgreement.setFeatureGroupIds(elementInfo.getRelations().stream() - .map(relation -> relation.getEdge2().getElementId().getValue()) - .collect(Collectors.toSet())); - } - return licenseAgreement; - } - - private ChoiceOrOther getCoiceOrOther(Map licenseTerm) { - return new ChoiceOrOther(LicenseTerm.valueOf((String) licenseTerm.get("choice")), - (String) licenseTerm.get("other")); - } - - private ZusammenElement buildLicenseAgreementElement(LicenseAgreementEntity licenseAgreement, Action action) { - ZusammenElement licenseAgreementElement = new ZusammenElement(); - licenseAgreementElement.setAction(action); - if (licenseAgreement.getId() != null) { - licenseAgreementElement.setElementId(new Id(licenseAgreement.getId())); - } + 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); 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 976db94f39..4e7aee377a 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 @@ -9,27 +9,22 @@ import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.LicenseKeyGroupDao; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToLicenseKeyGroupConvertor; 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; -import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.util.ArrayList; import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; import java.util.Optional; -import java.util.Set; import java.util.stream.Collectors; -/** - * Created by ayalaben on 3/30/2017. - */ +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; + + public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { private ZusammenAdaptor zusammenAdaptor; @@ -47,18 +42,20 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { ZusammenElement licenseKeyGroupElement = buildLicenseKeyGroupElement(licenseKeyGroup, Action.CREATE); + ZusammenElement limitsElement = buildStructuralElement(ElementType.Limits, Action.CREATE); + licenseKeyGroupElement.addSubElement(limitsElement); + ZusammenElement lkgsElement = - VlmZusammenUtil.buildStructuralElement(StructureElement.LicenseKeyGroups, null); + buildStructuralElement(ElementType.LicenseKeyGroups, Action.IGNORE); lkgsElement.addSubElement(licenseKeyGroupElement); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - Optional savedElement = zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - lkgsElement, "Create license Key Group"); + SessionContext context = createSessionContext(); + Element lkgsSavedElement = zusammenAdaptor.saveElement(context, + new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()), lkgsElement, "Create license Key Group"); - savedElement.ifPresent(element -> licenseKeyGroup - .setId(element.getSubElements().iterator().next().getElementId().getValue())); + licenseKeyGroup + .setId(lkgsSavedElement.getSubElements().iterator().next().getElementId().getValue()); } @Override @@ -66,55 +63,50 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { ZusammenElement licenseKeyGroupElement = buildLicenseKeyGroupElement(licenseKeyGroup, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + 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 (lkgFromDb.isPresent()) { - if( licenseKeyGroupElement.getRelations() == null) { - licenseKeyGroupElement.setRelations(new ArrayList<>()); + if (licenseKeyGroupElement.getRelations() == null) { + licenseKeyGroupElement.setRelations(new ArrayList<>()); } if (lkgFromDb.get().getRelations() != null && lkgFromDb.get().getRelations().size() > 0) { licenseKeyGroupElement.getRelations().addAll(lkgFromDb.get().getRelations()); } } - - zusammenAdaptor.saveElement(context, elementContext, - licenseKeyGroupElement, + zusammenAdaptor.saveElement(context, elementContext, licenseKeyGroupElement, String.format("Update license key group with id %s", licenseKeyGroup.getId())); } @Override public LicenseKeyGroupEntity get(LicenseKeyGroupEntity licenseKeyGroup) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(licenseKeyGroup.getVersion())); - + 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 -> mapElementInfoToLicenseKeyGroup( - licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion(), elementInfo)) + .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) { - SessionContext context = ZusammenUtil.createSessionContext(); - ZusammenElement zusammenElement = new ZusammenElement(); - zusammenElement.setAction(Action.DELETE); - zusammenElement.setElementId(new Id(licenseKeyGroup.getId())); + ZusammenElement zusammenElement = buildElement(new Id(licenseKeyGroup.getId()), Action.DELETE); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "delete license key group. id:" + licenseKeyGroup.getId() + "."); @@ -122,29 +114,29 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { @Override public Collection list(LicenseKeyGroupEntity licenseKeyGroup) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(licenseKeyGroup.getVersion())); - + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()); + ElementToLicenseKeyGroupConvertor convertor = new ElementToLicenseKeyGroupConvertor(); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.LicenseKeyGroups.name()) - .stream().map(elementInfo -> mapElementInfoToLicenseKeyGroup( - licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion(), elementInfo)) + .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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(licenseKeyGroup.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.LicenseKeyGroups.name()) + .listElementsByName(context, elementContext, null, ElementType.LicenseKeyGroups.name()) .size(); } @@ -156,10 +148,9 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { @Override public void removeReferencingFeatureGroup(LicenseKeyGroupEntity licenseKeyGroup, String featureGroupId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()); Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseKeyGroup.getId())); @@ -180,10 +171,9 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { @Override public void addReferencingFeatureGroup(LicenseKeyGroupEntity licenseKeyGroup, String featureGroupId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()); Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseKeyGroup.getId())); @@ -204,18 +194,15 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { private ZusammenElement buildLicenseKeyGroupElement(LicenseKeyGroupEntity licenseKeyGroup, Action action) { - - ZusammenElement lkgElement = new ZusammenElement(); - lkgElement.setAction(action); - if (licenseKeyGroup.getId() != null) { - lkgElement.setElementId(new Id(licenseKeyGroup.getId())); - } + 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("version_uuid", licenseKeyGroup.getVersionUuId()); info.addProperty("operational_scope", licenseKeyGroup.getOperationalScope()); info.addProperty("startDate", licenseKeyGroup.getStartDate()); info.addProperty("expiryDate", licenseKeyGroup.getExpiryDate()); @@ -224,70 +211,15 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { info.addProperty("increments", licenseKeyGroup.getIncrements()); lkgElement.setInfo(info); - if (licenseKeyGroup.getReferencingFeatureGroups() != null - && licenseKeyGroup.getReferencingFeatureGroups().size() > 0) { + if (licenseKeyGroup.getReferencingFeatureGroups() != null + && licenseKeyGroup.getReferencingFeatureGroups().size() > 0) { lkgElement.setRelations(licenseKeyGroup.getReferencingFeatureGroups().stream() .map(rel -> VlmZusammenUtil .createRelation(RelationType.LicenseKeyGroupToReferencingFeatureGroup, rel)) .collect(Collectors.toList())); } - return lkgElement; } - private LicenseKeyGroupEntity mapElementInfoToLicenseKeyGroup(String vlmId, Version version, - ElementInfo elementInfo) { - LicenseKeyGroupEntity licenseKeyGroup = - new LicenseKeyGroupEntity(vlmId, version, elementInfo.getId().getValue()); - licenseKeyGroup.setName(elementInfo.getInfo().getName()); - licenseKeyGroup.setDescription(elementInfo.getInfo().getDescription()); - licenseKeyGroup.setVersionUuId(elementInfo.getInfo().getProperty("version_uuid")); - licenseKeyGroup - .setType(LicenseKeyType.valueOf(elementInfo.getInfo().getProperty("LicenseKeyType"))); - licenseKeyGroup.setVersionUuId(elementInfo.getInfo().getProperty("version_uuid")); - licenseKeyGroup.setOperationalScope(getOperationalScopeMultiChoiceOrOther( - elementInfo.getInfo().getProperty("operational_scope"))); - licenseKeyGroup.setStartDate(elementInfo.getInfo().getProperty("startDate")); - licenseKeyGroup.setExpiryDate(elementInfo.getInfo().getProperty("expiryDate")); - if (elementInfo.getInfo().getProperty("thresholdUnits") != null ){ - licenseKeyGroup.setThresholdUnits(ThresholdUnit.valueOf(elementInfo - .getInfo().getProperty("thresholdUnits"))); - } - if (elementInfo.getInfo().getProperty("thresholdValue") != null ){ - licenseKeyGroup.setThresholdValue(toInteger(elementInfo.getInfo().getProperty - ("thresholdValue"))); - } - licenseKeyGroup.setIncrements(elementInfo.getInfo().getProperty("increments")); - - if (elementInfo.getRelations() != null && elementInfo.getRelations().size() > 0) { - licenseKeyGroup - .setReferencingFeatureGroups(elementInfo.getRelations().stream().map(relation -> relation - .getEdge2().getElementId().getValue()).collect(Collectors.toSet())); - } - return licenseKeyGroup; - } - private MultiChoiceOrOther getOperationalScopeMultiChoiceOrOther - (Map - operationalScope) { - if(operationalScope != null && !operationalScope.isEmpty()) { - Set choices = new HashSet<>(); - ((List) operationalScope.get("choices")) - .forEach(choice -> choices.add(OperationalScope.valueOf(choice))); - - return new MultiChoiceOrOther<>(choices, operationalScope.get("other")==null?null:(String) operationalScope.get("other")); - } - return null; - } - - private Integer toInteger(Object val) { - 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()); - } } 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 78c26c83d3..7b19236409 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 @@ -9,26 +9,30 @@ import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.LimitDao; import org.openecomp.sdc.vendorlicense.dao.types.AggregationFunction; import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; 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.Optional; import java.util.stream.Collectors; +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; + public class LimitZusammenDaoImpl implements LimitDao { - public static final String LIMT_TYPE = "type"; - public static final String METRIC = "metric"; - public static final String AGGREGATIONFUNCTION = "aggregationfunction"; - public static final String TIME = "time"; - public static final String UNIT = "unit"; - public static final String VALUE = "value"; + 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) { @@ -39,36 +43,30 @@ public class LimitZusammenDaoImpl implements LimitDao { public void create(LimitEntity limitEntity) { ZusammenElement limitElement = limitToZusammen(limitEntity, Action.CREATE); - ZusammenElement limitsElement = - VlmZusammenUtil.buildStructuralElement(StructureElement.Limits, null); + ZusammenElement limitsElement = buildStructuralElement(ElementType.Limits, null); limitsElement.setSubElements(Collections.singletonList(limitElement)); - ZusammenElement epLkgElement = - buildZusammenElement(new Id(limitEntity.getEpLkgId()), Action.IGNORE); + ZusammenElement epLkgElement = buildElement(new Id(limitEntity.getEpLkgId()), Action.IGNORE); epLkgElement.setSubElements(Collections.singletonList(limitsElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(limitEntity.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); - Optional savedElement = + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, epLkgElement, "Create limit"); - savedElement.ifPresent(element -> - limitEntity.setId(element.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue())); + limitEntity.setId(savedElement.getSubElements().iterator().next() + .getSubElements().iterator().next().getElementId().getValue()); } @Override public boolean isLimitPresent(LimitEntity limitEntity) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(limitEntity.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(limitEntity.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); Collection elementInfos = zusammenAdaptor.listElementsByName(context, - elementContext, new Id(limitEntity.getEpLkgId()),StructureElement.Limits.name()); + elementContext, new Id(limitEntity.getEpLkgId()), ElementType.Limits.name()); for (ElementInfo elementInfo : elementInfos) { if (elementInfo.getId().getValue().equals(limitEntity.getId())) { @@ -81,20 +79,18 @@ public class LimitZusammenDaoImpl implements LimitDao { @Override public Collection list(LimitEntity limitEntity) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(limitEntity.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(limitEntity.getVersion())); + 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) { + LimitEntity limitEntity) { return zusammenAdaptor .listElementsByName(context, elementContext, new Id(limitEntity.getEpLkgId()), - StructureElement.Limits.name()) + ElementType.Limits.name()) .stream().map(elementInfo -> mapElementInfoToLimit( limitEntity.getVendorLicenseModelId(), limitEntity.getVersion(), limitEntity.getEpLkgId(), elementInfo)) @@ -102,18 +98,18 @@ public class LimitZusammenDaoImpl implements LimitDao { } private LimitEntity mapElementInfoToLimit(String vlmId, Version version, - String epLkgId, ElementInfo elementInfo) { + 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 ? + 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 + 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); @@ -126,25 +122,22 @@ public class LimitZusammenDaoImpl implements LimitDao { } @Override - public void update(LimitEntity entity) { - ZusammenElement limitElement = limitToZusammen(entity, Action.UPDATE); + public void update(LimitEntity limitEntity) { + ZusammenElement limitElement = limitToZusammen(limitEntity, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entity.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); - zusammenAdaptor.saveElement(context,elementContext, limitElement, - String.format("Update limit with id %s", entity.getId())); + zusammenAdaptor.saveElement(context, elementContext, limitElement, + String.format("Update limit with id %s", limitEntity.getId())); } @Override public LimitEntity get(LimitEntity limitEntity) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(limitEntity.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(limitEntity.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); return zusammenAdaptor.getElementInfo(context, elementContext, new Id(limitEntity.getId())) .map(elementInfo -> mapElementInfoToLimit( @@ -154,18 +147,14 @@ public class LimitZusammenDaoImpl implements LimitDao { } @Override - public void delete(LimitEntity entity) { - SessionContext context = ZusammenUtil.createSessionContext(); - ZusammenElement zusammenElement = new ZusammenElement(); - zusammenElement.setAction(Action.DELETE); - zusammenElement.setElementId(new Id(entity.getId())); + public void delete(LimitEntity limitEntity) { + ZusammenElement zusammenElement = buildElement(new Id(limitEntity.getId()), Action.DELETE); - Id itemId = new Id(entity.getVendorLicenseModelId()); + SessionContext context = createSessionContext(); ElementContext elementContext = - new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, zusammenElement, - "delete limit Id:" + entity.getId() + "."); + "delete limit Id:" + limitEntity.getId() + "."); } @Override @@ -173,23 +162,13 @@ public class LimitZusammenDaoImpl implements LimitDao { } - private ZusammenElement limitToZusammen(LimitEntity limit, - Action action) { - ZusammenElement limitElement = buildLimitElement(limit, action); - return limitElement; - } - - private ZusammenElement buildLimitElement(LimitEntity limit, - Action action) { - ZusammenElement limitElement = new ZusammenElement(); - limitElement.setAction(action); - if (limit.getId() != null) { - limitElement.setElementId(new Id(limit.getId())); - } - + 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()); @@ -199,11 +178,4 @@ public class LimitZusammenDaoImpl implements LimitDao { limitElement.setInfo(info); return limitElement; } - - private ZusammenElement buildZusammenElement(Id elementId, Action action) { - ZusammenElement element = new ZusammenElement(); - element.setElementId(elementId); - element.setAction(action); - return element; - } } 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 cd1ef0fbcf..13065515d8 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 @@ -1,23 +1,21 @@ package org.openecomp.sdc.vendorlicense.dao.impl.zusammen; 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 com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.ItemVersion; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.VendorLicenseModelDao; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToVLMGeneralConvertor; import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdc.versioning.VersioningManagerFactory; -import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.types.VersionableEntityMetadata; import org.openecomp.sdc.versioning.types.VersionableEntityStoreType; import java.util.Collection; -import java.util.Date; import java.util.stream.Collectors; public class VendorLicenseModelDaoZusammenImpl implements VendorLicenseModelDao { @@ -31,63 +29,91 @@ public class VendorLicenseModelDaoZusammenImpl implements VendorLicenseModelDao @Override public void registerVersioning(String versionableEntityType) { VersionableEntityMetadata metadata = - new VersionableEntityMetadata(VersionableEntityStoreType.Zusammen, "vlm", null, null); + new VersionableEntityMetadata(VersionableEntityStoreType.Zusammen, "VendorLicenseModel", + null, null); VersioningManagerFactory.getInstance().createInterface() .register(versionableEntityType, metadata); } @Override - public Collection list(VendorLicenseModelEntity entity) { + public Collection list( + VendorLicenseModelEntity vendorLicenseModelEntity) { + + ElementToVLMGeneralConvertor convertor = new ElementToVLMGeneralConvertor(); return zusammenAdaptor.listItems(ZusammenUtil.createSessionContext()).stream() - .map(item -> mapInfoToVlm( - item.getId().getValue(), null, item.getInfo(), - item.getModificationTime(), item.getCreationTime())) + .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(); - Id itemId = zusammenAdaptor.createItem(context, mapVlmToZusammenItemInfo(vendorLicenseModel)); - Id versionId = - zusammenAdaptor.createVersion(context, itemId, null, ZusammenUtil.createFirstVersionData()); + ElementContext elementContext = new ElementContext(vendorLicenseModel.getId(), + vendorLicenseModel.getVersion().getId()); ZusammenElement generalElement = mapVlmToZusammenElement(vendorLicenseModel, Action.CREATE); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, versionId), - generalElement, "Create VSP General Info Element"); - vendorLicenseModel.setId(itemId.getValue());//set id for caller + 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) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vendorLicenseModel.getId()); - Id versionId = VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); - - zusammenAdaptor.updateItem(context, itemId, mapVlmToZusammenItemInfo(vendorLicenseModel)); - ZusammenElement generalElement = mapVlmToZusammenElement(vendorLicenseModel, Action.UPDATE); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, versionId), + + 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(); - Id itemId = new Id(vendorLicenseModel.getId()); - ItemVersion itemVersion = VlmZusammenUtil.getFirstVersion(context, itemId, zusammenAdaptor); - ElementContext elementContext = new ElementContext(itemId, itemVersion.getId(), - VlmZusammenUtil.getVersionTag(vendorLicenseModel.getVersion())); - + ElementContext elementContext = + new ElementContext(vendorLicenseModel.getId(), vendorLicenseModel.getVersion().getId()); + ElementToVLMGeneralConvertor convertor = new ElementToVLMGeneralConvertor(); return zusammenAdaptor - .getElementInfoByName(context, elementContext, null, StructureElement.General.name()) - .map(generalElementInfo -> mapInfoToVlm( - vendorLicenseModel.getId(), vendorLicenseModel.getVersion(), - generalElementInfo.getInfo(), - itemVersion.getModificationTime(), itemVersion.getCreationTime())) + .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); } @@ -96,19 +122,19 @@ public class VendorLicenseModelDaoZusammenImpl implements VendorLicenseModelDao } - private Info mapVlmToZusammenItemInfo(VendorLicenseModelEntity vendorLicenseModel) { + /* private Info mapVlmToZusammenItemInfo(VendorLicenseModelEntity vendorLicenseModel) { Info info = new Info(); info.setName(vendorLicenseModel.getVendorName()); info.setDescription(vendorLicenseModel.getDescription()); - info.addProperty("type", "vlm"); + info.addProperty("type", "VendorLicenseModel"); addVlmToInfo(info, vendorLicenseModel); return info; - } + }*/ private ZusammenElement mapVlmToZusammenElement(VendorLicenseModelEntity vendorLicenseModel, Action action) { ZusammenElement generalElement = - VlmZusammenUtil.buildStructuralElement(StructureElement.General, action); + ZusammenUtil.buildStructuralElement(ElementType.VendorLicenseModel, action); addVlmToInfo(generalElement.getInfo(), vendorLicenseModel); return generalElement; } @@ -117,22 +143,21 @@ public class VendorLicenseModelDaoZusammenImpl implements VendorLicenseModelDao info.addProperty(InfoPropertyName.name.name(), vendorLicenseModel.getVendorName()); info.addProperty(InfoPropertyName.description.name(), vendorLicenseModel.getDescription()); info.addProperty(InfoPropertyName.iconRef.name(), vendorLicenseModel.getIconRef()); + info.addProperty(InfoPropertyName.oldVersion.name(), vendorLicenseModel.getOldVersion()); } - private VendorLicenseModelEntity mapInfoToVlm(String vlmId, Version version, Info info, - Date modificationTime, Date creationTime) { + /*private VendorLicenseModelEntity mapInfoToVlm(String vlmId, Version version, Info info) { VendorLicenseModelEntity vendorLicenseModel = new VendorLicenseModelEntity(vlmId, version); vendorLicenseModel.setVendorName(info.getProperty(InfoPropertyName.name.name())); vendorLicenseModel.setDescription(info.getProperty(InfoPropertyName.description.name())); vendorLicenseModel.setIconRef(info.getProperty(InfoPropertyName.iconRef.name())); - vendorLicenseModel.setWritetimeMicroSeconds( - modificationTime == null ? creationTime.getTime() : modificationTime.getTime()); return vendorLicenseModel; - } + }*/ - private enum InfoPropertyName { + public enum InfoPropertyName { name, description, - iconRef + iconRef, + oldVersion } } 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 f16d0fae67..07a4f87e67 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 @@ -3,49 +3,13 @@ package org.openecomp.sdc.vendorlicense.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; 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.ItemVersion; import com.amdocs.zusammen.datatypes.item.Relation; import com.amdocs.zusammen.datatypes.item.RelationEdge; -import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.vendorlicense.errors.VendorLicenseModelNotFoundErrorBuilder; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionStatus; -import java.util.Optional; import java.util.stream.Collectors; public class VlmZusammenUtil { - static ItemVersion getFirstVersion(SessionContext context, Id itemId, - ZusammenAdaptor zusammenAdaptor) { - Optional itemVersion = zusammenAdaptor.getFirstVersion(context, itemId); - - if (!itemVersion.isPresent()) { - throw new CoreException( - new VendorLicenseModelNotFoundErrorBuilder(itemId.getValue()).build()); - } - return itemVersion.get(); - } - - static Id getFirstVersionId(SessionContext context, Id itemId, ZusammenAdaptor zusammenAdaptor) { - return getFirstVersion(context, itemId, zusammenAdaptor).getId(); - } - - // TODO: 4/25/2017 remove upon working with more than one single version - static String getVersionTag(Version version) { - return version.getStatus() == VersionStatus.Locked - ? null - : version.toString(); - } - - static ZusammenElement buildStructuralElement(StructureElement structureElement, Action action) { - return ZusammenUtil.buildStructuralElement(structureElement.name(), action); - } - static ZusammenElement getZusammenElement(ElementInfo elementInfo) { ZusammenElement zusammenElement = new ZusammenElement(); zusammenElement.setElementId(elementInfo.getId()); @@ -67,6 +31,9 @@ public class VlmZusammenUtil { } public static Integer toInteger(Object val) { + if (val == null) { + return null; + } if (val instanceof Double) { return ((Double) val).intValue(); } else if (val instanceof String) { 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 new file mode 100644 index 0000000000..75fc6f2605 --- /dev/null +++ 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 @@ -0,0 +1,95 @@ +package org.openecomp.sdc.vendorlicense.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 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.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; + + +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; + } + 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; + } + + private void mapInfoToEntitlementPoolEntity(EntitlementPoolEntity entitlementPool, Info info) { + entitlementPool.setName(info.getName()); + entitlementPool.setDescription(info.getDescription()); + entitlementPool.setVersionUuId(info.getProperty("version_uuid")); + 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")); + } + + 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 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 new file mode 100644 index 0000000000..e39c22e569 --- /dev/null +++ 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 @@ -0,0 +1,83 @@ +package org.openecomp.sdc.vendorlicense.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 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; + + +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; + } + 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; + } + + + 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 mapInfoToFeatureGroup(FeatureGroupEntity featureGroup, Info info) { + featureGroup.setName(info.getName()); + featureGroup.setDescription(info.getDescription()); + featureGroup.setPartNumber(info.getProperty("partNumber")); + featureGroup.setManufacturerReferenceNumber(info.getProperty("manufacturerReferenceNumber")); + } + + 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); + } +} 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 new file mode 100644 index 0000000000..a0caa0cf5b --- /dev/null +++ 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 @@ -0,0 +1,86 @@ +package org.openecomp.sdc.vendorlicense.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 com.amdocs.zusammen.datatypes.item.Relation; +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; + } + 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())); + } + + } + + 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 new file mode 100644 index 0000000000..5956c3e6f1 --- /dev/null +++ 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 @@ -0,0 +1,104 @@ +package org.openecomp.sdc.vendorlicense.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 com.amdocs.zusammen.datatypes.item.Relation; +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; + +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; + + +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; + } + 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)); + + licenseKeyGroup.setThresholdValue(toInteger(info.getProperty("thresholdValue"))); + licenseKeyGroup.setIncrements(info.getProperty("increments")); + } + + 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 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 new file mode 100644 index 0000000000..4b2370aea1 --- /dev/null +++ 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 @@ -0,0 +1,44 @@ +package org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; +import org.openecomp.sdc.vendorlicense.dao.types.LimitType; + +/** + * Created by ayalaben on 9/26/2017 + */ +public class ElementToLimitConvertor extends ElementConvertor { + @Override + public Object 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")); + + 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); + } + } +} 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 new file mode 100644 index 0000000000..c2ef5a6c41 --- /dev/null +++ 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 @@ -0,0 +1,52 @@ +package org.openecomp.sdc.vendorlicense.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 com.amdocs.zusammen.datatypes.item.Item; +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())); + vendorLicenseModelEntity.setOldVersion(info.getProperty( + VendorLicenseModelDaoZusammenImpl.InfoPropertyName.oldVersion.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/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 b2f2d488e9..0898e48b54 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 @@ -20,18 +20,12 @@ package org.openecomp.sdc.vendorlicense.facade.impl; -import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE; -import static org.openecomp.sdc.vendorlicense.errors.UncompletedVendorLicenseModelErrorType.SUBMIT_UNCOMPLETED_VLM_MSG_FG_MISSING_EP; -import static org.openecomp.sdc.vendorlicense.errors.UncompletedVendorLicenseModelErrorType.SUBMIT_UNCOMPLETED_VLM_MSG_LA_MISSING_FG; - import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.util.UniqueValueUtil; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; @@ -62,23 +56,21 @@ import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdc.vendorlicense.errors.SubmitUncompletedLicenseModelErrorBuilder; import org.openecomp.sdc.vendorlicense.errors.VendorLicenseModelNotFoundErrorBuilder; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; -import org.openecomp.sdc.vendorlicense.types.VersionedVendorLicenseModel; -import org.openecomp.sdc.versioning.VersioningManager; -import org.openecomp.sdc.versioning.VersioningManagerFactory; import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder; import org.openecomp.sdc.versioning.errors.VersionableSubEntityNotFoundErrorBuilder; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; -public class VendorLicenseFacadeImpl implements VendorLicenseFacade { - - private static final VersioningManager versioningManager = - VersioningManagerFactory.getInstance().createInterface(); +import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE; +import static org.openecomp.sdc.vendorlicense.errors.UncompletedVendorLicenseModelErrorType.SUBMIT_UNCOMPLETED_VLM_MSG_FG_MISSING_EP; +import static org.openecomp.sdc.vendorlicense.errors.UncompletedVendorLicenseModelErrorType.SUBMIT_UNCOMPLETED_VLM_MSG_LA_MISSING_FG; +public class VendorLicenseFacadeImpl implements VendorLicenseFacade { private static final VendorLicenseModelDao vendorLicenseModelDao = VendorLicenseModelDaoFactory.getInstance().createInterface(); private static final LicenseAgreementDao @@ -91,7 +83,6 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { licenseKeyGroupDao = LicenseKeyGroupDaoFactory.getInstance().createInterface(); private static final LimitDao limitDao = LimitDaoFactory.getInstance().createInterface(); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); /** * Instantiates a new Vendor license facade. @@ -106,32 +97,7 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { } @Override - public Version checkin(String vendorLicenseModelId, String user) { - Version newVersion = versioningManager - .checkin(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vendorLicenseModelId, user, null); - updateVlmLastModificationTime(vendorLicenseModelId, newVersion); - return newVersion; - } - - @Override - public Version submit(String vendorLicenseModelId, String user) { - validateCompletedVendorLicenseModel(vendorLicenseModelId, user); - Version newVersion = versioningManager - .submit(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vendorLicenseModelId, user, null); - updateVlmLastModificationTime(vendorLicenseModelId, newVersion); - return newVersion; - } - - @Override - public FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup, String user) { - Version version = VersioningUtil.resolveVersion(featureGroup.getVersion(), - getVersionInfo(featureGroup.getVendorLicenseModelId(), VersionableEntityAction.Read, - user), user); - featureGroup.setVersion(version); - return getFeatureGroup(featureGroup); - } - - private FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup) { + public FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup) { FeatureGroupEntity retrieved = featureGroupDao.get(featureGroup); VersioningUtil .validateEntityExistence(retrieved, featureGroup, VendorLicenseModelEntity.ENTITY_TYPE); @@ -142,8 +108,8 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { } @Override - public FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup, String user) { - FeatureGroupEntity retrieved = getFeatureGroup(featureGroup, user); + public FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup) { + FeatureGroupEntity retrieved = getFeatureGroup(featureGroup); FeatureGroupModel featureGroupModel = new FeatureGroupModel(); featureGroupModel.setFeatureGroup(retrieved); @@ -164,9 +130,9 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { @Override public LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, - String licenseAgreementId, String user) { + String licenseAgreementId) { LicenseAgreementEntity retrieved = - getLicenseAgreement(vlmId, version, licenseAgreementId, user); + getLicenseAgreement(vlmId, version, licenseAgreementId); LicenseAgreementModel licenseAgreementModel = new LicenseAgreementModel(); licenseAgreementModel.setLicenseAgreement(retrieved); @@ -180,103 +146,71 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { } @Override - public EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool, - String user) { - entitlementPool.setVersion(VersioningUtil.resolveVersion(entitlementPool.getVersion(), - getVersionInfo(entitlementPool.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user)); - //entitlementPool.setId(CommonMethods.nextUuId()); + public EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool) { entitlementPool.setVersionUuId(CommonMethods.nextUuId()); UniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.ENTITLEMENT_POOL_NAME, - entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().toString(), + entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().getId(), entitlementPool.getName()); entitlementPoolDao.create(entitlementPool); - updateVlmLastModificationTime(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion()); return entitlementPool; } @Override - public void updateEntitlementPool(EntitlementPoolEntity entitlementPool, String user) { - entitlementPool.setVersion(VersioningUtil.resolveVersion(entitlementPool.getVersion(), - getVersionInfo(entitlementPool.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user)); + 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().toString()); + entitlementPool.getVersion().getId()); entitlementPool.setVersionUuId(CommonMethods.nextUuId()); entitlementPoolDao.update(entitlementPool); - - updateVlmLastModificationTime(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion()); - } @Override - public Collection listLicenseKeyGroups(String vlmId, Version version, - String user) { - return licenseKeyGroupDao.list(new LicenseKeyGroupEntity(vlmId, VersioningUtil - .resolveVersion(version, getVersionInfo(vlmId, VersionableEntityAction.Read, user), user), - null)); + public Collection listLicenseKeyGroups(String vlmId, Version version) { + return licenseKeyGroupDao.list(new LicenseKeyGroupEntity(vlmId, version, null)); } @Override - public Collection listEntitlementPools(String vlmId, Version version, - String user) { - return entitlementPoolDao.list(new EntitlementPoolEntity(vlmId, VersioningUtil - .resolveVersion(version, getVersionInfo(vlmId, VersionableEntityAction.Read, user), user), - null)); + public Collection listEntitlementPools(String vlmId, Version version) { + return entitlementPoolDao.list(new EntitlementPoolEntity(vlmId, version, null)); } @Override - public void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, String user) { - licenseKeyGroup.setVersion(VersioningUtil.resolveVersion(licenseKeyGroup.getVersion(), - getVersionInfo(licenseKeyGroup.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user)); + 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().toString()); + licenseKeyGroup.getVersion().getId()); licenseKeyGroupDao.update(licenseKeyGroup); - - updateVlmLastModificationTime(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion()); } @Override - public LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, - String user) { - licenseKeyGroup.setVersion(VersioningUtil.resolveVersion(licenseKeyGroup.getVersion(), - getVersionInfo(licenseKeyGroup.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user)); - //licenseKeyGroup.setId(CommonMethods.nextUuId()); + public LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { licenseKeyGroup.setVersionUuId(CommonMethods.nextUuId()); UniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_KEY_GROUP_NAME, - licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().toString(), + licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().getId(), licenseKeyGroup.getName()); licenseKeyGroupDao.create(licenseKeyGroup); - updateVlmLastModificationTime(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion()); return licenseKeyGroup; } @Override - public VersionedVendorLicenseModel getVendorLicenseModel(String vlmId, Version version, - String user) { + public VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version) { mdcDataDebugMessage.debugEntryMessage("VLM id", vlmId); - VersionInfo versionInfo = getVersionInfo(vlmId, VersionableEntityAction.Read, user); - - VendorLicenseModelEntity vendorLicenseModel = vendorLicenseModelDao.get( - new VendorLicenseModelEntity(vlmId, - VersioningUtil.resolveVersion(version, versionInfo, user))); + VendorLicenseModelEntity vendorLicenseModel = + vendorLicenseModelDao.get(new VendorLicenseModelEntity(vlmId, version)); if (vendorLicenseModel == null) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.GET_VLM, ErrorLevel.ERROR.name(), @@ -285,90 +219,61 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { } mdcDataDebugMessage.debugExitMessage("VLM id", vlmId); - return new VersionedVendorLicenseModel(vendorLicenseModel, versionInfo); - } - - @Override - public VendorLicenseModelEntity createVendorLicenseModel( - VendorLicenseModelEntity vendorLicenseModelEntity, String user) { - - mdcDataDebugMessage.debugEntryMessage(null, null); - - UniqueValueUtil.validateUniqueValue(VendorLicenseConstants.UniqueValues.VENDOR_NAME, - vendorLicenseModelEntity.getVendorName()); - //vendorLicenseModelEntity.setId(CommonMethods.nextUuId()); - - vendorLicenseModelDao.create(vendorLicenseModelEntity); - UniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.VENDOR_NAME, - vendorLicenseModelEntity.getVendorName()); - - Version version = versioningManager - .create(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vendorLicenseModelEntity.getId(), user); - vendorLicenseModelEntity.setVersion(version); - - mdcDataDebugMessage.debugExitMessage(null, null); - return vendorLicenseModelEntity; + return vendorLicenseModel; } @Override - public LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement, - String user) { - Version version = VersioningUtil.resolveVersion(licenseAgreement.getVersion(), - getVersionInfo(licenseAgreement.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user); - licenseAgreement.setVersion(version); + public LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement) { //licenseAgreement.setId(CommonMethods.nextUuId()); VersioningUtil.validateEntitiesExistence(licenseAgreement.getFeatureGroupIds(), - new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), version, null), + new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion(), + null), featureGroupDao, VendorLicenseModelEntity.ENTITY_TYPE); UniqueValueUtil.validateUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME, - licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().toString(), + licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId(), licenseAgreement.getName()); licenseAgreementDao.create(licenseAgreement); UniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME, - licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().toString(), + licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId(), licenseAgreement.getName()); if (licenseAgreement.getFeatureGroupIds() != null) { for (String addedFgId : licenseAgreement.getFeatureGroupIds()) { featureGroupDao.addReferencingLicenseAgreement( - new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), version, + new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion(), addedFgId), licenseAgreement.getId()); } } - updateVlmLastModificationTime(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion()); - return licenseAgreement; } @Override - public FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup, String user) { - Version version = VersioningUtil.resolveVersion(featureGroup.getVersion(), - getVersionInfo(featureGroup.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user); - //featureGroup.setId(CommonMethods.nextUuId()); - featureGroup.setVersion(version); + public FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup) { VersioningUtil.validateEntitiesExistence(featureGroup.getLicenseKeyGroupIds(), - new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), version, null), + new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), + null), licenseKeyGroupDao, VendorLicenseModelEntity.ENTITY_TYPE); VersioningUtil.validateEntitiesExistence(featureGroup.getEntitlementPoolIds(), - new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), version, null), + new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), + null), entitlementPoolDao, VendorLicenseModelEntity.ENTITY_TYPE); UniqueValueUtil.validateUniqueValue(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME, - featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().toString(), + featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId(), featureGroup.getName()); featureGroupDao.create(featureGroup); UniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME, - featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().toString(), + featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId(), featureGroup.getName()); if (featureGroup.getLicenseKeyGroupIds() != null) { for (String addedLkgId : featureGroup.getLicenseKeyGroupIds()) { licenseKeyGroupDao.addReferencingFeatureGroup( - new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), version, addedLkgId), + new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion(), addedLkgId), featureGroup.getId()); } } @@ -376,27 +281,20 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { if (featureGroup.getEntitlementPoolIds() != null) { for (String addedEpId : featureGroup.getEntitlementPoolIds()) { entitlementPoolDao.addReferencingFeatureGroup( - new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), version, addedEpId), - featureGroup.getId()); + new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion(), addedEpId), featureGroup.getId()); } } - - updateVlmLastModificationTime(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion()); - return featureGroup; } @Override - public Collection listFeatureGroups(String vlmId, Version version, - String user) { + public Collection listFeatureGroups(String vlmId, Version version) { Collection featureGroupEntities = - featureGroupDao.list(new FeatureGroupEntity(vlmId, VersioningUtil - .resolveVersion(version, getVersionInfo(vlmId, VersionableEntityAction.Read, user), - user), null)); + featureGroupDao.list(new FeatureGroupEntity(vlmId, version, null)); featureGroupEntities.stream() .filter(fgEntity -> Objects.isNull(fgEntity.getManufacturerReferenceNumber())) - .forEach(fgEntity -> updateManufacturerNumberInFeatureGroup(fgEntity)); + .forEach(this::updateManufacturerNumberInFeatureGroup); return featureGroupEntities; } @@ -405,23 +303,22 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { public Collection validateLicensingData(String vlmId, Version version, String licenseAgreementId, Collection featureGroupIds) { - try { + // TODO: 5/21/2017 validate version exists and final +/* try { VersionInfo versionInfo = getVersionInfo(vlmId, VersionableEntityAction.Read, ""); if (version == null || !version.isFinal() || !versionInfo.getViewableVersions().contains(version)) { return Collections.singletonList(new RequestedVersionInvalidErrorBuilder().build()); } } catch (CoreException exception) { - log.debug("",exception); return Collections.singletonList(exception.code()); - } + }*/ List errorMessages = new ArrayList<>(); try { - getLicenseAgreement(vlmId, licenseAgreementId, version); + getLicenseAgreement(vlmId, version, licenseAgreementId); } catch (CoreException exception) { - log.debug("",exception); errorMessages.add(exception.code()); } @@ -438,7 +335,6 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { version).build()); } } catch (CoreException exception) { - log.debug("",exception); errorMessages.add(exception.code()); } } @@ -447,71 +343,34 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { } @Override - public VersionInfo getVersionInfo(String vendorLicenseModelId, VersionableEntityAction action, - String user) { - return versioningManager - .getEntityVersionInfo(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vendorLicenseModelId, user, - action); + 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 updateVlmLastModificationTime(String vendorLicenseModelId, Version version) { - VendorLicenseModelEntity retrieved = - vendorLicenseModelDao.get(new VendorLicenseModelEntity(vendorLicenseModelId, version)); - vendorLicenseModelDao.update(retrieved); + public Collection listLimits(String vlmId, Version version, String epLkgId) { + return limitDao.list(new LimitEntity(vlmId, version, epLkgId, null)); } @Override - public LicenseAgreementEntity getLicenseAgreement(String vlmId, Version version, - String licenseAgreementId, String user) { - return getLicenseAgreement(vlmId, licenseAgreementId, VersioningUtil - .resolveVersion(version, getVersionInfo(vlmId, VersionableEntityAction.Read, user), user)); - } - - @Override - public LimitEntity createLimit(LimitEntity limit, String user) { - limit.setVersion(VersioningUtil.resolveVersion(limit.getVersion(), - getVersionInfo(limit.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user)); - //limit.setVersionUuId(CommonMethods.nextUuId()); + public LimitEntity createLimit(LimitEntity limit) { limitDao.create(limit); - updateVlmLastModificationTime(limit.getVendorLicenseModelId(), - limit.getVersion()); return limit; } @Override - public Collection listLimits(String vlmId, Version version, String epLkgId, - String user) { - return limitDao.list(new LimitEntity(vlmId, VersioningUtil - .resolveVersion(version, getVersionInfo(vlmId, VersionableEntityAction.Read, user), user), - epLkgId, null)); - - } - - @Override - public void updateLimit(LimitEntity limit, String user) { - limit.setVersion(VersioningUtil.resolveVersion(limit.getVersion(), - getVersionInfo(limit.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user)); - //limit.setVersionUuId(CommonMethods.nextUuId()); + public void updateLimit(LimitEntity limit) { limitDao.update(limit); - updateVlmLastModificationTime(limit.getVendorLicenseModelId(), - limit.getVersion()); - } - - private LicenseAgreementEntity getLicenseAgreement(String vlmId, String licenseAgreementId, - Version version) { - LicenseAgreementEntity input = new LicenseAgreementEntity(vlmId, version, licenseAgreementId); - LicenseAgreementEntity retrieved = licenseAgreementDao.get(input); - VersioningUtil.validateEntityExistence(retrieved, input, VendorLicenseModelEntity.ENTITY_TYPE); - return retrieved; } private void updateManufacturerNumberInFeatureGroup(FeatureGroupEntity featureGroupEntity) { if (CollectionUtils.isNotEmpty(featureGroupEntity.getEntitlementPoolIds())) { Object[] entitlementPoolIdsList = featureGroupEntity.getEntitlementPoolIds().toArray(); - if (entitlementPoolIdsList != null && entitlementPoolIdsList.length > 0) { + if (entitlementPoolIdsList.length > 0) { String entitlementPoolId = entitlementPoolIdsList[0].toString(); EntitlementPoolEntity entitlementPoolEntity = new EntitlementPoolEntity(featureGroupEntity.getVendorLicenseModelId(), @@ -523,35 +382,40 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { } } } - private void validateCompletedVendorLicenseModel(String vendorLicenseModelId, String user) { + + @Override + public void validate(String vendorLicenseModelId, Version version) { Collection allFeatureGroupEntities = new HashSet<>(); - Version version = VersioningUtil.resolveVersion(null, - getVersionInfo(vendorLicenseModelId, VersionableEntityAction.Read, user), user); Collection licenseAgreements = licenseAgreementDao - .list(new LicenseAgreementEntity(vendorLicenseModelId, version, null)); + .list(new LicenseAgreementEntity(vendorLicenseModelId, version, null)); if (CollectionUtils.isNotEmpty(licenseAgreements)) { licenseAgreements.forEach(licenseAgreement -> { if (CollectionUtils.isEmpty(licenseAgreement.getFeatureGroupIds())) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.SUBMIT_ENTITY, ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.SUBMIT_ENTITY); + LoggerTragetServiceName.SUBMIT_ENTITY, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.SUBMIT_ENTITY); throw new CoreException( - new SubmitUncompletedLicenseModelErrorBuilder(SUBMIT_UNCOMPLETED_VLM_MSG_LA_MISSING_FG).build()); + 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())) { + FeatureGroupEntity featureGroupEntity = + featureGroupDao.get(new FeatureGroupEntity(vendorLicenseModelId, version, fg)); + if (CollectionUtils.isEmpty(featureGroupEntity.getEntitlementPoolIds())) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.SUBMIT_ENTITY, ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.SUBMIT_ENTITY); + LoggerTragetServiceName.SUBMIT_ENTITY, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.SUBMIT_ENTITY); throw new CoreException( - new SubmitUncompletedLicenseModelErrorBuilder(SUBMIT_UNCOMPLETED_VLM_MSG_FG_MISSING_EP).build()); + 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 7cb3e2e844..c62061e529 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 @@ -40,14 +40,14 @@ import java.util.UUID; public class SimpleHealingServiceImpl implements HealingService { private static final EntitlementPoolDao entitlementPoolDao = - EntitlementPoolDaoFactory.getInstance().createInterface(); + EntitlementPoolDaoFactory.getInstance().createInterface(); private static final LicenseKeyGroupDao licenseKeyGroupDao = - LicenseKeyGroupDaoFactory.getInstance().createInterface(); + LicenseKeyGroupDaoFactory.getInstance().createInterface(); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); @Override - public VersionableEntity heal(VersionableEntity toHeal, String user) { - return handleMissingVersionId(toHeal, user); + public VersionableEntity heal(VersionableEntity toHeal) { + return handleMissingVersionId(toHeal); } @Override @@ -59,10 +59,10 @@ public class SimpleHealingServiceImpl implements HealingService { } } - private VersionableEntity handleMissingVersionId(VersionableEntity toHeal, String user) { + private VersionableEntity handleMissingVersionId(VersionableEntity toHeal) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); if (toHeal != null && toHeal.getVersionUuId() != null) { return toHeal; @@ -76,13 +76,13 @@ public class SimpleHealingServiceImpl implements HealingService { licenseKeyGroupDao.update((LicenseKeyGroupEntity) toHeal); } else { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.SELF_HEALING, ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.UNSUPPORTED_OPERATION); + LoggerTragetServiceName.SELF_HEALING, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.UNSUPPORTED_OPERATION); throw new UnsupportedOperationException( - "Unsupported operation for 1610 release/1607->1610 migration."); + "Unsupported operation for 1610 release/1607->1610 migration."); } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); 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 6dbed22db5..07f19b1e2b 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 @@ -20,9 +20,6 @@ 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 org.apache.commons.collections.CollectionUtils; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; @@ -58,15 +55,14 @@ import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorL public class VendorLicenseArtifactsServiceImpl implements VendorLicenseArtifactsService { public static final VendorLicenseFacade vendorLicenseFacade = - VendorLicenseFacadeFactory.getInstance().createInterface(); + VendorLicenseFacadeFactory.getInstance().createInterface(); public static final HealingService healingService = - HealingServiceFactory.getInstance().createInterface(); + HealingServiceFactory.getInstance().createInterface(); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private static byte[] createVnfArtifact(String vspId, String vlmId, Version vlmVersion, - String vendorName, - List featureGroups, String user) { + private static byte[] createVnfArtifact(String vspId, String vlmId, Version vlmVersion, String vendorName, + List featureGroups) { mdcDataDebugMessage.debugEntryMessage("VLM name", vendorName); @@ -78,30 +74,31 @@ public class VendorLicenseArtifactsServiceImpl implements VendorLicenseArtifacts if (featureGroups != null) { for (String featureGroupId : featureGroups) { FeatureGroupModel featureGroupModel = vendorLicenseFacade - .getFeatureGroupModel(new FeatureGroupEntity(vlmId, vlmVersion, featureGroupId), user); + .getFeatureGroupModel(new FeatureGroupEntity(vlmId, vlmVersion, featureGroupId)); Set entitlementPoolEntities = - featureGroupModel.getEntitlementPools(); + featureGroupModel.getEntitlementPools(); for (EntitlementPoolEntity entitlementPoolEntity : entitlementPoolEntities) { entitlementPoolEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, vlmVersion, - entitlementPoolEntity.getId(), user)); + entitlementPoolEntity.getId())); entitlementPoolEntity.setManufacturerReferenceNumber(featureGroupModel. - getEntityManufacturerReferenceNumber()); + getEntityManufacturerReferenceNumber()); } + Set licenseKeyGroupEntities = - featureGroupModel.getLicenseKeyGroups(); + featureGroupModel.getLicenseKeyGroups(); for (LicenseKeyGroupEntity licenseKeyGroupEntity : licenseKeyGroupEntities) { licenseKeyGroupEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, vlmVersion, - licenseKeyGroupEntity.getId(), user)); + licenseKeyGroupEntity.getId())); licenseKeyGroupEntity.setManufacturerReferenceNumber(featureGroupModel. - getEntityManufacturerReferenceNumber()); + getEntityManufacturerReferenceNumber()); } featureGroupModel.setEntitlementPools(entitlementPoolEntities.stream().map( - entitlementPoolEntity -> (EntitlementPoolEntity) healingService - .heal(entitlementPoolEntity, user)).collect(Collectors.toSet())); + entitlementPoolEntity -> (EntitlementPoolEntity) healingService + .heal(entitlementPoolEntity)).collect(Collectors.toSet())); featureGroupModel.setLicenseKeyGroups(licenseKeyGroupEntities.stream().map( - licenseKeyGroupEntity -> (LicenseKeyGroupEntity) healingService - .heal(licenseKeyGroupEntity, user)).collect(Collectors.toSet())); + licenseKeyGroupEntity -> (LicenseKeyGroupEntity) healingService + .heal(licenseKeyGroupEntity)).collect(Collectors.toSet())); artifact.getFeatureGroups().add(featureGroupModel); } } @@ -110,7 +107,7 @@ public class VendorLicenseArtifactsServiceImpl implements VendorLicenseArtifacts return artifact.toXml().getBytes(); } - private static byte[] createVendorLicenseArtifact(String vlmId, String vendorName, String user) { + private static byte[] createVendorLicenseArtifact(String vlmId, String vendorName) { mdcDataDebugMessage.debugEntryMessage("VLM name", vendorName); @@ -122,40 +119,37 @@ public class VendorLicenseArtifactsServiceImpl implements VendorLicenseArtifacts List finalVersions = getFinalVersionsForVlm(vlmId); for (Version finalVersion : finalVersions) { - Collection coll = vendorLicenseFacade.listEntitlementPools(vlmId, - finalVersion, user); - coll.stream().forEach(entitlementPoolEntity -> { + Collection eps = + vendorLicenseFacade.listEntitlementPools(vlmId, finalVersion); + eps.forEach(entitlementPoolEntity -> { entitlementPoolEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, finalVersion, - entitlementPoolEntity.getId(), user)); + entitlementPoolEntity.getId())); Optional manufacturerReferenceNumber = getFeatureGroupManufactureRefNumber - (entitlementPoolEntity.getReferencingFeatureGroups(), vlmId, finalVersion, user); + (entitlementPoolEntity.getReferencingFeatureGroups(), vlmId, finalVersion); manufacturerReferenceNumber - .ifPresent(entitlementPoolEntity::setManufacturerReferenceNumber); + .ifPresent(entitlementPoolEntity::setManufacturerReferenceNumber); }); + entitlementPoolEntities.addAll(eps); - entitlementPoolEntities.addAll(coll); + Collection lkgs = + vendorLicenseFacade.listLicenseKeyGroups(vlmId, finalVersion); - Collection coll2 = vendorLicenseFacade.listLicenseKeyGroups(vlmId, - finalVersion, user); - - coll2.stream().forEach(licenseKeyGroupEntity -> { + lkgs.forEach(licenseKeyGroupEntity -> { licenseKeyGroupEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, finalVersion, - licenseKeyGroupEntity.getId(), user)); + licenseKeyGroupEntity.getId())); Optional manufacturerReferenceNumber = getFeatureGroupManufactureRefNumber - (licenseKeyGroupEntity.getReferencingFeatureGroups(), vlmId, finalVersion, user); + (licenseKeyGroupEntity.getReferencingFeatureGroups(), vlmId, finalVersion); manufacturerReferenceNumber - .ifPresent(licenseKeyGroupEntity::setManufacturerReferenceNumber); + .ifPresent(licenseKeyGroupEntity::setManufacturerReferenceNumber); }); - - licenseKeyGroupEntities.addAll(coll2); + licenseKeyGroupEntities.addAll(lkgs); } + entitlementPoolEntities = - healEPs(user, filterChangedEntities(prepareForFiltering(entitlementPoolEntities, user, - true))); + healEPs(filterChangedEntities(prepareForFiltering(entitlementPoolEntities, true))); licenseKeyGroupEntities = - healLkgs(user, filterChangedEntities(prepareForFiltering(licenseKeyGroupEntities, user, - false))); + healLkgs(filterChangedEntities(prepareForFiltering(licenseKeyGroupEntities, false))); vendorLicenseArtifact.setEntitlementPoolEntities(entitlementPoolEntities); vendorLicenseArtifact.setLicenseKeyGroupEntities(licenseKeyGroupEntities); @@ -165,21 +159,20 @@ public class VendorLicenseArtifactsServiceImpl implements VendorLicenseArtifacts private static Optional getFeatureGroupManufactureRefNumber(Set featureGroupIds, String vlmId, - Version finalVersion, - String user) { + 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()), user); + vendorLicenseFacade.getFeatureGroup(new FeatureGroupEntity(vlmId, finalVersion, + featureGroupIdsList[0].toString())); manufactureReferenceNumber = featureGroup != null ? featureGroup - .getManufacturerReferenceNumber() : null; + .getManufacturerReferenceNumber() : null; } } return manufactureReferenceNumber != null ? Optional.of(manufactureReferenceNumber) : - Optional.empty(); + Optional.empty(); } @@ -190,22 +183,21 @@ public class VendorLicenseArtifactsServiceImpl implements VendorLicenseArtifacts * @param vlmId vlmId * @param vlmVersion vlmVersion * @param featureGroups featureGroups - * @param user user * @return FileContentHandler */ public FileContentHandler createLicenseArtifacts(String vspId, String vlmId, Version vlmVersion, - List featureGroups, String user) { + List featureGroups) { mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); FileContentHandler artifacts = new FileContentHandler(); - String vendorName = getVendorName(vlmId, user); + String vendorName = getVendorName(vlmId); artifacts.addFile(VNF_ARTIFACT_NAME_WITH_PATH, - createVnfArtifact(vspId, vlmId, vlmVersion, vendorName, featureGroups, user)); + createVnfArtifact(vspId, vlmId, vlmVersion, vendorName, featureGroups)); artifacts.addFile(VENDOR_LICENSE_MODEL_ARTIFACT_NAME_WITH_PATH, - createVendorLicenseArtifact(vlmId, vendorName, user)); + createVendorLicenseArtifact(vlmId, vendorName)); mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); 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 b2cb710eec..91a73b6377 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 @@ -38,11 +38,11 @@ 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; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; @JacksonXmlRootElement(localName = "vf-license-model", namespace = "http://xmlns.openecomp.org/asdc/license-model/1.0") 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 ac45528acd..70ef26f573 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 @@ -62,12 +62,18 @@ public abstract class MixinEntitlementPoolEntityForVendorLicenseArtifact { @JsonProperty(value = "version") abstract String getVersionForArtifact(); - @JsonProperty(value = "start-date") + @JsonIgnore abstract String getStartDate(); - @JsonProperty(value = "expiry-date") + @JsonIgnore abstract String getExpiryDate(); + @JsonProperty(value = "start-date") + abstract String getIsoFormatStartDate(); + + @JsonProperty(value = "expiry-date") + abstract String getIsoFormatExpiryDate(); + @JsonIgnore abstract String getVendorLicenseModelId(); 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 ad1a9a6bdf..7618b7a54f 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 @@ -42,7 +42,7 @@ public abstract class MixinEntitlementPoolEntityForVnfArtifact { @JsonProperty(value = "threshold-value") abstract ThresholdForXml getThresholdForArtifact(); - @JsonIgnore + @JsonProperty(value = "entitlement-pool-invariant-uuid") abstract String getId(); @JsonProperty(value = "manufacturer-reference-number") @@ -60,7 +60,7 @@ public abstract class MixinEntitlementPoolEntityForVnfArtifact { @JsonIgnore abstract String getVersion(); - @JsonIgnore + @JsonProperty(value = "version") abstract String getVersionForArtifact(); @JsonIgnore @@ -72,12 +72,18 @@ public abstract class MixinEntitlementPoolEntityForVnfArtifact { @JsonIgnore abstract float getThresholdValue(); - @JsonProperty(value = "start-date") + @JsonIgnore abstract String getStartDate(); - @JsonProperty(value = "expiry-date") + @JsonIgnore abstract String getExpiryDate(); + @JsonProperty(value = "start-date") + abstract String getIsoFormatStartDate(); + + @JsonProperty(value = "expiry-date") + abstract String getIsoFormatExpiryDate(); + @JsonIgnore abstract ChoiceOrOther getEntitlementMetric(); 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 5a8e9966cc..eeaa7c0a3a 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 @@ -79,12 +79,18 @@ public abstract class MixinLicenseKeyGroupEntityForVendorLicenseArtifact { @JsonIgnore abstract Collection getLimits(); - @JsonProperty(value = "start-date") + @JsonIgnore abstract String getStartDate(); - @JsonProperty(value = "expiry-date") + @JsonIgnore abstract String getExpiryDate(); + @JsonProperty(value = "start-date") + abstract String getIsoFormatStartDate(); + + @JsonProperty(value = "expiry-date") + abstract String getIsoFormatExpiryDate(); + @JsonProperty(value = "threshold-value") abstract ThresholdForXml getThresholdForArtifact(); 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 4af4b592a9..f560f363a1 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 @@ -34,7 +34,7 @@ import java.util.Collection; import java.util.Set; public abstract class MixinLicenseKeyGroupEntityForVnfArtifact { - @JsonIgnore + @JsonProperty(value = "license-key-group-invariant-uuid") abstract String getId(); @JsonProperty(value = "manufacturer-reference-number") @@ -46,7 +46,7 @@ public abstract class MixinLicenseKeyGroupEntityForVnfArtifact { @JsonIgnore abstract String getVersion(); - @JsonIgnore + @JsonProperty(value = "version") abstract String getVersionForArtifact(); @JsonIgnore @@ -87,12 +87,18 @@ public abstract class MixinLicenseKeyGroupEntityForVnfArtifact { @JsonIgnore abstract Collection getLimits(); - @JsonProperty(value = "start-date") + @JsonIgnore abstract String getStartDate(); - @JsonProperty(value = "expiry-date") + @JsonIgnore abstract String getExpiryDate(); + @JsonProperty(value = "start-date") + abstract String getIsoFormatStartDate(); + + @JsonProperty(value = "expiry-date") + abstract String getIsoFormatExpiryDate(); + @JsonIgnore abstract String getThresholdUnits(); 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 502aa350b9..bd209f9e81 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 @@ -27,16 +27,19 @@ import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; import org.openecomp.sdc.vendorlicense.healing.HealingService; import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.VendorLicenseArtifactsServiceImpl; +import org.openecomp.sdc.versioning.ItemManagerFactory; +import org.openecomp.sdc.versioning.VersioningManager; +import org.openecomp.sdc.versioning.VersioningManagerFactory; import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; 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; /** * @author katyr @@ -45,7 +48,7 @@ import java.util.Set; public class VendorLicenseArtifactsServiceUtils { private static final HealingService healingService = - HealingServiceFactory.getInstance().createInterface(); + HealingServiceFactory.getInstance().createInterface(); /** * maps the entities by id @@ -53,7 +56,7 @@ public class VendorLicenseArtifactsServiceUtils { * @return a Map of id -> list of versionable entities with that id */ private static MultiValuedMap mapById( - Collection versionableEntities) { + Collection versionableEntities) { MultiValuedMap mappedById = new ArrayListValuedHashMap<>(); for (VersionableEntity ve : versionableEntities) { mappedById.put(ve.getId(), ve); @@ -62,17 +65,18 @@ public class VendorLicenseArtifactsServiceUtils { } /** - * 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 + * 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) { + Collection versionableEntities) { MultiValuedMap entitiesById = mapById( - versionableEntities); + versionableEntities); MultiValuedMap entitiesByVersionUuId = - new ArrayListValuedHashMap<>(); + new ArrayListValuedHashMap<>(); List changedOnly = new ArrayList<>(); for (String epId : entitiesById.keySet()) { @@ -85,7 +89,7 @@ public class VendorLicenseArtifactsServiceUtils { //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); + (List) entitiesByVersionUuId.get(versionUid); versionableEntitiesForUuid.sort(new VersionableEntitySortByVlmMajorVersion()); changedOnly.add(versionableEntitiesForUuid.get(0)); } @@ -93,40 +97,38 @@ public class VendorLicenseArtifactsServiceUtils { return changedOnly; } - public static Set healLkgs(String user, - Collection licenseKeyGroupEntities) { + public static Set healLkgs( + Collection licenseKeyGroupEntities) { Set healed = new HashSet<>(); for (VersionableEntity licenseKeyGroupEntity : licenseKeyGroupEntities) { healed.add((LicenseKeyGroupEntity) VendorLicenseArtifactsServiceImpl.healingService - .heal(licenseKeyGroupEntity, user)); + .heal(licenseKeyGroupEntity)); } return healed; } - public static Set healEPs(String user, - Collection entitlementPoolEntities) { + public static Set healEPs( + Collection entitlementPoolEntities) { Set healed = new HashSet<>(); for (VersionableEntity entitlementPoolEntity : entitlementPoolEntities) { healed.add((EntitlementPoolEntity) VendorLicenseArtifactsServiceImpl.healingService - .heal(entitlementPoolEntity, user)); + .heal(entitlementPoolEntity)); } return healed; } public static List getFinalVersionsForVlm(String vlmId) { - VersionInfo versionInfo = - VendorLicenseArtifactsServiceImpl.vendorLicenseFacade - .getVersionInfo(vlmId, VersionableEntityAction.Read, ""); - return versionInfo.getFinalVersions(); - + 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, String user) { - return VendorLicenseArtifactsServiceImpl.vendorLicenseFacade - .getVendorLicenseModel(vendorLicenseModelId, null, user) - .getVendorLicenseModel().getVendorName(); + public static String getVendorName(String vendorLicenseModelId) { + return ItemManagerFactory.getInstance().createInterface().get(vendorLicenseModelId).getName(); } @@ -140,38 +142,36 @@ public class VendorLicenseArtifactsServiceUtils { * to healing as before. For VLMs created post-bugfix this code should not update any element */ public static Collection prepareForFiltering(Collection versionableEntities, String user, boolean isEP) { + VersionableEntity> versionableEntities, boolean isEP) { MultiValuedMap entitiesById = mapById( - versionableEntities); + versionableEntities); for (String epId : entitiesById.keySet()) { List versionableEntitiesForId = new ArrayList<>(); versionableEntitiesForId.addAll(entitiesById.get(epId)); versionableEntitiesForId.sort(new VersionableEntitySortByVlmMajorVersion()); - healingService.heal(versionableEntitiesForId.get(0), user); + 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); + .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), - user)); + versionableEntitiesForId.set(i, healingService.heal(versionableEntitiesForId.get(i))); } } else { LicenseKeyGroupEntity current = (LicenseKeyGroupEntity) versionableEntitiesForId.get(i); LicenseKeyGroupEntity previous = (LicenseKeyGroupEntity) versionableEntitiesForId - .get(i - 1); + .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), - user)); + versionableEntitiesForId.set(i, healingService.heal(versionableEntitiesForId.get(i))); } 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 8010c40023..bf48bfb40e 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 @@ -22,14 +22,14 @@ package org.openecomp.sdc.vendorsoftwareproduct; public final class VendorSoftwareProductConstants { public static final String VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE = "VendorSoftwareProduct"; - public static final String GENERAL_COMPONENT_ID = "General"; public static final String VSP_PACKAGE_ZIP = "VSPPackage.zip"; public static final String CSAR = "CSAR"; public static final String UPLOAD_RAW_DATA = "UPLOAD_RAW_DATA"; public static final String INFORMATION_ARTIFACT_NAME = "VSP_%s_Information.txt"; - public static final String UNSUPPORTED_OPERATION_ERROR = - "An error has occurred: Unsupported operation for 1707 release."; + public static final String UNSUPPORTED_OPERATION_ERROR = + "An error has occurred: Unsupported operation for 1707 release."; public static final String NAME_PATTERN = "^[a-zA-Z0-9_]*$"; + public static final String VALIDATION_VSP_NAME = "validationOnlyVspName"; public final class UniqueValues { public static final String VENDOR_SOFTWARE_PRODUCT_NAME = "Vendor Software Product 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/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 a980918c36..cbbb97b3c7 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 @@ -3,10 +3,7 @@ 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; -import org.openecomp.sdc.versioning.dao.types.Version; public interface ComponentDependencyModelDao extends VersionableDao, BaseDao { - - public 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/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 fceac0ac98..3d7c621d67 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 @@ -31,7 +31,9 @@ public interface OrchestrationTemplateCandidateDao extends VersionableDao { OrchestrationTemplateCandidateData get(String vspId, Version version); - void update(String vspId, OrchestrationTemplateCandidateData candidateData); + OrchestrationTemplateCandidateData getInfo(String vspId, Version version); + + void update(String vspId, Version version, OrchestrationTemplateCandidateData candidateData); void updateStructure(String vspId, Version version, FilesDataStructure fileDataStructure); 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 a8c2eb8f7b..4d82ed37af 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 @@ -20,17 +20,16 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadData; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; import org.openecomp.sdc.versioning.dao.types.Version; public interface OrchestrationTemplateDao extends VersionableDao { - String getValidationData(String vspId, Version version); + OrchestrationTemplateEntity getInfo(String vspId, Version version); - UploadDataEntity getOrchestrationTemplate(String vspId, Version version); + OrchestrationTemplateEntity get(String vspId, Version version); - void updateOrchestrationTemplateData(String vspId, UploadData uploadData); + void update(String vspId, Version version, OrchestrationTemplateEntity uploadData); } 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 d12069f480..36fff1e534 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 @@ -22,17 +22,9 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo; -import org.openecomp.sdc.versioning.dao.types.Version; -import java.nio.ByteBuffer; import java.util.List; public interface PackageInfoDao extends BaseDao { List listByCategory(String category, String subCategory); - - public void deleteRowTranslateContent(String vspId, Version version); - - void updateTranslatedContent(String vspId, Version version, ByteBuffer translateContent); - - } 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 c6622ef8e5..aea93a352e 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 @@ -12,6 +12,11 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface ProcessDao extends VersionableDao, BaseDao { void deleteAll(ProcessEntity entity); - void deleteVspAll(String vspId, Version version); + + ProcessEntity getArtifact(ProcessEntity entity); + + void uploadArtifact(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/UploadDataDao.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/UploadDataDao.java deleted file mode 100644 index cdc3a770db..0000000000 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/UploadDataDao.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.vendorsoftwareproduct.dao; - -import org.openecomp.core.dao.BaseDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; -import org.openecomp.sdc.versioning.dao.types.Version; - -import java.nio.ByteBuffer; - -public interface UploadDataDao extends BaseDao { - - void deleteContentDataAndValidationData(String vspId, Version version); - - ByteBuffer getContentData(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/UploadDataDaoFactory.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/UploadDataDaoFactory.java deleted file mode 100644 index 9654551f8f..0000000000 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/UploadDataDaoFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============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 UploadDataDaoFactory extends AbstractComponentFactory { - - public static UploadDataDaoFactory getInstance() { - return AbstractFactory.getInstance(UploadDataDaoFactory.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/VendorSoftwareProductDao.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/VendorSoftwareProductDao.java deleted file mode 100644 index 48d1e1606a..0000000000 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductDao.java +++ /dev/null @@ -1,127 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.vendorsoftwareproduct.dao; - -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; -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.ProcessEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; -import org.openecomp.sdc.versioning.dao.VersionableDao; -import org.openecomp.sdc.versioning.dao.types.Version; - -import java.util.Collection; -import java.util.List; - - -public interface VendorSoftwareProductDao extends VersionableDao { - - //VspDetails getVendorSoftwareProductInfo(VspDetails vspDetails); - - Collection listComponents(String vspId, Version version); - - Collection listComponentsQuestionnaire(String vspId, Version version); - - Collection listComponentsCompositionAndQuestionnaire(String vspId, - Version version); - - - Collection listProcesses(String vspId, Version version, String componentId); - - void deleteProcesses(String vspId, Version version, String componentId); - - ProcessEntity getProcess(String vspId, Version version, String componentId, String processId); - - void createProcess(ProcessEntity processEntity); - - void updateProcess(ProcessEntity processEntity); - - void deleteProcess(String vspId, Version version, String componentId, String processId); - - - void uploadProcessArtifact(String vspId, Version version, String componentId, String processId, - byte[] artifact, String artifactFileName); - - ProcessEntity getProcessArtifact(String vspId, Version version, String componentId, - String processId); - - void deleteProcessArtifact(String vspId, Version version, String componentId, String processId); - - - Collection listNicsByVsp(String vspId, Version version); - - - void deleteUploadData(String vspId, Version version); - - //void updateVspLatestModificationTime(String vspId, Version version); - void createComponentDependencyModel( - List componentDependencyModelEntity, String vspId, - Version version); - - Collection listComponentDependencies(String vspId,Version - version); - - void createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavor); - - Collection listDeploymentFlavors(String vspId, Version version); - - DeploymentFlavorEntity getDeploymentFlavor(String vspId, Version version, String - deploymentFlavorId); - void deleteDeploymentFlavor(String vspId, Version version, String deploymentFlavorId); - - - void createImage(ImageEntity imageEntity); - - Collection listImages(String vspId, Version version, String componentId); - - ImageEntity getImage(String vspId, Version version, String componentId, String imageId); - - Collection listImagesByVsp(String vspId, Version version); - - void createCompute(ComputeEntity computeEntity); - - Collection listComputes(String vspId, Version version, String componentId); - - Collection listComputesByVsp(String vspId, Version version); - - ComputeEntity getCompute(String vspId, Version version, String componentId, String - computeFlavorId); - - void deleteImage(String vspId, Version version, String componentId, String imageId); - - void updateDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity); - - void updateImage(ImageEntity imageEntity); - - void updateImageQuestionnaire(String vspId, Version activeVersion, String componentId, - String imageId, String questionnaireData); - - void updateComputeQuestionnaire(String vspId, Version activeVersion, String componentId, - String computeId, String questionnaireData); - - void updateCompute(ComputeEntity compute); - - void deleteCompute(String vspId, Version version, String componentId, 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/dao/VendorSoftwareProductDaoFactory.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/VendorSoftwareProductDaoFactory.java deleted file mode 100644 index 32070fe06a..0000000000 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductDaoFactory.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============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 VendorSoftwareProductDaoFactory extends - AbstractComponentFactory { - - - public static VendorSoftwareProductDaoFactory getInstance() { - return AbstractFactory.getInstance(VendorSoftwareProductDaoFactory.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 0481829ebd..c44a9cd89e 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 @@ -28,15 +28,9 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface VendorSoftwareProductInfoDao extends VersionableDao, BaseDao { - void updateOldVersionIndication(VspDetails vspDetails); - void updateQuestionnaireData(String vspId, Version version, String questionnaireData); - String getQuestionnaireData(String vspId, Version version); - VspQuestionnaireEntity getQuestionnaire(String vspId, Version version); - void deleteAll(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/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 new file mode 100644 index 0000000000..c9525bfbd8 --- /dev/null +++ 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 @@ -0,0 +1,16 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao; + +import com.amdocs.zusammen.datatypes.item.Resolution; +import org.openecomp.sdc.versioning.dao.types.Version; + +public interface VspMergeDao { + + boolean isVspModelConflicted(String vspId, Version version); + + void updateVspModelId(String vspId, Version version); + + // TODO: 11/7/2017 change to sdc Resolution + void updateVspModelConflictResolution(String vspId, Version version, Resolution resolution); + + void applyVspModelConflictResolution(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 new file mode 100644 index 0000000000..40ef50a961 --- /dev/null +++ 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 @@ -0,0 +1,11 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +public abstract class VspMergeDaoFactory extends AbstractComponentFactory { + + public static VspMergeDaoFactory getInstance() { + return AbstractFactory.getInstance(VspMergeDaoFactory.class); + } +} \ No newline at end of file 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 b20e11077f..57161fbe2e 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 @@ -1,6 +1,10 @@ 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 org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityId; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityType; 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 new file mode 100644 index 0000000000..108fd22c1b --- /dev/null +++ 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 @@ -0,0 +1,6 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.type; + +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 de70434d2f..7b19e8630c 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 @@ -5,15 +5,18 @@ import java.nio.ByteBuffer; public class OrchestrationTemplateCandidateData { private ByteBuffer contentData; private String filesDataStructure; - + private String fileSuffix; + private String fileName; public OrchestrationTemplateCandidateData() { } - public OrchestrationTemplateCandidateData(ByteBuffer contentData, - String dataStructureJson) { + public OrchestrationTemplateCandidateData(ByteBuffer contentData, String dataStructureJson, + String fileSuffix, String fileName) { this.contentData = contentData; this.filesDataStructure = dataStructureJson; + this.fileSuffix = fileSuffix; + this.fileName = fileName; } public ByteBuffer getContentData() { @@ -31,4 +34,20 @@ public class OrchestrationTemplateCandidateData { public void setFilesDataStructure(String filesDataStructure) { this.filesDataStructure = filesDataStructure; } + + 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; + } } 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 new file mode 100644 index 0000000000..ef3a4b6012 --- /dev/null +++ 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 @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.vendorsoftwareproduct.dao.type; + +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; + + public 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(); + } + + 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 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; + } +} 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 ad02883b2e..3403f28ab2 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 @@ -21,7 +21,6 @@ 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 org.openecomp.sdc.versioning.dao.types.Version; @@ -38,8 +37,7 @@ public class PackageInfo { private String vspId; @PartitionKey(value = 1) - @Frozen - private Version version; + private String version; @Column(name = "display_name") private String displayName; @@ -75,7 +73,7 @@ public class PackageInfo { public PackageInfo(String packageId, Version version) { this.vspId = packageId; - this.version = version; + this.version = version.getName(); } public String getDisplayName() { @@ -94,11 +92,11 @@ public class PackageInfo { this.vspDescription = vspDescription; } - public Version getVersion() { + public String getVersion() { return version; } - public void setVersion(Version version) { + public void setVersion(String version) { this.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/type/UploadData.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/UploadData.java deleted file mode 100644 index 071af919a4..0000000000 --- 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/UploadData.java +++ /dev/null @@ -1,90 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.vendorsoftwareproduct.dao.type; - -import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList; - -import java.nio.ByteBuffer; - - -public class UploadData { - - private String id; - - private String packageName; - - private String packageVersion; - - private String validationData; - - private ByteBuffer contentData; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - 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; - } -} 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/UploadDataEntity.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/UploadDataEntity.java deleted file mode 100644 index 2ade95b025..0000000000 --- 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/UploadDataEntity.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.vendorsoftwareproduct.dao.type; - -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 UploadDataEntity implements VersionableEntity { - private static final String ENTITY_TYPE = "Vendor Software Product Upload data"; - - private String id; - - private Version version; - - private String packageName; - - private String packageVersion; - - private String validationData; - - private ByteBuffer contentData; - - public UploadDataEntity() { - } - - public UploadDataEntity(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 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; - } -} 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 3f9768b9d7..3ba77ad0ee 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 @@ -20,13 +20,10 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -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.util.List; -import java.util.Objects; public class VspDetails implements VersionableEntity { @@ -55,18 +52,10 @@ public class VspDetails implements VersionableEntity { private List featureGroups; - private String validationData; - - private String oldVersion; - private Long writetimeMicroSeconds; private String onboardingMethod; - private String onboardingOrigin; - - private String networkPackageName; - public VspDetails() { } @@ -183,24 +172,6 @@ public class VspDetails implements VersionableEntity { this.featureGroups = featureGroups; } - 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 Long getWritetimeMicroSeconds() { return this.writetimeMicroSeconds; } @@ -213,36 +184,14 @@ public class VspDetails implements VersionableEntity { return this.oldVersion; }*/ - public String getOldVersion(){ - return this.oldVersion; - } - - public void setOldVersion(String oldVersion) { - this.oldVersion = oldVersion; - } - - public String getOnboardingOrigin() { - return onboardingOrigin; - } - - public void setOnboardingOrigin(String onboardingOrigin) { - this.onboardingOrigin = onboardingOrigin; - } - public String getOnboardingMethod() { return onboardingMethod; } + public void setOnboardingMethod(String onboardingMethod) { this.onboardingMethod = onboardingMethod; } - public String getNetworkPackageName() { - return networkPackageName; - } - - public void setNetworkPackageName(String networkPackageName) { - this.networkPackageName = networkPackageName; - } @Override public String toString() { 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/CompositionEntityDataManager.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/CompositionEntityDataManager.java index b77012e5cf..ff78fff689 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/CompositionEntityDataManager.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/CompositionEntityDataManager.java @@ -22,7 +22,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.services.composition; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.CompositionEntity; -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.NetworkEntity; @@ -64,12 +63,10 @@ public interface CompositionEntityDataManager { void saveComponents(String vspId, Version version, CompositionData compositionData, Map networkIdByName); - void saveNicsByComponent(String vspId, Version version, - Map networkIdByName, Component component, - String componentId); + void saveNicsByComponent(String vspId, Version version, Map networkIdByName, + Component component, String componentId); - Map saveNetworks(String vspId, Version version, - CompositionData compositionData); + Map saveNetworks(String vspId, Version version, CompositionData compositionData); NetworkEntity createNetwork(NetworkEntity network); @@ -77,15 +74,14 @@ public interface CompositionEntityDataManager { NicEntity createNic(NicEntity nic); - public ComputeEntity createCompute(ComputeEntity compute); + DeploymentFlavorEntity createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavor); - public DeploymentFlavorEntity createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavor); + ImageEntity createImage(ImageEntity image); - public ImageEntity createImage(ImageEntity image); + void saveComputesFlavorByComponent(String vspId, Version version, Component component, + String componentId); - public void saveComputesFlavorByComponent(String vspId, Version version, Component component, String - componentId); - public void saveImagesByComponent(String vspId, Version version, Component component, String - componentId); + void saveImagesByComponent(String vspId, Version version, Component component, + String componentId); } 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 6cc639fac0..697dab27e9 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 @@ -45,19 +45,23 @@ public interface CandidateService { Optional validateRawZipData(byte[] uploadedFileData); OrchestrationTemplateCandidateData createCandidateDataEntity( - CandidateDataEntityTo candidateDataEntityTo, InputStream zipFileManifest, AnalyzedZipHeatFiles analyzedZipHeatFiles) throws Exception; + CandidateDataEntityTo candidateDataEntityTo, InputStream zipFileManifest, + AnalyzedZipHeatFiles analyzedZipHeatFiles) throws Exception; - void updateCandidateUploadData(OrchestrationTemplateCandidateData uploadData, String - itemId); + void updateCandidateUploadData(String vspId, Version version, + OrchestrationTemplateCandidateData uploadData); Optional getOrchestrationTemplateCandidateFileDataStructure(String vspId, - Version activeVersion); + Version version); - void updateOrchestrationTemplateCandidateFileDataStructure(String vspId, Version activeVersion, - FilesDataStructure fileDataStructure); + void updateOrchestrationTemplateCandidateFileDataStructure(String vspId, Version version, + FilesDataStructure fileDataStructure); OrchestrationTemplateCandidateData getOrchestrationTemplateCandidate(String vspId, - Version activeVersion); + Version version); + + OrchestrationTemplateCandidateData getOrchestrationTemplateCandidateInfo(String vspId, + Version version); Optional fetchZipFileByteArrayInputStream(String vspId, OrchestrationTemplateCandidateData candidateDataEntity, @@ -66,11 +70,11 @@ public interface CandidateService { Map> uploadErrors); byte[] replaceManifestInZip(ByteBuffer contentData, String manifest, String vspId, - OnboardingTypesEnum type) - throws IOException; + OnboardingTypesEnum type) throws IOException; Optional createManifest(VspDetails vspDetails, - FileContentHandler fileContentHandler, AnalyzedZipHeatFiles analyzedZipHeatFiles); + FileContentHandler fileContentHandler, + AnalyzedZipHeatFiles analyzedZipHeatFiles); String createManifest(VspDetails vspDetails, FilesDataStructure structure); 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 dd303c7bb9..8ed51603aa 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 @@ -28,7 +28,11 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.util.*; +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; public class HeatFileAnalyzerRowDataImpl implements HeatFileAnalyzer { 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 41510ecc13..c34e6541e9 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 @@ -57,22 +57,22 @@ public class CandidateEntityBuilder { public OrchestrationTemplateCandidateData buildCandidateEntityFromZip( VspDetails vspDetails, byte[] uploadedFileData, FileContentHandler contentMap, - Map> uploadErrors, String user) throws Exception { + Map> uploadErrors) throws Exception { //mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); try (InputStream zipFileManifest = contentMap.getFileContent(SdcCommon.MANIFEST_NAME)) { HeatFileAnalyzer heatFileAnalyzer = new HeatFileAnalyzerRowDataImpl(); AnalyzedZipHeatFiles analyzedZipHeatFiles = - heatFileAnalyzer.analyzeFilesNotEligibleForModulesFromFileAnalyzer(contentMap.getFiles()); + heatFileAnalyzer.analyzeFilesNotEligibleForModulesFromFileAnalyzer(contentMap.getFiles()); HeatStructureTree tree = getHeatStructureTree(vspDetails, contentMap, analyzedZipHeatFiles); CandidateDataEntityTo candidateDataEntityTo = - new CandidateDataEntityTo(vspDetails.getId(), user, uploadedFileData, tree, contentMap, - vspDetails.getVersion()); + new CandidateDataEntityTo(vspDetails.getId(), vspDetails.getVersion(), uploadedFileData, + tree, contentMap); candidateDataEntityTo.setErrors(uploadErrors); OrchestrationTemplateCandidateData candidateDataEntity = - candidateService.createCandidateDataEntity(candidateDataEntityTo, zipFileManifest, - analyzedZipHeatFiles); + candidateService.createCandidateDataEntity(candidateDataEntityTo, zipFileManifest, + analyzedZipHeatFiles); MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP Id", vspDetails.getId()); return candidateDataEntity; @@ -81,7 +81,8 @@ public class CandidateEntityBuilder { private HeatStructureTree getHeatStructureTree(VspDetails vspDetails, FileContentHandler contentMap, - AnalyzedZipHeatFiles analyzedZipHeatFiles) throws IOException { + AnalyzedZipHeatFiles analyzedZipHeatFiles) + throws IOException { addManifestToFileContentMapIfNotExist(vspDetails, contentMap, analyzedZipHeatFiles); HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(contentMap); heatTreeManager.createTree(); @@ -90,21 +91,22 @@ public class CandidateEntityBuilder { private void addManifestToFileContentMapIfNotExist(VspDetails vspDetails, FileContentHandler fileContentHandler, - AnalyzedZipHeatFiles analyzedZipHeatFiles) throws IOException { + AnalyzedZipHeatFiles analyzedZipHeatFiles) + throws IOException { MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP Id", vspDetails.getId()); try (InputStream manifest = fileContentHandler.getFileContent(SdcCommon.MANIFEST_NAME)) { if (Objects.isNull(manifest)) { Optional manifestContentOptional = - candidateService.createManifest(vspDetails, fileContentHandler, analyzedZipHeatFiles); + 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()); + SdcCommon.MANIFEST_NAME, + String.valueOf(JsonUtil.sbObject2Json(manifestContent)).getBytes()); } } finally { MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP Id", vspDetails.getId()); 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 4ea0a02053..cf6e6f7181 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 @@ -31,32 +31,26 @@ import java.util.Map; public class CandidateDataEntityTo { private final String vspId; - private final String user; -// private final UploadFileResponse uploadFileResponse; - private Map> errors = new HashMap<>(); + private final Version version; private final byte[] uploadedFileData; private final HeatStructureTree tree; - private final Version activeVersion; private final FileContentHandler contentMap; + private Map> errors = new HashMap<>(); /** * Instantiates a new Candidate data entity to. - * @param vspId the vsp id - * @param user the user - * @param uploadedFileData the uploaded file data - * @param tree the tree - * @param contentMap the content map - * @param activeVersion the active version + * + * @param vspId the vsp id + * @param uploadedFileData the uploaded file data + * @param tree the tree + * @param contentMap the content map */ - public CandidateDataEntityTo(String vspId, String user, - byte[] uploadedFileData, HeatStructureTree tree, - FileContentHandler contentMap, Version activeVersion) { + public CandidateDataEntityTo(String vspId, Version version, byte[] uploadedFileData, + HeatStructureTree tree, FileContentHandler contentMap) { this.vspId = vspId; - this.user = user; - this.errors = errors; + this.version = version; this.uploadedFileData = uploadedFileData; this.tree = tree; - this.activeVersion = activeVersion; this.contentMap = contentMap; } @@ -64,10 +58,6 @@ public class CandidateDataEntityTo { return vspId; } - public String getUser() { - return user; - } - public byte[] getUploadedFileData() { return uploadedFileData; } @@ -76,15 +66,19 @@ public class CandidateDataEntityTo { return tree; } - public Version getActiveVersion() { - return activeVersion; + public Version getVersion() { + return version; } public FileContentHandler getContentMap() { return contentMap; } - public Map> getErrors() {return errors;} + public Map> getErrors() { + return errors; + } - public void setErrors(Map> errors) {this.errors = errors;} + public void setErrors(Map> errors) { + this.errors = errors; + } } 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 db22b3a3ee..489557cf08 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 @@ -26,7 +26,7 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.co public class GuestOS { private String name; private String tools; - private int bitSize; + private Number bitSize; public String getName() { return name; @@ -44,11 +44,11 @@ public class GuestOS { this.tools = tools; } - public int getBitSize() { + public Number getBitSize() { return bitSize; } - public void setBitSize(int bitSize) { + public void setBitSize(Number bitSize) { this.bitSize = 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/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 fb4aaa61f1..a6a8b406cf 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 @@ -23,8 +23,8 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.co public class VmSizing { private int numOfCPUs; private String fileSystemSizeGB; - private int persistentStorageVolumeSize; - private int IOOperationsPerSec; + private Number persistentStorageVolumeSize; + private Number IOOperationsPerSec; private String cpuOverSubscriptionRatio; private String memoryRAM; @@ -44,19 +44,19 @@ public class VmSizing { this.fileSystemSizeGB = fileSystemSizeGB; } - public int getPersistentStorageVolumeSize() { + public Number getPersistentStorageVolumeSize() { return persistentStorageVolumeSize; } - public void setPersistentStorageVolumeSize(int persistentStorageVolumeSize) { + public void setPersistentStorageVolumeSize(Number persistentStorageVolumeSize) { this.persistentStorageVolumeSize = persistentStorageVolumeSize; } - public int getIOOperationsPerSec() { + public Number getIOOperationsPerSec() { return IOOperationsPerSec; } - public void setIOOperationsPerSec(int IOOperationsPerSec) { + public void setIOOperationsPerSec(Number IOOperationsPerSec) { this.IOOperationsPerSec = IOOperationsPerSec; } 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 09e83b875f..e87c0fd2ce 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 @@ -26,8 +26,8 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.ge public class Image { private String format; private String providedBy; - private int bootDiskSizePerVM; - private int ephemeralDiskSizePerVM; + private Number bootDiskSizePerVM; + private Number ephemeralDiskSizePerVM; public String getFormat() { return format; @@ -45,19 +45,19 @@ public class Image { this.providedBy = providedBy; } - public int getBootDiskSizePerVM() { + public Number getBootDiskSizePerVM() { return bootDiskSizePerVM; } - public void setBootDiskSizePerVM(int bootDiskSizePerVM) { + public void setBootDiskSizePerVM(Number bootDiskSizePerVM) { this.bootDiskSizePerVM = bootDiskSizePerVM; } - public int getEphemeralDiskSizePerVM() { + public Number getEphemeralDiskSizePerVM() { return ephemeralDiskSizePerVM; } - public void setEphemeralDiskSizePerVM(int ephemeralDiskSizePerVM) { + public void setEphemeralDiskSizePerVM(Number ephemeralDiskSizePerVM) { this.ephemeralDiskSizePerVM = 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 4a13829d71..f1f8017689 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 @@ -24,23 +24,23 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.ge * Created by TALIO on 11/22/2016. */ public class Recovery { - private int pointObjective; - private int timeObjective; + private Number pointObjective; + private Number timeObjective; private String vmProcessFailuresHandling; - public int getPointObjective() { + public Number getPointObjective() { return pointObjective; } - public void setPointObjective(int pointObjective) { + public void setPointObjective(Number pointObjective) { this.pointObjective = pointObjective; } - public int getTimeObjective() { + public Number getTimeObjective() { return timeObjective; } - public void setTimeObjective(int timeObjective) { + public void setTimeObjective(Number timeObjective) { this.timeObjective = timeObjective; } 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 df5bcb0a02..2357ddfaa1 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 @@ -27,7 +27,7 @@ public class Backup { private String backupType; private String backupSolution; private String backupNIC; - private int backupStorageSize; + private Number backupStorageSize; public String getBackupType() { return backupType; @@ -53,11 +53,11 @@ public class Backup { this.backupNIC = backupNIC; } - public int getBackupStorageSize() { + public Number getBackupStorageSize() { return backupStorageSize; } - public void setBackupStorageSize(int backupStorageSize) { + public void setBackupStorageSize(Number backupStorageSize) { this.backupStorageSize = 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 cbf1fbeb78..1b6453ac86 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 @@ -24,24 +24,24 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.st * Created by TALIO on 11/22/2016. */ public class LogBackup { - private int sizeOfLogFiles; - private int logBackupFrequency; + private Number sizeOfLogFiles; + private Number logBackupFrequency; private int logRetentionPeriod; private String logFileLocation; - public int getSizeOfLogFiles() { + public Number getSizeOfLogFiles() { return sizeOfLogFiles; } - public void setSizeOfLogFiles(int sizeOfLogFiles) { + public void setSizeOfLogFiles(Number sizeOfLogFiles) { this.sizeOfLogFiles = sizeOfLogFiles; } - public int getLogBackupFrequency() { + public Number getLogBackupFrequency() { return logBackupFrequency; } - public void setLogBackupFrequency(int logBackupFrequency) { + public void setLogBackupFrequency(Number logBackupFrequency) { this.logBackupFrequency = logBackupFrequency; } 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 3d80224698..1e443277f4 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 @@ -25,7 +25,7 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic; */ public class PeakAndAvg { private int peak; - private int avg; + private Number avg; public int getPeak() { return peak; @@ -35,11 +35,11 @@ public class PeakAndAvg { this.peak = peak; } - public int getAvg() { + public Number getAvg() { return avg; } - public void setAvg(int avg) { + public void setAvg(Number avg) { this.avg = 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/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 32a9e5a186..4160cba554 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 @@ -25,7 +25,7 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic; */ public class Sizing { private String describeQualityOfService; - private int acceptablePacketLoss; + private Number acceptablePacketLoss; private PacketsAndBytes inflowTrafficPerSecond; private PacketsAndBytes outflowTrafficPerSecond; private PacketsAndBytes flowLength; @@ -39,11 +39,11 @@ public class Sizing { this.describeQualityOfService = describeQualityOfService; } - public int getAcceptablePacketLoss() { + public Number getAcceptablePacketLoss() { return acceptablePacketLoss; } - public void setAcceptablePacketLoss(int acceptablePacketLoss) { + public void setAcceptablePacketLoss(Number acceptablePacketLoss) { this.acceptablePacketLoss = acceptablePacketLoss; } 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 7c073af422..cf48703371 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 @@ -25,8 +25,8 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general; */ public class StorageDataReplication { private boolean storageReplicationAcrossRegion; - private int storageReplicationSize; - private int storageReplicationFrequency; + private Number storageReplicationSize; + private Number storageReplicationFrequency; private String storageReplicationSource; private String storageReplicationDestination; @@ -38,19 +38,19 @@ public class StorageDataReplication { this.storageReplicationDestination = storageReplicationDestination; } - public int getStorageReplicationSize() { + public Number getStorageReplicationSize() { return storageReplicationSize; } - public void setStorageReplicationSize(int storageReplicationSize) { + public void setStorageReplicationSize(Number storageReplicationSize) { this.storageReplicationSize = storageReplicationSize; } - public int getStorageReplicationFrequency() { + public Number getStorageReplicationFrequency() { return storageReplicationFrequency; } - public void setStorageReplicationFrequency(int storageReplicationFrequency) { + public void setStorageReplicationFrequency(Number storageReplicationFrequency) { this.storageReplicationFrequency = storageReplicationFrequency; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/resources/factoryConfiguration.json index 52c6119ae6..90160c4b12 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/resources/factoryConfiguration.json +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/resources/factoryConfiguration.json @@ -1,8 +1,6 @@ { - "org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.VendorSoftwareProductDaoFactoryImpl", "org.openecomp.sdc.vendorsoftwareproduct.dao.VspDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.VspDaoFactoryImpl", "org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.VendorSoftwareProductInfoDaoFactoryImpl", - "org.openecomp.sdc.vendorsoftwareproduct.dao.UploadDataDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.UploadDataDaoFactoryImpl", "org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.OrchestrationTemplateCandidateDaoFactoryImpl", "org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.OrchestrationTemplateDaoFactoryImpl", "org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.PackageInfoDaoFactoryImpl", 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/ComponentDependencyModelDaoCassandraImpl.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/ComponentDependencyModelDaoCassandraImpl.java index aa611c0bd2..2fcbc1aae8 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/ComponentDependencyModelDaoCassandraImpl.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/ComponentDependencyModelDaoCassandraImpl.java @@ -51,12 +51,6 @@ public class ComponentDependencyModelDaoCassandraImpl extends CassandraBaseDao .list(entity.getVspId(), versionMapper.toUDT(entity.getVersion())).all(); } - @Override - public void deleteAll(String vspId, Version version) { - accessor.deleteAll(vspId, versionMapper.toUDT(version)); - } - - @Override public void registerVersioning(String versionableEntityType) { VersionableEntityMetadata metadata = new VersionableEntityMetadata( 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 0b29fdab27..41ab1a35ae 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 @@ -20,10 +20,8 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; -import com.datastax.driver.core.UDTValue; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; -import com.datastax.driver.mapping.UDTMapper; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; import org.openecomp.core.dao.impl.CassandraBaseDao; @@ -32,9 +30,7 @@ import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo; -import org.openecomp.sdc.versioning.dao.types.Version; -import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -46,8 +42,6 @@ public class PackageInfoDaoImpl extends CassandraBaseDao implements noSqlDb.getMappingManager().mapper(PackageInfo.class); private static final PackageInfoAccessor accessor = noSqlDb.getMappingManager().createAccessor(PackageInfoAccessor.class); - private static final UDTMapper versionMapper = - noSqlDb.getMappingManager().udtMapper(Version.class); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); @@ -58,7 +52,7 @@ public class PackageInfoDaoImpl extends CassandraBaseDao implements @Override protected Object[] getKeys(PackageInfo entity) { - return new Object[]{entity.getVspId(), versionMapper.toUDT(entity.getVersion())}; + return new Object[]{entity.getVspId(), entity.getVersion()}; } @Override @@ -68,8 +62,7 @@ public class PackageInfoDaoImpl extends CassandraBaseDao implements @Override public List listByCategory(String category, String subCategory) { - - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); Result packages = accessor.listInfo(); List filteredPackages = new ArrayList<>(); @@ -86,20 +79,10 @@ public class PackageInfoDaoImpl extends CassandraBaseDao implements filteredPackages.add(packageInfo); } } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); return filteredPackages; } - @Override - public void deleteRowTranslateContent(String vspId, Version version) { - accessor.deleteRowTranslateContent(vspId, version); - } - - @Override - public void updateTranslatedContent(String vspId, Version version, ByteBuffer translateContent){ - accessor.updateTranslateContent(translateContent, vspId, versionMapper.toUDT(version)); - } - @Accessor interface PackageInfoAccessor { @@ -107,13 +90,5 @@ public class PackageInfoDaoImpl extends CassandraBaseDao implements "SELECT vsp_id,version,display_name,vsp_name,vsp_description,vendor_name,category" + " ,sub_category, vendor_release,package_checksum,package_type FROM package_details") Result listInfo(); - - @Query("DELETE TRANSLATE_CONTENT FROM package_details WHERE vsp_id=? and version=?") - Result deleteRowTranslateContent(String vspId, Version version); - - @Query("UPDATE package_details set translate_content = ? where vsp_id = ? and version = ?") - Result updateTranslateContent(ByteBuffer translateContent, String vspId, - UDTValue version); - } } 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 ada76e790a..0205446ae8 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 @@ -21,8 +21,8 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ProcessDaoZusammenImpl; public class ProcessDaoFactoryImpl extends ProcessDaoFactory { 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/VendorSoftwareProductDaoFactoryImpl.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/VendorSoftwareProductDaoFactoryImpl.java deleted file mode 100644 index 0a80b2ae51..0000000000 --- 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/VendorSoftwareProductDaoFactoryImpl.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; - -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; - - -public class VendorSoftwareProductDaoFactoryImpl extends VendorSoftwareProductDaoFactory { - private static final VendorSoftwareProductDao INSTANCE = new VendorSoftwareProductDaoImpl(); - - @Override - public VendorSoftwareProductDao 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/VendorSoftwareProductDaoImpl.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/VendorSoftwareProductDaoImpl.java deleted file mode 100644 index 832f36b3b9..0000000000 --- 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/VendorSoftwareProductDaoImpl.java +++ /dev/null @@ -1,323 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; - -import org.openecomp.core.model.dao.EnrichedServiceArtifactDao; -import org.openecomp.core.model.dao.EnrichedServiceArtifactDaoFactory; -import org.openecomp.core.model.dao.EnrichedServiceModelDao; -import org.openecomp.core.model.dao.EnrichedServiceModelDaoFactory; -import org.openecomp.core.model.dao.ServiceArtifactDaoFactory; -import org.openecomp.core.model.dao.ServiceArtifactDaoInter; -import org.openecomp.core.model.dao.ServiceModelDao; -import org.openecomp.core.model.dao.ServiceModelDaoFactory; -import org.openecomp.core.model.dao.ServiceTemplateDaoFactory; -import org.openecomp.core.model.dao.ServiceTemplateDaoInter; -import org.openecomp.core.utilities.CommonMethods; -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.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.NetworkDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; -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.ProcessEntity; -import org.openecomp.sdc.versioning.dao.types.Version; - -import java.nio.ByteBuffer; -import java.util.Collection; -import java.util.List; - -public class VendorSoftwareProductDaoImpl implements VendorSoftwareProductDao { - - private static final VendorSoftwareProductInfoDao vspInfoDao = VendorSoftwareProductInfoDaoFactory - .getInstance().createInterface(); - private static final PackageInfoDao packageInfoDao = - PackageInfoDaoFactory.getInstance().createInterface(); - private static final OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDataDao = - OrchestrationTemplateCandidateDaoFactory.getInstance().createInterface(); - private static final NetworkDao networkDao = NetworkDaoFactory.getInstance().createInterface(); - private static final ComponentDao componentDao = - ComponentDaoFactory.getInstance().createInterface(); - private static final NicDao nicDao = NicDaoFactory.getInstance().createInterface(); - private static final ProcessDao processDao = ProcessDaoFactory.getInstance().createInterface(); - private static final ServiceArtifactDaoInter - artifactDao = ServiceArtifactDaoFactory.getInstance().createInterface(); - public static final ServiceTemplateDaoInter - templateDao = ServiceTemplateDaoFactory.getInstance().createInterface(); - private static final EnrichedServiceArtifactDao enrichArtifactDao = - EnrichedServiceArtifactDaoFactory.getInstance().createInterface(); - private static final EnrichedServiceModelDao enrichedServiceModelDao = - EnrichedServiceModelDaoFactory.getInstance().createInterface(); - private static final ServiceModelDao serviceModelDao = - ServiceModelDaoFactory.getInstance().createInterface(); - private static final ComponentDependencyModelDao componentDependencyModelDao = - ComponentDependencyModelDaoFactory.getInstance().createInterface(); - private static final DeploymentFlavorDao - deploymentFlavorDao = DeploymentFlavorDaoFactory.getInstance().createInterface(); - private static final ImageDao imageDao = ImageDaoFactory.getInstance().createInterface(); - private static final ComputeDao computeDao = ComputeDaoFactory.getInstance().createInterface(); - - - @Override - public void registerVersioning(String versionableEntityType) { - vspInfoDao.registerVersioning(versionableEntityType); - networkDao.registerVersioning(versionableEntityType); - componentDao.registerVersioning(versionableEntityType); - nicDao.registerVersioning(versionableEntityType); - processDao.registerVersioning(versionableEntityType); - orchestrationTemplateCandidateDataDao.registerVersioning(versionableEntityType); - componentDependencyModelDao.registerVersioning(versionableEntityType); - computeDao.registerVersioning(versionableEntityType); - deploymentFlavorDao.registerVersioning(versionableEntityType); - imageDao.registerVersioning(versionableEntityType); - } - - @Override - public Collection listComponents(String vspId, Version version) { - return componentDao.list(new ComponentEntity(vspId, version, null)); - } - - @Override - public Collection listComponentsQuestionnaire(String vspId, Version version) { - return componentDao.listQuestionnaires(vspId, version); - } - - @Override - public Collection listComponentsCompositionAndQuestionnaire(String vspId, - Version version) { - return componentDao.listCompositionAndQuestionnaire(vspId, version); - } - - @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) { - processDao.delete(new ProcessEntity(vspId, version, componentId, null)); - } - - @Override - public ProcessEntity getProcess(String vspId, Version version, String componentId, - String processId) { - return processDao.get(new ProcessEntity(vspId, version, componentId, processId)); - } - - @Override - public void createProcess(ProcessEntity processEntity) { - processDao.create(processEntity); - } - - @Override - public void updateProcess(ProcessEntity processEntity) { - ProcessEntity process = processDao.get(new ProcessEntity(processEntity.getVspId(), processEntity.getVersion(), - processEntity.getComponentId(), processEntity.getId())); - processEntity.setArtifact(process.getArtifact()); - processEntity.setArtifactName(process.getArtifactName()); - processDao.update(processEntity); - } - - @Override - public void deleteProcess(String vspId, Version version, String componentId, String processId) { - processDao.delete(new ProcessEntity(vspId, version, componentId, processId)); - } - - @Override - public void uploadProcessArtifact(String vspId, Version version, String componentId, - String processId, byte[] artifact, String artifactName) { - ProcessEntity - processArtifact = new ProcessEntity(vspId, version, componentId, processId); - processArtifact = processDao.get(processArtifact); - processArtifact.setArtifact(ByteBuffer.wrap(artifact)); - processArtifact.setArtifactName(artifactName); - processDao.update(processArtifact); - } - - @Override - public ProcessEntity getProcessArtifact(String vspId, Version version, String componentId, - String processId) { - return processDao - .get(new ProcessEntity(vspId, version, componentId, processId)); - } - - @Override - public void deleteProcessArtifact(String vspId, Version version, String componentId, - String processId) { - processDao.delete(new ProcessEntity(vspId, version, componentId, processId)); - } - - @Override - public Collection listNicsByVsp(String vspId, Version version) { - return nicDao.listByVsp(vspId, version); - } - - @Override - public void deleteUploadData(String vspId, Version version) { - networkDao.deleteAll(vspId, version); - enrichedServiceModelDao.deleteAll(vspId, version); - serviceModelDao.deleteAll(vspId, version); - componentDao.deleteAll(vspId, version); - } - - @Override - public void createComponentDependencyModel(List - componentDependencyModel, String vspId, - Version version) { - componentDependencyModelDao.deleteAll(vspId, version); - for (ComponentDependencyModelEntity entity : componentDependencyModel) { - entity.setId(CommonMethods.nextUuId()); - componentDependencyModelDao.create(entity); - } - } - - @Override - public Collection listComponentDependencies(String vspId, - Version version) { - return componentDependencyModelDao.list(new ComponentDependencyModelEntity(vspId, version, - null)); - } - - @Override - public void createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavor) { - deploymentFlavorDao.create(deploymentFlavor); - } - - @Override - public Collection listDeploymentFlavors(String vspId, Version version) { - return deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); - } - - @Override - public DeploymentFlavorEntity getDeploymentFlavor(String vspId, Version version, - String deploymentFlavorId) { - return deploymentFlavorDao.get(new DeploymentFlavorEntity(vspId, version, deploymentFlavorId)); - } - - @Override - public void deleteDeploymentFlavor(String vspId, Version version, String deploymentFlavorId) { - deploymentFlavorDao.delete(new DeploymentFlavorEntity(vspId,version, - deploymentFlavorId)); - } - - @Override - public void createImage(ImageEntity imageEntity) { - imageDao.create(imageEntity); - } - - @Override - public Collection listImages(String vspId, Version version, String componentId) { - return imageDao.list(new ImageEntity(vspId, version, componentId, null)); - } - - @Override - public ImageEntity getImage(String vspId, Version version, String componentId, String imageId) { - return imageDao.get(new ImageEntity(vspId, version, componentId, imageId)); - } - - @Override - public Collection listImagesByVsp(String vspId, Version version) { - return imageDao.listByVsp(vspId, version); - } - - @Override - public void createCompute(ComputeEntity computeEntity) { - computeDao.create(computeEntity); - } - - @Override - public Collection listComputes(String vspId, Version version, String componentId) { - return computeDao.list(new ComputeEntity(vspId, version, componentId, null)); - } - - @Override - public Collection listComputesByVsp(String vspId, Version version) { - return computeDao.listByVsp(vspId, version); - } - - @Override - public ComputeEntity getCompute(String vspId, Version version, String componentId, - String computeFlavorId) { - return computeDao.get(new ComputeEntity(vspId, version, componentId, computeFlavorId)); - } - - @Override - public void deleteImage(String vspId, Version version, String componentId, String imageId) { - ImageEntity imageEntity = new ImageEntity(vspId, version, componentId, imageId); - imageDao.delete(imageEntity); - } - - @Override - public void updateDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity) { - deploymentFlavorDao.update(deploymentFlavorEntity); - } - - @Override - public void updateImage(ImageEntity imageEntity) { - imageDao.update(imageEntity); - } - - @Override - public void updateImageQuestionnaire(String vspId, Version version, String componentId, - String imageId, String questionnaireData) { - imageDao.updateQuestionnaireData(vspId, version, componentId, imageId, questionnaireData); - } - - @Override - public void updateComputeQuestionnaire(String vspId, Version version, String componentId, - String computeId, String questionnaireData) { - computeDao.updateQuestionnaireData(vspId, version, componentId, computeId, questionnaireData); - } - - @Override - public void updateCompute(ComputeEntity compute) { - computeDao.update(compute); - } - - @Override - public void deleteCompute(String vspId, Version version, String componentId, String - computeFlavorId) { - computeDao.delete(new ComputeEntity(vspId, version, componentId, computeFlavorId)); - } -} 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/VendorSoftwareProductInfoDaoImpl.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/VendorSoftwareProductInfoDaoImpl.java index d9b629cc60..fef49c8199 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/VendorSoftwareProductInfoDaoImpl.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/VendorSoftwareProductInfoDaoImpl.java @@ -72,32 +72,17 @@ public class VendorSoftwareProductInfoDaoImpl extends CassandraBaseDao 1; + } + + @Override + public void updateVspModelId(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 updateVspModelConflictResolution(String vspId, Version version, + Resolution resolution) { + accessor.updateModelResolution(resolution, getUser(), vspId, version.getId()); + } + + @Override + public void applyVspModelConflictResolution(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.getModelMergeHint(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.updateModelMergeHint(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()); + } + + private void updateVspModelId(String vspId, Version version, String vspModelId) { + accessor.updateModelMergeHint(vspModelId, null, getUser(), vspId, version.getId()); + } + + private String getUser() { + return SessionContextProviderFactory.getInstance().createInterface() + .get().getUser().getUserId(); + } + + @Accessor + interface VspMergeHintAccessor { + + @Query("UPDATE vsp_merge_hint SET model_id=?, model_resolution=? " + + "WHERE space=? AND item_id=? AND version_id=?") + void updateModelMergeHint(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("SELECT model_id, model_resolution FROM vsp_merge_hint " + + "WHERE space=? AND item_id=? AND version_id=?") + ResultSet getModelMergeHint(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 517f2fd19b..01be738b56 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 @@ -1,7 +1,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; 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; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; @@ -10,10 +9,10 @@ import com.amdocs.zusammen.datatypes.item.ElementContext; import org.openecomp.core.enrichment.types.MonitoringUploadType; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; 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 org.openecomp.sdc.versioning.dao.types.Version; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; @@ -21,13 +20,17 @@ import java.util.Collection; 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; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + /** * @author Avrahamg. * @since March 21, 2017 */ public class ComponentArtifactDaoZusammenImpl implements ComponentArtifactDao { - private static final String ARTIFACT_NAME = "name"; + private static final String ARTIFACT_NAME = "artifactName"; private ZusammenAdaptor zusammenAdaptor; @@ -43,28 +46,25 @@ public class ComponentArtifactDaoZusammenImpl implements ComponentArtifactDao { @Override public Optional getByType( ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(componentMonitoringUploadEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(componentMonitoringUploadEntity.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(componentMonitoringUploadEntity.getVspId(), + componentMonitoringUploadEntity.getVersion().getId()); + Optional mibsElement = - zusammenAdaptor.getElementByName(context, elementContext, new Id( - componentMonitoringUploadEntity - .getComponentId()), StructureElement.Mibs.toString()); + 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()); + getMonitoringStructuralElement(componentMonitoringUploadEntity.getType()).toString()); if (monitoringElement.isPresent()) { - componentMonitoringUploadEntity.setId(monitoringElement.get().getElementId().getValue()); - componentMonitoringUploadEntity - .setArtifactName( - (String) monitoringElement.get().getInfo().getProperties().get(ARTIFACT_NAME)); - componentMonitoringUploadEntity - .setArtifact(ByteBuffer.wrap(FileUtils.toByteArray(monitoringElement.get().getData()))); - return Optional.of(componentMonitoringUploadEntity); + ComponentMonitoringUploadEntity entity = + new ElementToComponentMonitoringUploadConvertor().convert(monitoringElement.get()); + entity.setVspId(componentMonitoringUploadEntity.getVspId()); + entity.setVersion(componentMonitoringUploadEntity.getVersion()); + entity.setComponentId(componentMonitoringUploadEntity.getComponentId()); + return Optional.of(entity); } } @@ -75,93 +75,113 @@ public class ComponentArtifactDaoZusammenImpl implements ComponentArtifactDao { public void create(ComponentMonitoringUploadEntity entity) { ZusammenElement mibElement = buildMibElement(entity); - ZusammenElement mibsElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Mibs, null); + ZusammenElement mibsElement = buildStructuralElement(ElementType.Mibs, null); - ZusammenElement componentElement = buildComponentElement(entity); + ZusammenElement componentElement = buildElement(new Id(entity.getComponentId()), Action.IGNORE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(entity.getVspId(), entity.getVersion().getId()); - Optional savedElement = zusammenAdaptor.saveElement(context, elementContext, + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, VspZusammenUtil.aggregateElements(componentElement, mibsElement, mibElement), "Create monitoring upload"); - savedElement.ifPresent(element -> - entity.setId(element.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue())); + entity.setId(savedElement.getSubElements().iterator().next() + .getSubElements().iterator().next().getElementId().getValue()); } @Override public void delete(ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - ZusammenElement mibElement = new ZusammenElement(); - mibElement.setElementId(new Id(componentMonitoringUploadEntity.getId())); - mibElement.setAction(Action.DELETE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(componentMonitoringUploadEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + 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 mib) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(mib.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(mib.getVersion())); - - return zusammenAdaptor.listElementsByName(context, elementContext, new Id(mib.getComponentId()), - StructureElement.Mibs.toString()).stream() - .map(elementInfo -> - mapElementInfoToMib(mib.getVspId(), mib.getVersion(), mib.getComponentId(), - elementInfo)) + public Collection list( + ComponentMonitoringUploadEntity mibEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(mibEntity.getVspId(), mibEntity.getVersion().getId()); + ElementToComponentMonitoringUploadConvertor + convertor = new ElementToComponentMonitoringUploadConvertor(); + return zusammenAdaptor + .listElementsByName(context, elementContext, new Id(mibEntity.getComponentId()), + ElementType.Mibs.toString()).stream() + .map(elementInfo -> convertor.convert(elementInfo)) + .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) { - ZusammenElement mibsElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Mibs, Action.DELETE); + /*ZusammenElement mibsElement = + buildStructuralElement(ElementType.Mibs, Action.DELETE); ZusammenElement componentElement = buildComponentElement(componentMonitoringUploadEntity); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(componentMonitoringUploadEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(componentMonitoringUploadEntity.getVspId(), + componentMonitoringUploadEntity.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, - VspZusammenUtil.aggregateElements(componentElement, mibsElement), "Delete mibs"); + VspaggregateElements(componentElement, mibsElement), "Delete mibs"); + +*/ + 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()); + }); + } } @Override public Collection listArtifacts( ComponentMonitoringUploadEntity monitoringUploadEntity) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(monitoringUploadEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(monitoringUploadEntity.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(monitoringUploadEntity.getVspId(), + monitoringUploadEntity.getVersion().getId()); final Optional elementByName = zusammenAdaptor.getElementByName(context, elementContext, - new Id(monitoringUploadEntity.getComponentId() - ), StructureElement.Mibs.name()); + new Id(monitoringUploadEntity.getComponentId()), ElementType.Mibs.name()); - if(!elementByName.isPresent()) + if (!elementByName.isPresent()) { return null; - else { + } else { final Id elementId = elementByName.get().getElementId(); return zusammenAdaptor.listElementData(context, elementContext, elementId).stream() - .map(element -> - buildMibEntity(element, monitoringUploadEntity) - ).collect(Collectors.toList()); + .map(element -> buildMibEntity(element, monitoringUploadEntity)) + .collect(Collectors.toList()); } } @@ -179,18 +199,10 @@ public class ComponentArtifactDaoZusammenImpl implements ComponentArtifactDao { return createdMib; } - private ZusammenElement buildComponentElement( - ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setElementId(new Id(componentMonitoringUploadEntity.getComponentId())); - componentElement.setAction(Action.IGNORE); - return componentElement; - } + private ZusammenElement buildMibElement( + ComponentMonitoringUploadEntity monitoringUploadEntity) { - private ZusammenElement buildMibElement(ComponentMonitoringUploadEntity monitoringUploadEntity) { - ZusammenElement monitoringElement = VspZusammenUtil - .buildStructuralElement(getMonitoringStructuralElement(monitoringUploadEntity.getType()), - Action.UPDATE); + ZusammenElement monitoringElement = buildMibElementStructure(monitoringUploadEntity); monitoringElement.getInfo().getProperties() .put(ARTIFACT_NAME, monitoringUploadEntity.getArtifactName()); monitoringElement @@ -198,27 +210,23 @@ public class ComponentArtifactDaoZusammenImpl implements ComponentArtifactDao { return monitoringElement; } - private ComponentMonitoringUploadEntity mapElementInfoToMib(String vspId, Version version, - String componentId, - ElementInfo elementInfo) { - ComponentMonitoringUploadEntity - monitoringUploadEntity = new ComponentMonitoringUploadEntity(vspId, version, componentId, - elementInfo.getId().getValue()); - monitoringUploadEntity - .setArtifactName((String) elementInfo.getInfo().getProperties().get(ARTIFACT_NAME)); - monitoringUploadEntity.setType(MonitoringUploadType.valueOf(elementInfo.getInfo().getName())); - return monitoringUploadEntity; + private ZusammenElement buildMibElementStructure( + ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { + ZusammenElement monitoringElement = + buildStructuralElement(getMonitoringStructuralElement(componentMonitoringUploadEntity.getType()), + Action.UPDATE); + return monitoringElement; } - private StructureElement getMonitoringStructuralElement(MonitoringUploadType type) + private ElementType getMonitoringStructuralElement(MonitoringUploadType type) throws IllegalArgumentException { switch (type) { case SNMP_POLL: - return StructureElement.SNMP_POLL; + return ElementType.SNMP_POLL; case SNMP_TRAP: - return StructureElement.SNMP_TRAP; + return ElementType.SNMP_TRAP; case VES_EVENTS: - return StructureElement.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 ed6a13d2a1..e658ea55ae 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 @@ -8,20 +8,26 @@ 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 org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComponentConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComponentQuestionnnaireConvertor; 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.Arrays; +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.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class ComponentDaoZusammenImpl implements ComponentDao { private ZusammenAdaptor zusammenAdaptor; @@ -36,105 +42,97 @@ public class ComponentDaoZusammenImpl implements ComponentDao { @Override public Collection list(ComponentEntity component) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(component.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(component.getVersion())); + SessionContext context = createSessionContext(); - return listComponents(zusammenAdaptor, context, elementContext, component.getVspId(), - component.getVersion()); + return listComponents(zusammenAdaptor, context, component.getVspId(), component.getVersion()); } static Collection listComponents(ZusammenAdaptor zusammenAdaptor, SessionContext context, - ElementContext elementContext, String vspId, Version version) { - return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.Components.name()) - .stream().map(elementInfo -> mapElementInfoToComponent(vspId, version, elementInfo)) + 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()); } - private static ComponentEntity mapElementInfoToComponent(String vspId, Version version, - ElementInfo elementInfo) { - ComponentEntity componentEntity = - new ComponentEntity(vspId, version, elementInfo.getId().getValue()); - componentEntity.setCompositionData( - elementInfo.getInfo().getProperty(ElementPropertyName.compositionData.name())); - return componentEntity; - } @Override public void create(ComponentEntity component) { ZusammenElement componentElement = componentToZusammen(component, Action.CREATE); + ZusammenElement componentsElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Components, null); + buildStructuralElement(ElementType.Components, Action.IGNORE); componentsElement.getSubElements().add(componentElement); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(component.getVspId()); - Optional savedElement = zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - componentsElement, "Create component"); - savedElement.ifPresent(element -> - component.setId(element.getSubElements().iterator().next().getElementId().getValue())); + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(component.getVspId()); + SessionContext context = createSessionContext(); zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(component.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(component.getVersion())); + SessionContext context = createSessionContext(); Optional element = - zusammenAdaptor.getElement(context, elementContext, component.getId()); + zusammenAdaptor.getElement(context, + new ElementContext(component.getVspId(), component.getVersion().getId()), + component.getId()); if (element.isPresent()) { - component.setCompositionData(new String(FileUtils.toByteArray(element.get().getData()))); - return component; + ComponentEntity entity = new ElementToComponentConvertor().convert(element.get()); + entity.setVspId(component.getVspId()); + entity.setVersion(component.getVersion()); + return entity; } return null; } @Override public void delete(ComponentEntity component) { - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setElementId(new Id(component.getId())); - componentElement.setAction(Action.DELETE); + ZusammenElement componentElement = buildElement(new Id(component.getId()), Action.DELETE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(component.getVspId()); + SessionContext context = createSessionContext(); zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); - return getQuestionnaire(context, elementContext, + return getQuestionnaire(context, new ElementContext(vspId, version.getId()), new ComponentEntity(vspId, version, componentId)); } @@ -142,14 +140,12 @@ public class ComponentDaoZusammenImpl implements ComponentDao { ComponentEntity component) { Optional questionnaireElement = zusammenAdaptor .getElementByName(context, elementContext, new Id(component.getId()), - StructureElement.Questionnaire.name()); - return questionnaireElement.map( - element -> element.getData() == null - ? null - : new String(FileUtils.toByteArray(element.getData()))) - .map(questionnaireData -> { - component.setQuestionnaireData(questionnaireData); - return component; + ElementType.ComponentQuestionnaire.name()); + return questionnaireElement.map(new ElementToComponentQuestionnnaireConvertor()::convert) + .map(entity -> { + entity.setVspId(component.getVspId()); + entity.setVersion(component.getVersion()); + return entity; }) .orElse(null); } @@ -160,16 +156,11 @@ public class ComponentDaoZusammenImpl implements ComponentDao { ZusammenElement questionnaireElement = componentQuestionnaireToZusammen(questionnaireData, Action.UPDATE); - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setAction(Action.IGNORE); - componentElement.setElementId(new Id(componentId)); + ZusammenElement componentElement = buildElement(new Id(componentId), Action.IGNORE); componentElement.setSubElements(Collections.singletonList(questionnaireElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(vspId, version.getId()), componentElement, "Update component questionnaire"); } @@ -181,45 +172,57 @@ public class ComponentDaoZusammenImpl implements ComponentDao { @Override public Collection listCompositionAndQuestionnaire(String vspId, Version version) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); Collection components = - listComponents(zusammenAdaptor, context, elementContext, vspId, version); + listComponents(zusammenAdaptor, context, vspId, version); - components.forEach(component -> getQuestionnaire(context, elementContext, component)); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + components.forEach(component -> component.setQuestionnaireData( + getQuestionnaire(context, elementContext, component).getQuestionnaireData())); return components; } @Override public void deleteAll(String vspId, Version version) { - ZusammenElement componentsElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Components, Action.DELETE); + 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; + } - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - componentsElement, "Delete all components"); + 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 componentToZusammen(ComponentEntity component, Action action) { ZusammenElement componentElement = buildComponentElement(component, action); - if (action == Action.CREATE) { - componentElement - .setSubElements(Arrays.asList( - componentQuestionnaireToZusammen(component.getQuestionnaireData(), Action.CREATE), - VspZusammenUtil.buildStructuralElement(StructureElement.Nics, Action.CREATE), - VspZusammenUtil.buildStructuralElement(StructureElement.Processes, Action.CREATE), - VspZusammenUtil.buildStructuralElement(StructureElement.Mibs, Action.CREATE), - VspZusammenUtil.buildStructuralElement(StructureElement.Computes, Action.CREATE), - VspZusammenUtil.buildStructuralElement(StructureElement.Images, Action.CREATE))); - + 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; } @@ -227,22 +230,21 @@ public class ComponentDaoZusammenImpl implements ComponentDao { private ZusammenElement componentQuestionnaireToZusammen(String questionnaireData, Action action) { ZusammenElement questionnaireElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Questionnaire, action); + buildStructuralElement(ElementType.ComponentQuestionnaire, action); questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); return questionnaireElement; } private ZusammenElement buildComponentElement(ComponentEntity component, Action action) { - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setAction(action); - if (component.getId() != null) { - componentElement.setElementId(new Id(component.getId())); - } + ZusammenElement componentElement = + buildElement(component.getId() == null ? null : new Id(component.getId()), action); Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.Component); + 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 e36b6c7743..6741d72bd2 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 @@ -9,17 +9,23 @@ import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; 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.sdc.versioning.dao.types.Version; +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.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + /** * Created by ayalaben on 5/16/2017. */ @@ -35,19 +41,22 @@ public class ComponentDependencyModelDaoZusammenImpl implements ComponentDepende } @Override - public ComponentDependencyModelEntity get(ComponentDependencyModelEntity entity) { + public ComponentDependencyModelEntity get(ComponentDependencyModelEntity dependency) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entity.getVspId()); // entity.getId()? - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(entity.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); Optional componentDependencyElement = - zusammenAdaptor.getElementInfo(context, elementContext, new Id(entity.getId())); + zusammenAdaptor.getElementInfo(context, elementContext, new Id(dependency.getId())); if (componentDependencyElement.isPresent()) { - addComponentDependencyData(entity, componentDependencyElement.get()); + ElementToComponentDependencyModelConvertor convertor = new + ElementToComponentDependencyModelConvertor(); + + ComponentDependencyModelEntity entity = convertor.convert(componentDependencyElement.get()); + entity.setVspId(dependency.getVspId()); + entity.setVersion(dependency.getVersion()); return entity; } @@ -55,70 +64,52 @@ public class ComponentDependencyModelDaoZusammenImpl implements ComponentDepende } @Override - public void create(ComponentDependencyModelEntity entity) { + public void create(ComponentDependencyModelEntity dependency) { + ZusammenElement componentDependency = + buildComponentDependencyElement(dependency, Action.CREATE); ZusammenElement componentDependencies = - VspZusammenUtil.buildStructuralElement(StructureElement.ComponentDependencies, null); + buildStructuralElement(ElementType.ComponentDependencies, Action.IGNORE); + componentDependencies.addSubElement(componentDependency); - ZusammenElement componentDependency = buildComponentDependencyElement(entity); - componentDependency.setAction(Action.CREATE); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(componentDependencies); - Id itemId = new Id(entity.getVspId()); - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); - Optional savedElement = zusammenAdaptor.saveElement(context, elementContext, - VspZusammenUtil.aggregateElements(componentDependencies, componentDependency), - "Create component dependency model"); + Element compDepsSavedElement = zusammenAdaptor + .saveElement(context, elementContext, vspModel, "Create component dependency model"); - savedElement.ifPresent(element -> - entity.setId(element.getSubElements().iterator().next().getElementId().getValue())); - } - - @Override - public void update(ComponentDependencyModelEntity entity) { - ZusammenElement componentDependencyElement = buildComponentDependencyElement(entity); - componentDependencyElement.setAction(Action.UPDATE); - - Id itemId = new Id(entity.getVspId()); - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - - zusammenAdaptor.saveElement(context, elementContext, - componentDependencyElement, - String.format("Update component dependency model with id %s", entity.getId())); + dependency.setId(compDepsSavedElement.getSubElements().iterator().next() + .getSubElements().iterator().next().getElementId().getValue()); } @Override - public void delete(ComponentDependencyModelEntity entity) { - ZusammenElement componentDependencyElement = new ZusammenElement(); - componentDependencyElement.setElementId(new Id(entity.getId())); - componentDependencyElement.setAction(Action.DELETE); + public void update(ComponentDependencyModelEntity dependency) { + ZusammenElement componentDependencyElement = + buildComponentDependencyElement(dependency, Action.UPDATE); - Id itemId = new Id(entity.getVspId()); - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + 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", entity.getId())); + zusammenAdaptor.saveElement(context, elementContext, componentDependencyElement, + String.format("Update component dependency model with id %s", dependency.getId())); } @Override - public void deleteAll(String vspId, Version version) { - ZusammenElement componentDependenciesElement = - VspZusammenUtil - .buildStructuralElement(StructureElement.ComponentDependencies, Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - componentDependenciesElement, "Delete all component dependencies"); + 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 @@ -127,75 +118,55 @@ public class ComponentDependencyModelDaoZusammenImpl implements ComponentDepende } @Override - public Collection list(ComponentDependencyModelEntity entity) { - - Id itemId = new Id(entity.getVspId()); - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(entity.getVersion())); - - return zusammenAdaptor.listElementsByName(context, elementContext, - null, StructureElement.ComponentDependencies.name()) - .stream().map(elementInfo -> mapElementInfoToComponentDependencyModel(entity.getVspId(), - entity.getVersion(), elementInfo)) - .collect(Collectors.toList()); - } + 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<>(); + } - private static ComponentDependencyModelEntity mapElementInfoToComponentDependencyModel( - String vspId, Version version, - ElementInfo elementInfo) { - ComponentDependencyModelEntity componentDependencyModelEntity = - new ComponentDependencyModelEntity(vspId, version, elementInfo.getId().getValue()); - componentDependencyModelEntity.setSourceComponentId(elementInfo.getInfo() - .getProperty(ComponentDependencyModelPropertyName.sourcecomponent_id.name())); - componentDependencyModelEntity.setTargetComponentId(elementInfo.getInfo() - .getProperty(ComponentDependencyModelPropertyName.targetcomponent_id.name())); - componentDependencyModelEntity.setRelation(elementInfo.getInfo() - .getProperty(ComponentDependencyModelPropertyName.relation.name())); - - return componentDependencyModelEntity; + 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 ZusammenElement buildComponentDependencyElement(ComponentDependencyModelEntity entity) { - ZusammenElement componentDependencyElement = new ZusammenElement(); - - if (entity.getId() != null) { - componentDependencyElement.setElementId(new Id(entity.getId())); - } + 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(ComponentDependencyModelPropertyName.id.name(), entity.getId()); - info.addProperty(ComponentDependencyModelPropertyName.relation.name(), entity.getRelation()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.ComponentDependency); + //info.addProperty(ComponentDependencyModelPropertyName.id.name(), entity.getId()); + info.addProperty(ComponentDependencyModelPropertyName.relation.name(), compDep.getRelation()); info.addProperty(ComponentDependencyModelPropertyName.sourcecomponent_id.name(), - entity.getSourceComponentId()); + compDep.getSourceComponentId()); info.addProperty(ComponentDependencyModelPropertyName.targetcomponent_id.name(), - entity.getTargetComponentId()); + compDep.getTargetComponentId()); componentDependencyElement.setInfo(info); return componentDependencyElement; } - private void addComponentDependencyData(ComponentDependencyModelEntity componentDependency, - ElementInfo componentDependencyElement) { - componentDependency.setId(componentDependencyElement.getInfo() - .getProperty(ComponentDependencyModelPropertyName.id.name())); - componentDependency.setRelation(componentDependencyElement.getInfo() - .getProperty(ComponentDependencyModelPropertyName.id.name())); - componentDependency.setSourceComponentId(componentDependencyElement.getInfo() - .getProperty(ComponentDependencyModelPropertyName.sourcecomponent_id.name())); - componentDependency.setTargetComponentId(componentDependencyElement.getInfo() - .getProperty(ComponentDependencyModelPropertyName.targetcomponent_id.name())); - } - - private 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 aa4bab67df..0f92c95294 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 @@ -2,7 +2,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; 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; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; @@ -11,11 +10,13 @@ import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComputeConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; 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; @@ -23,6 +24,10 @@ import java.util.Collections; 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; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class ComputeDaoZusammenImpl implements ComputeDao { private ZusammenAdaptor zusammenAdaptor; @@ -37,83 +42,78 @@ public class ComputeDaoZusammenImpl implements ComputeDao { @Override public Collection list(ComputeEntity compute) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(compute.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(compute.getVersion())); + 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) { + ElementContext elementContext, + ComputeEntity compute) { + ElementToComputeConvertor convertor = new ElementToComputeConvertor(); return zusammenAdaptor .listElementsByName(context, elementContext, new Id(compute.getComponentId()), - StructureElement.Computes.name()) - .stream().map(elementInfo -> mapElementInfoToCompute( - compute.getVspId(), compute.getVersion(), compute.getComponentId(), elementInfo)) + ElementType.Computes.name()) + .stream().map(elementInfo -> convertor.convert(elementInfo)) + .map(computeEntity -> { + computeEntity.setComponentId(compute.getComponentId()); + computeEntity.setVspId(compute.getVspId()); + computeEntity.setVersion(compute.getVersion()); + return computeEntity; + }) .collect(Collectors.toList()); } - private static ComputeEntity mapElementInfoToCompute(String vspId, Version version, - String componentId, ElementInfo elementInfo) { - ComputeEntity componentEntity = - new ComputeEntity(vspId, version, componentId, elementInfo.getId().getValue()); - componentEntity.setCompositionData( - elementInfo.getInfo().getProperty(ElementPropertyName.compositionData.name())); - return componentEntity; - } - @Override public void create(ComputeEntity compute) { ZusammenElement computeElement = computeToZusammen(compute, Action.CREATE); - ZusammenElement computesElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Computes, null); + ZusammenElement computesElement = buildStructuralElement(ElementType.Computes, Action.IGNORE); computesElement.setSubElements(Collections.singletonList(computeElement)); - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setElementId(new Id(compute.getComponentId())); - componentElement.setAction(Action.IGNORE); + ZusammenElement componentElement = + buildElement(new Id(compute.getComponentId()), Action.IGNORE); componentElement.setSubElements(Collections.singletonList(computesElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(compute.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(compute.getVspId(), compute.getVersion().getId()); - Optional savedElement = + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, componentElement, "Create compute"); - savedElement.ifPresent(element -> - compute.setId(element.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue())); + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(compute.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(compute.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(compute.getVersion())); - Optional element = zusammenAdaptor.getElement(context, elementContext, compute.getId()); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(compute.getVspId(), compute.getVersion().getId()); + Optional element = + zusammenAdaptor.getElement(context, elementContext, compute.getId()); if (element.isPresent()) { - compute.setCompositionData(new String(FileUtils.toByteArray(element.get().getData()))); - return compute; + + 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; } @@ -121,36 +121,30 @@ public class ComputeDaoZusammenImpl implements ComputeDao { @Override public void delete(ComputeEntity compute) { - ZusammenElement computeElement = new ZusammenElement(); - computeElement.setElementId(new Id(compute.getId())); - computeElement.setAction(Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(compute.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + 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) { + ComputeEntity compute) { Optional questionnaireElement = zusammenAdaptor .getElementByName(context, elementContext, new Id(compute.getId()), - StructureElement.Questionnaire.name()); + ElementType.ComputeQuestionnaire.name()); return questionnaireElement.map( element -> element.getData() == null ? null @@ -168,29 +162,22 @@ public class ComputeDaoZusammenImpl implements ComputeDao { ZusammenElement questionnaireElement = computeQuestionnaireToZusammen(questionnaireData, Action.UPDATE); - ZusammenElement computeElement = new ZusammenElement(); - computeElement.setAction(Action.IGNORE); - computeElement.setElementId(new Id(computeId)); + ZusammenElement computeElement = buildElement(new Id(computeId), Action.IGNORE); computeElement.setSubElements(Collections.singletonList(questionnaireElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); zusammenAdaptor.saveElement(context, elementContext, computeElement, "Update compute " + "questionnaire"); } @Override public Collection listByVsp(String vspId, Version version) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); Collection components = ComponentDaoZusammenImpl - .listComponents(zusammenAdaptor, context, elementContext, vspId, version); + .listComponents(zusammenAdaptor, context, vspId, version); return components.stream() .map(component -> @@ -204,15 +191,23 @@ public class ComputeDaoZusammenImpl implements ComputeDao { @Override public void deleteAll(String vspId, Version version) { - ZusammenElement computesElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Computes, Action.DELETE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - computesElement, "Delete all computes"); + 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) { @@ -225,27 +220,21 @@ public class ComputeDaoZusammenImpl implements ComputeDao { } private ZusammenElement computeQuestionnaireToZusammen(String questionnaireData, - Action action) { + Action action) { ZusammenElement questionnaireElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Questionnaire, action); + buildStructuralElement(ElementType.ComputeQuestionnaire, action); questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); return questionnaireElement; } private ZusammenElement buildComputeElement(ComputeEntity compute, Action action) { - ZusammenElement computeElement = new ZusammenElement(); - computeElement.setAction(action); - if (compute.getId() != null) { - computeElement.setElementId(new Id(compute.getId())); - } + ZusammenElement computeElement = + buildElement(compute.getId() == null ? null : new Id(compute.getId()), action); Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.Compute); + 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 947bcc27e5..17580b293b 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 @@ -1,7 +1,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; 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; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; @@ -10,16 +9,22 @@ import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToDeploymentFlavorConvertor; 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.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class DeploymentFlavorDaoZusammenImpl implements DeploymentFlavorDao { private ZusammenAdaptor zusammenAdaptor; @@ -34,52 +39,49 @@ public class DeploymentFlavorDaoZusammenImpl implements DeploymentFlavorDao { @Override public Collection list(DeploymentFlavorEntity deploymentFlavor) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(deploymentFlavor.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(deploymentFlavor.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()); - return listDeploymentFlavor(zusammenAdaptor, context, elementContext, deploymentFlavor.getVspId(), + return listDeploymentFlavor(zusammenAdaptor, context, elementContext, + deploymentFlavor.getVspId(), deploymentFlavor.getVersion()); } - static Collection listDeploymentFlavor(ZusammenAdaptor zusammenAdaptor, - SessionContext context, - ElementContext elementContext, - String vspId, Version version) { + private static Collection listDeploymentFlavor( + ZusammenAdaptor zusammenAdaptor, + SessionContext context, + ElementContext elementContext, + String vspId, Version version) { + ElementToDeploymentFlavorConvertor convertor = new ElementToDeploymentFlavorConvertor(); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.DeploymentFlavors.name()) - .stream().map(elementInfo -> mapElementInfoToComponent(vspId, version, elementInfo)) + .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()); } - private static DeploymentFlavorEntity mapElementInfoToComponent(String vspId, Version version, - ElementInfo elementInfo) { - DeploymentFlavorEntity deploymentFlavorEntity = - new DeploymentFlavorEntity(vspId, version, elementInfo.getId().getValue()); - deploymentFlavorEntity.setCompositionData( - elementInfo.getInfo().getProperty(ElementPropertyName.compositionData.name())); - return deploymentFlavorEntity; - } @Override public void create(DeploymentFlavorEntity deploymentFlavor) { ZusammenElement deploymentFlavorElement = deploymentFlavorToZusammen(deploymentFlavor, Action.CREATE); ZusammenElement deploymentFlavorElements = - VspZusammenUtil.buildStructuralElement(StructureElement.DeploymentFlavors, null); + buildStructuralElement(ElementType.DeploymentFlavors, Action.IGNORE); deploymentFlavorElements.getSubElements().add(deploymentFlavorElement); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(deploymentFlavor.getVspId()); - Optional savedElement = zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + SessionContext context = createSessionContext(); + Element savedElement = zusammenAdaptor.saveElement(context, + new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()), deploymentFlavorElements, "Create deloymentFlavor"); - savedElement.ifPresent(element -> - deploymentFlavor.setId(element.getSubElements().iterator().next().getElementId() - .getValue())); + deploymentFlavor.setId(savedElement.getSubElements().iterator().next().getElementId() + .getValue()); } @Override @@ -87,87 +89,83 @@ public class DeploymentFlavorDaoZusammenImpl implements DeploymentFlavorDao { ZusammenElement deploymentFlavorElement = deploymentFlavorToZusammen(deploymentFlavor, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(deploymentFlavor.getVspId()); + SessionContext context = createSessionContext(); zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(deploymentFlavor.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(deploymentFlavor.getVersion())); + 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()))); - return deploymentFlavor; + entity.setVspId(deploymentFlavor.getVspId()); + entity.setVersion(deploymentFlavor.getVersion()); + return entity; } return null; } @Override public void delete(DeploymentFlavorEntity deploymentFlavor) { - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setElementId(new Id(deploymentFlavor.getId())); - componentElement.setAction(Action.DELETE); + ZusammenElement componentElement = + buildElement(new Id(deploymentFlavor.getId()), Action.DELETE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(deploymentFlavor.getVspId()); + SessionContext context = createSessionContext(); zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()), componentElement, String.format("Delete deloymentFlavor with id %s", deploymentFlavor.getId())); } @Override public void deleteAll(String vspId, Version version) { - ZusammenElement deploymentFlavorsElement = - VspZusammenUtil.buildStructuralElement(StructureElement.DeploymentFlavors, Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - deploymentFlavorsElement, "Delete all deploymentFlavors"); - } - - private ZusammenElement deploymentFlavorToZusammen(DeploymentFlavorEntity deploymentFlavor, - Action action) { - ZusammenElement deploymentFlavorElement = buildDeploymentFlavorElement - (deploymentFlavor, action); - - return deploymentFlavorElement; + 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 deplymentFlavorQuestionnaireToZusammen(String questionnaireData, Action action) { ZusammenElement questionnaireElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Questionnaire, action); + VspbuildStructuralElement(ElementType.Questionnaire, action); questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); return questionnaireElement; }*/ - private ZusammenElement buildDeploymentFlavorElement(DeploymentFlavorEntity deploymentFlavor, - Action action) { - ZusammenElement deploymentFlavorElement = new ZusammenElement(); - deploymentFlavorElement.setAction(action); - if (deploymentFlavor.getId() != null) { - deploymentFlavorElement.setElementId(new Id(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.type.name(), ElementType.DeploymentFlavor); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.DeploymentFlavor); info.addProperty(ElementPropertyName.compositionData.name(), deploymentFlavor .getCompositionData()); deploymentFlavorElement.setInfo(info); 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/ElementPropertyName.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/ElementPropertyName.java deleted file mode 100644 index 9ca0bf721a..0000000000 --- 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/ElementPropertyName.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; - -public enum ElementPropertyName { - type, - compositionData -} 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/ElementType.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/ElementType.java deleted file mode 100644 index 9da0780f73..0000000000 --- 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/ElementType.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; - -public enum ElementType { - Network, - Component, - Nic, - Process, - Mib, - LKG, - Compute, - DeploymentFlavor, - Image -} 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 d913b18956..24ca072b23 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 @@ -2,7 +2,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; 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; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; @@ -11,11 +10,13 @@ import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToImageConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; 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; @@ -23,6 +24,10 @@ import java.util.Collections; 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; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class ImageDaoZusammenImpl implements ImageDao { private ZusammenAdaptor zusammenAdaptor; @@ -37,83 +42,76 @@ public class ImageDaoZusammenImpl implements ImageDao { @Override public Collection list(ImageEntity image) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(image.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(image.getVersion())); + 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) { + ElementContext elementContext, ImageEntity image) { + ElementToImageConvertor convertor = new ElementToImageConvertor(); return zusammenAdaptor .listElementsByName(context, elementContext, new Id(image.getComponentId()), - StructureElement.Images.name()) - .stream().map(elementInfo -> mapElementInfoToImage( - image.getVspId(), image.getVersion(), image.getComponentId(), elementInfo)) + ElementType.Images.name()) + .stream().map(convertor::convert) + .map(imageEntity -> { + imageEntity.setComponentId(image.getComponentId()); + imageEntity.setVspId(image.getVspId()); + imageEntity.setVersion(image.getVersion()); + return imageEntity; + }) .collect(Collectors.toList()); } - private static ImageEntity mapElementInfoToImage(String vspId, Version version, - String componentId, ElementInfo elementInfo) { - ImageEntity imageEntity = - new ImageEntity(vspId, version, componentId, elementInfo.getId().getValue()); - imageEntity.setCompositionData( - elementInfo.getInfo().getProperty(ElementPropertyName.compositionData.name())); - return imageEntity; - } - @Override public void create(ImageEntity image) { ZusammenElement imageElement = imageToZusammen(image, Action.CREATE); ZusammenElement imagesElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Images, null); + buildStructuralElement(ElementType.Images, Action.IGNORE); imagesElement.setSubElements(Collections.singletonList(imageElement)); - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setElementId(new Id(image.getComponentId())); - componentElement.setAction(Action.IGNORE); + ZusammenElement componentElement = buildElement(new Id(image.getComponentId()), Action.IGNORE); componentElement.setSubElements(Collections.singletonList(imagesElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(image.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(image.getVspId(), image.getVersion().getId()); - Optional savedElement = + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, componentElement, "Create image"); - savedElement.ifPresent(element -> - image.setId(element.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue())); + image.setId(savedElement.getSubElements().iterator().next() + .getSubElements().iterator().next().getElementId().getValue()); } @Override public void update(ImageEntity image) { ZusammenElement imageElement = imageToZusammen(image, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(image.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(image.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(image.getVersion())); + SessionContext context = createSessionContext(); + + ElementContext elementContext = + new ElementContext(image.getVspId(), image.getVersion().getId()); Optional element = zusammenAdaptor.getElement(context, elementContext, image.getId()); if (element.isPresent()) { - image.setCompositionData(new String(FileUtils.toByteArray(element.get().getData()))); - return image; + 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; } @@ -121,41 +119,41 @@ public class ImageDaoZusammenImpl implements ImageDao { @Override public void delete(ImageEntity image) { - ZusammenElement imageElement = new ZusammenElement(); - imageElement.setElementId(new Id(image.getId())); - imageElement.setAction(Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(image.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + 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) { - ZusammenElement imagesElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Images, Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - imagesElement, String.format("Delete all images with vsp id %s", vspId)); + 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 Collection listByVsp(String vspId, Version version) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); Collection components = ComponentDaoZusammenImpl - .listComponents(zusammenAdaptor, context, elementContext, vspId, version); + .listComponents(zusammenAdaptor, context, vspId, version); return components.stream() .map(component -> @@ -169,12 +167,9 @@ public class ImageDaoZusammenImpl implements ImageDao { @Override public ImageEntity getQuestionnaireData(String vspId, Version version, String componentId, - String imageId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + String imageId) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); return getQuestionnaire(context, elementContext, new ImageEntity(vspId, version, componentId, imageId)); @@ -184,7 +179,7 @@ public class ImageDaoZusammenImpl implements ImageDao { ImageEntity image) { Optional questionnaireElement = zusammenAdaptor .getElementByName(context, elementContext, new Id(image.getId()), - StructureElement.Questionnaire.name()); + ElementType.ImageQuestionnaire.name()); return questionnaireElement.map( element -> element.getData() == null ? null @@ -202,21 +197,16 @@ public class ImageDaoZusammenImpl implements ImageDao { ZusammenElement questionnaireElement = imageQuestionnaireToZusammen(questionnaireData, Action.UPDATE); - ZusammenElement imageElement = new ZusammenElement(); - imageElement.setAction(Action.IGNORE); - imageElement.setElementId(new Id(imageId)); + ZusammenElement imageElement = buildElement(new Id(imageId), Action.IGNORE); imageElement.setSubElements(Collections.singletonList(questionnaireElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); zusammenAdaptor.saveElement(context, elementContext, imageElement, "Update image " + "questionnaire"); } - private ZusammenElement imageToZusammen(ImageEntity image, Action action) { ZusammenElement imageElement = buildImageElement(image, action); if (action == Action.CREATE) { @@ -227,21 +217,18 @@ public class ImageDaoZusammenImpl implements ImageDao { } private ZusammenElement imageQuestionnaireToZusammen(String questionnaireData, - Action action) { + Action action) { ZusammenElement questionnaireElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Questionnaire, action); + buildStructuralElement(ElementType.ImageQuestionnaire, action); questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); return questionnaireElement; } private ZusammenElement buildImageElement(ImageEntity image, Action action) { - ZusammenElement imageElement = new ZusammenElement(); - imageElement.setAction(action); - if (image.getId() != null) { - imageElement.setElementId(new Id(image.getId())); - } + ZusammenElement imageElement = + buildElement(image.getId() == null ? null : new Id(image.getId()), action); Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.Image); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Image); info.addProperty(ElementPropertyName.compositionData.name(), image.getCompositionData()); imageElement.setInfo(info); imageElement.setData(new ByteArrayInputStream(image.getCompositionData().getBytes())); 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 b22c9f32ed..bccea3a85c 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 @@ -8,19 +8,25 @@ 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 org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToNetworkConvertor; 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.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class NetworkDaoZusammenImpl implements NetworkDao { private ZusammenAdaptor zusammenAdaptor; @@ -36,71 +42,70 @@ public class NetworkDaoZusammenImpl implements NetworkDao { @Override public Collection list(NetworkEntity network) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(network.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(network.getVersion())); - - return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.Networks.name()) - .stream().map(elementInfo -> - mapElementInfoToNetwork(network.getVspId(), network.getVersion(), elementInfo)) - .collect(Collectors.toList()); - } + 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<>(); + } - private NetworkEntity mapElementInfoToNetwork(String vspId, Version version, - ElementInfo elementInfo) { - NetworkEntity networkEntity = - new NetworkEntity(vspId, version, elementInfo.getId().getValue()); - networkEntity.setCompositionData( - elementInfo.getInfo().getProperty(ElementPropertyName.compositionData.name())); - return networkEntity; + ElementToNetworkConvertor convertor = new ElementToNetworkConvertor(); + return zusammenAdaptor.listElementsByName(context, elementContext, vspModel.get().getId(), + ElementType.Networks.name()).stream() + .map(convertor::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 = - VspZusammenUtil.buildStructuralElement(StructureElement.Networks, null); + + ZusammenElement networksElement = buildStructuralElement(ElementType.Networks, Action.IGNORE); networksElement.setSubElements(Collections.singletonList(networkElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(network.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - Optional savedElement = - zusammenAdaptor.saveElement(context, elementContext, networksElement, "Create network"); - savedElement.ifPresent(element -> - network.setId(element.getSubElements().iterator().next().getElementId().getValue())); + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(network.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, networkElement, - String.format("Update network with id %s", network.getId())); + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(network.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(network.getVersion())); + SessionContext context = createSessionContext(); Optional element = - zusammenAdaptor.getElement(context, elementContext, network.getId()); + zusammenAdaptor.getElement(context, + new ElementContext(network.getVspId(), network.getVersion().getId()), network.getId()); if (element.isPresent()) { - network.setCompositionData(new String(FileUtils.toByteArray(element.get().getData()))); - return network; + ElementToNetworkConvertor convertor = new ElementToNetworkConvertor(); + NetworkEntity entity = convertor.convert(element.get()); + entity.setVspId(network.getVspId()); + entity.setVersion(network.getVersion()); + return entity; } else { return null; } @@ -108,39 +113,44 @@ public class NetworkDaoZusammenImpl implements NetworkDao { @Override public void delete(NetworkEntity network) { - ZusammenElement networkElement = new ZusammenElement(); - networkElement.setElementId(new Id(network.getId())); - networkElement.setAction(Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(network.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, - networkElement, String.format("Delete network with id %s", network.getId())); + 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 void deleteAll(String vspId, Version version) { - ZusammenElement networksElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Networks, Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, networksElement, "Delete all networks"); + 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 = new ZusammenElement(); - networkElement.setAction(action); - if (network.getId() != null) { - networkElement.setElementId(new Id(network.getId())); - } + ZusammenElement networkElement = + buildElement(network.getId() == null ? null : new Id(network.getId()), action); Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.Network); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Network); info.addProperty(ElementPropertyName.compositionData.name(), network.getCompositionData()); networkElement.setInfo(info); networkElement.setData(new ByteArrayInputStream(network.getCompositionData().getBytes())); 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 e597068d87..268e2546ed 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 @@ -1,20 +1,21 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; 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; 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 com.amdocs.zusammen.datatypes.item.Info; -import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToNicConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToNicQuestionnaireConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; 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; @@ -22,6 +23,10 @@ import java.util.Collections; 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; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class NicDaoZusammenImpl implements NicDao { private ZusammenAdaptor zusammenAdaptor; @@ -37,82 +42,70 @@ public class NicDaoZusammenImpl implements NicDao { @Override public Collection list(NicEntity nic) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(nic.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(nic.getVersion())); - - return listNics(context, elementContext, 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()), - StructureElement.Nics.name()) - .stream().map(elementInfo -> mapElementInfoToNic( - nic.getVspId(), nic.getVersion(), nic.getComponentId(), elementInfo)) + ElementToNicConvertor convertor = new ElementToNicConvertor(); + return zusammenAdaptor.listElementsByName(context, elementContext, new Id(nic.getComponentId()), + ElementType.Nics.name()) + .stream().map(convertor::convert) + .map(nicEntity -> { + nicEntity.setComponentId(nicEntity.getComponentId()); + nicEntity.setVspId(nic.getVspId()); + nicEntity.setVersion(nic.getVersion()); + return nicEntity; + }) .collect(Collectors.toList()); } - private NicEntity mapElementInfoToNic(String vspId, Version version, - String componentId, ElementInfo elementInfo) { - NicEntity nicEntity = - new NicEntity(vspId, version, componentId, elementInfo.getId().getValue()); - nicEntity.setCompositionData( - elementInfo.getInfo().getProperty(ElementPropertyName.compositionData.name())); - return nicEntity; - } @Override public void create(NicEntity nic) { ZusammenElement nicElement = nicToZusammen(nic, Action.CREATE); - ZusammenElement nicsElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Nics, null); + ZusammenElement nicsElement = buildStructuralElement(ElementType.Nics, Action.IGNORE); nicsElement.setSubElements(Collections.singletonList(nicElement)); - ZusammenElement componentElement = - buildZusammenElement(new Id(nic.getComponentId()), Action.IGNORE); + ZusammenElement componentElement = buildElement(new Id(nic.getComponentId()), Action.IGNORE); componentElement.setSubElements(Collections.singletonList(nicsElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(nic.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(nic.getVspId(), nic.getVersion().getId()); - Optional savedElement = + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, componentElement, "Create nic"); - savedElement.ifPresent(element -> - nic.setId(element.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue())); + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(nic.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, nicElement, - String.format("Update nic with id %s", nic.getId())); + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(nic.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(nic.getVersion())); - Optional element = zusammenAdaptor.getElement(context, elementContext, nic.getId()); + SessionContext context = createSessionContext(); + ElementToNicConvertor convertor = new ElementToNicConvertor(); + Optional element = zusammenAdaptor + .getElement(context, new ElementContext(nic.getVspId(), nic.getVersion().getId()), + nic.getId()); if (element.isPresent()) { - nic.setCompositionData(new String(FileUtils.toByteArray(element.get().getData()))); - return nic; + NicEntity entity = convertor.convert(element.get()); + entity.setVspId(nic.getVspId()); + entity.setVersion(nic.getVersion()); + entity.setComponentId(nic.getComponentId()); + + return entity; } else { return null; } @@ -120,26 +113,20 @@ public class NicDaoZusammenImpl implements NicDao { @Override public void delete(NicEntity nic) { - ZusammenElement nicElement = buildZusammenElement(new Id(nic.getId()), Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(nic.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, nicElement, - String.format("Delete nic with id %s", nic.getId())); + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); - return getQuestionnaire(context, elementContext, + return getQuestionnaire(context, new ElementContext(vspId, version.getId()), new NicEntity(vspId, version, componentId, nicId)); } @@ -147,14 +134,13 @@ public class NicDaoZusammenImpl implements NicDao { NicEntity nic) { Optional questionnaireElement = zusammenAdaptor .getElementByName(context, elementContext, new Id(nic.getId()), - StructureElement.Questionnaire.name()); - return questionnaireElement.map( - element -> element.getData() == null - ? null - : new String(FileUtils.toByteArray(element.getData()))) - .map(questionnaireData -> { - nic.setQuestionnaireData(questionnaireData); - return nic; + 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); } @@ -165,29 +151,22 @@ public class NicDaoZusammenImpl implements NicDao { ZusammenElement questionnaireElement = nicQuestionnaireToZusammen(questionnaireData, Action.UPDATE); - ZusammenElement nicElement = new ZusammenElement(); - nicElement.setAction(Action.IGNORE); - nicElement.setElementId(new Id(nicId)); + ZusammenElement nicElement = buildElement(new Id(nicId), Action.IGNORE); nicElement.setSubElements(Collections.singletonList(questionnaireElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, nicElement, "Update nic questionnaire"); + 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 = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); Collection components = ComponentDaoZusammenImpl - .listComponents(zusammenAdaptor, context, elementContext, vspId, version); + .listComponents(zusammenAdaptor, context, vspId, version); + ElementContext elementContext = new ElementContext(vspId, version.getId()); return components.stream() .map(component -> listNics(context, elementContext, @@ -200,16 +179,22 @@ public class NicDaoZusammenImpl implements NicDao { @Override public void deleteByComponentId(String vspId, Version version, String componentId) { - ZusammenElement componentElement = buildZusammenElement(new Id(componentId), Action.IGNORE); - componentElement.setSubElements(Collections.singletonList( - VspZusammenUtil.buildStructuralElement(StructureElement.Nics, Action.DELETE))); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, componentElement, - String.format("Delete all nics of component %s", 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 @@ -229,26 +214,16 @@ public class NicDaoZusammenImpl implements NicDao { private ZusammenElement nicQuestionnaireToZusammen(String questionnaireData, Action action) { ZusammenElement questionnaireElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Questionnaire, action); + buildStructuralElement(ElementType.NicQuestionnaire, action); questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); return questionnaireElement; } - private ZusammenElement buildZusammenElement(Id elementId, Action action) { - ZusammenElement element = new ZusammenElement(); - element.setElementId(elementId); - element.setAction(action); - return element; - } - private ZusammenElement buildNicElement(NicEntity nic, Action action) { - ZusammenElement nicElement = new ZusammenElement(); - nicElement.setAction(action); - if (nic.getId() != null) { - nicElement.setElementId(new Id(nic.getId())); - } + ZusammenElement nicElement = + buildElement(nic.getId() == null ? null : new Id(nic.getId()), action); Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.Nic); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Nic); info.addProperty(ElementPropertyName.compositionData.name(), nic.getCompositionData()); nicElement.setInfo(info); nicElement.setData(new ByteArrayInputStream(nic.getCompositionData().getBytes())); 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 ea51b770bf..5d1ef125fd 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 @@ -1,15 +1,16 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; 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; -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 com.amdocs.zusammen.utils.fileutils.FileUtils; +import org.apache.commons.io.IOUtils; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDao; @@ -18,11 +19,18 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStru 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.Arrays; import java.util.Optional; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class OrchestrationTemplateCandidateDaoZusammenImpl implements OrchestrationTemplateCandidateDao { + private static final Logger logger = LoggerFactory.getLogger(OrchestrationTemplateCandidateDaoZusammenImpl.class); @@ -39,95 +47,163 @@ public class OrchestrationTemplateCandidateDaoZusammenImpl @Override public OrchestrationTemplateCandidateData get(String vspId, Version version) { - logger.info("Getting orchestration template for vsp id -> " + vspId); + logger.info("Getting orchestration template for VendorSoftwareProduct id -> " + vspId); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); - ElementContext elementContext = new ElementContext(itemId, versionId, - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); Optional candidateElement = zusammenAdaptor.getElementByName(context, elementContext, null, - StructureElement.OrchestrationTemplateCandidate.name()); + ElementType.OrchestrationTemplateCandidate.name()); if (candidateElement.isPresent()) { + if (hasEmptyData(candidateElement.get().getData())) { + return null; + } OrchestrationTemplateCandidateData candidateData = new OrchestrationTemplateCandidateData(); candidateData.setFilesDataStructure( new String(FileUtils.toByteArray(candidateElement.get().getData()))); - zusammenAdaptor + Optional candidateContentElement = zusammenAdaptor .getElementByName(context, elementContext, candidateElement.get().getElementId(), - StructureElement.OrchestrationTemplateCandidateContent.name()) - .ifPresent(candidateContentElement -> candidateData.setContentData( - ByteBuffer.wrap(FileUtils.toByteArray(candidateContentElement.getData())))); - logger.info("Finished getting orchestration template for vsp id -> " + vspId); + ElementType.OrchestrationTemplateCandidateContent.name()); + + if (candidateContentElement.isPresent()) { + candidateData.setContentData( + ByteBuffer.wrap(FileUtils.toByteArray(candidateContentElement.get().getData()))); + candidateData.setFileSuffix(candidateContentElement.get().getInfo() + .getProperty(InfoPropertyName.fileSuffix.name())); + candidateData.setFileName(candidateContentElement.get().getInfo() + .getProperty(InfoPropertyName.fileName.name())); + } + logger + .info("Finished getting orchestration template for VendorSoftwareProduct id -> " + vspId); return candidateData; } - logger.info(String.format("Orchestration template for vsp id %s does not exist", vspId)); + logger.info(String + .format("Orchestration template for VendorSoftwareProduct id %s does not exist", vspId)); return null; } @Override - public void update(String vspId, OrchestrationTemplateCandidateData candidateData) { - logger.info("Uploading candidate data entity for vsp id -> " + vspId); + public OrchestrationTemplateCandidateData getInfo(String vspId, Version version) { + logger.info("Getting orchestration template info for VendorSoftwareProduct id -> " + vspId); + + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); - ElementContext elementContext = new ElementContext(itemId, versionId); + Optional candidateElement = + zusammenAdaptor.getElementInfoByName(context, elementContext, null, + ElementType.OrchestrationTemplateCandidate.name()); + if (candidateElement.isPresent()) { + OrchestrationTemplateCandidateData candidateData = new OrchestrationTemplateCandidateData(); - ZusammenElement candidateElement = VspZusammenUtil - .buildStructuralElement(StructureElement.OrchestrationTemplateCandidate, Action.UPDATE); + Optional candidateContentElement = zusammenAdaptor + .getElementByName(context, elementContext, candidateElement.get().getId(), + ElementType.OrchestrationTemplateCandidateContent.name()); + + if (candidateContentElement.isPresent()) { + candidateData.setFileSuffix(candidateContentElement.get().getInfo() + .getProperty(InfoPropertyName.fileSuffix.name())); + candidateData.setFileName(candidateContentElement.get().getInfo() + .getProperty(InfoPropertyName.fileName.name())); + } + logger.info( + "Finished getting orchestration template info for VendorSoftwareProduct id -> " + vspId); + return candidateData; + } + logger.info(String + .format("Orchestration template info for VendorSoftwareProduct id %s does not exist", + vspId)); + return null; + } + + @Override + public void update(String vspId, Version version, + OrchestrationTemplateCandidateData candidateData) { + logger.info("Uploading candidate data entity for VendorSoftwareProduct id -> " + vspId); + + ZusammenElement candidateElement = + buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.UPDATE); candidateElement .setData(new ByteArrayInputStream(candidateData.getFilesDataStructure().getBytes())); - ZusammenElement candidateContentElement = VspZusammenUtil - .buildStructuralElement(StructureElement.OrchestrationTemplateCandidateContent, Action.UPDATE); + + ZusammenElement candidateContentElement = + buildStructuralElement(ElementType.OrchestrationTemplateCandidateContent, Action.UPDATE); candidateContentElement .setData(new ByteArrayInputStream(candidateData.getContentData().array())); + candidateContentElement.getInfo() + .addProperty(InfoPropertyName.fileSuffix.name(), candidateData.getFileSuffix()); + candidateContentElement.getInfo() + .addProperty(InfoPropertyName.fileName.name(), candidateData.getFileName()); 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 uploading candidate data entity for VendorSoftwareProduct id -> " + vspId); } + @Override public void updateStructure(String vspId, Version version, FilesDataStructure fileDataStructure) { logger.info("Updating orchestration template for VSP id -> " + vspId); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); - ElementContext elementContext = new ElementContext(itemId, versionId); - - ZusammenElement candidateElement = VspZusammenUtil - .buildStructuralElement(StructureElement.OrchestrationTemplateCandidate, Action.UPDATE); + 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); + logger + .info("Finished uploading candidate data entity for VendorSoftwareProduct id -> " + vspId); } @Override public Optional getStructure(String vspId, Version version) { - logger.info("Getting orchestration template structure for vsp id -> " + vspId); + logger + .info("Getting orchestration template structure for VendorSoftwareProduct id -> " + vspId); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); - ElementContext elementContext = new ElementContext(itemId, versionId, - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); - logger.info("Finished getting orchestration template structure for vsp id -> " + vspId); + logger.info( + "Finished getting orchestration template structure for VendorSoftwareProduct id -> " + + vspId); Optional element = zusammenAdaptor.getElementByName(context, elementContext, null, - StructureElement.OrchestrationTemplateCandidate.name()); + ElementType.OrchestrationTemplateCandidate.name()); if (element.isPresent()) { + if (hasEmptyData(element.get().getData())) { + return Optional.empty(); + } return Optional.of(new String(FileUtils.toByteArray(element.get().getData()))); } else { return Optional.empty(); } + } + + private boolean hasEmptyData(InputStream elementData) { + String emptyData = "{}"; + byte[] byteElementData; + try { + byteElementData = IOUtils.toByteArray(elementData); + } catch (IOException ex) { + ex.printStackTrace(); + return false; + } + if (Arrays.equals(emptyData.getBytes(), byteElementData)) { + return true; + } + return false; + } + public enum InfoPropertyName { + fileSuffix, + 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/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 2b6d52a38a..d02e8541f4 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 @@ -3,22 +3,27 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; 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; -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 com.amdocs.zusammen.utils.fileutils.FileUtils; +import org.apache.commons.io.IOUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadData; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; 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.Arrays; 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 ZusammenAdaptor zusammenAdaptor; @@ -33,79 +38,128 @@ public class OrchestrationTemplateDaoZusammenImpl implements OrchestrationTempla } @Override - public String getValidationData(String vspId, Version version) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + 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, null, - StructureElement.OrchestrationTemplate.name()); - if (elementInfo.isPresent()) { - Optional element = - zusammenAdaptor.getElementByName(context, elementContext, elementInfo.get().getId(), - StructureElement.OrchestrationTemplateValidationData.name()); - if (element.isPresent()) { - return new String(FileUtils.toByteArray(element.get().getData())); - } + .getElementInfoByName(context, elementContext, vspModel.get().getId(), + ElementType.OrchestrationTemplate.name()); + if (!elementInfo.isPresent()) { + return null; } - 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.fileSuffix.name())); + orchestrationTemplate + .setFileName(element.get().getInfo().getProperty(InfoPropertyName.fileName.name())); + if (!hasEmptyData(element.get().getData())) { + orchestrationTemplate + .setValidationData(new String(FileUtils.toByteArray(element.get().getData()))); + } + return orchestrationTemplate; } @Override - public UploadDataEntity getOrchestrationTemplate(String vspId, Version version) { + public OrchestrationTemplateEntity get(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); - UploadDataEntity uploadData = new UploadDataEntity(); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + OrchestrationTemplateEntity orchestrationTemplate = new OrchestrationTemplateEntity(); - Optional elementInfo = zusammenAdaptor - .getElementInfoByName(context, elementContext, null, - StructureElement.OrchestrationTemplate.name()); - if (elementInfo.isPresent()) { - Optional element = - zusammenAdaptor.getElementByName(context, elementContext, elementInfo.get().getId(), - StructureElement.OrchestrationTemplateValidationData.name()); - element.ifPresent(element1 -> uploadData - .setValidationData(new String(FileUtils.toByteArray(element1.getData())))); - element = - zusammenAdaptor.getElementByName(context, elementContext, elementInfo.get().getId(), - StructureElement.OrchestrationTemplateContent.name()); - element.ifPresent(element1 -> uploadData - .setContentData(ByteBuffer.wrap(FileUtils.toByteArray(element1.getData())))); + Optional vspModel = zusammenAdaptor + .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); + if (!vspModel.isPresent()) { + return orchestrationTemplate; + } + + Optional orchestrationTemplateElement = zusammenAdaptor + .getElementByName(context, elementContext, vspModel.get().getId(), + ElementType.OrchestrationTemplate.name()); + if (!orchestrationTemplateElement.isPresent()) { + return orchestrationTemplate; + } + + if (!hasEmptyData(orchestrationTemplateElement.get().getData())) { + orchestrationTemplate.setContentData( + ByteBuffer.wrap(FileUtils.toByteArray(orchestrationTemplateElement.get().getData()))); } - return uploadData; + + Optional validationDataElement = + zusammenAdaptor.getElementByName(context, elementContext, + orchestrationTemplateElement.get().getElementId(), + ElementType.OrchestrationTemplateValidationData.name()); + if (validationDataElement.isPresent()) { + orchestrationTemplate.setFileSuffix(validationDataElement.get().getInfo() + .getProperty(InfoPropertyName.fileSuffix.name())); + orchestrationTemplate.setFileName(validationDataElement.get().getInfo() + .getProperty(InfoPropertyName.fileName.name())); + if (!hasEmptyData(validationDataElement.get().getData())) { + orchestrationTemplate.setValidationData( + new String(FileUtils.toByteArray(validationDataElement.get().getData()))); + } + } + return orchestrationTemplate; } @Override - public void updateOrchestrationTemplateData(String vspId, UploadData uploadData) { + 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.fileSuffix.name(), orchestrationTemplate.getFileSuffix()); + validationData.getInfo() + .addProperty(InfoPropertyName.fileName.name(), orchestrationTemplate.getFileName()); + ZusammenElement orchestrationTemplateElement = - VspZusammenUtil.buildStructuralElement(StructureElement.OrchestrationTemplate, null); - ZusammenElement orchestrationTemplateValidationDataElement = - VspZusammenUtil - .buildStructuralElement(StructureElement.OrchestrationTemplateValidationData, Action.UPDATE); - orchestrationTemplateValidationDataElement.setData(new ByteArrayInputStream(uploadData - .getValidationData().getBytes())); - ZusammenElement orchestrationTemplateContent = - VspZusammenUtil.buildStructuralElement(StructureElement.OrchestrationTemplateContent, Action.UPDATE); - orchestrationTemplateContent - .setData(new ByteArrayInputStream(uploadData.getContentData().array())); - orchestrationTemplateElement.addSubElement(orchestrationTemplateValidationDataElement); - orchestrationTemplateElement.addSubElement(orchestrationTemplateContent); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - - zusammenAdaptor.saveElement(context, elementContext, orchestrationTemplateElement, "Update " + - "Orchestration Template"); + buildStructuralElement(ElementType.OrchestrationTemplate, Action.UPDATE); + orchestrationTemplateElement + .setData(new ByteArrayInputStream(orchestrationTemplate.getContentData().array())); + orchestrationTemplateElement.addSubElement(validationData); + + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(orchestrationTemplateElement); + + zusammenAdaptor.saveElement(context, elementContext, vspModel, "Update Orchestration Template"); } + private boolean hasEmptyData(InputStream elementData) { + String emptyData = "{}"; + byte[] byteElementData; + try { + byteElementData = IOUtils.toByteArray(elementData); + } catch (IOException ex) { + ex.printStackTrace(); + return false; + } + if (Arrays.equals(emptyData.getBytes(), byteElementData)) { + return true; + } + return false; + } + + private enum InfoPropertyName { + fileSuffix, + 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/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 b0cff4371e..d74900bdf6 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 @@ -8,34 +8,35 @@ 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 org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor; 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 org.openecomp.types.ElementPropertyName; import java.io.ByteArrayInputStream; -import java.nio.ByteBuffer; 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.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; + /** * @author Avrahamg. * @since March 23, 2017 */ public class ProcessDaoZusammenImpl implements ProcessDao { - private static final String NAME = "name"; - private static final String ELEMENT_TYPE = "type"; - private static final String ARTIFACT_NAME = "artifactName"; - private static final String DESCRIPTION = "description"; - private static final String PROCESS_TYPE = "processType"; - private ZusammenAdaptor zusammenAdaptor; public ProcessDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { @@ -52,85 +53,59 @@ public class ProcessDaoZusammenImpl implements ProcessDao { ZusammenElement processElement = buildProcessElement(processEntity, Action.CREATE); ZusammenElement processesElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Processes, null); + buildStructuralElement(ElementType.Processes, Action.IGNORE); ZusammenElement aggregatedElement = VspZusammenUtil.aggregateElements(processesElement, processElement); ZusammenElement componentElement; if (processEntity.getComponentId() != null) { - componentElement = createParentElement(processEntity); + componentElement = buildElement(new Id(processEntity.getComponentId()), Action.IGNORE); aggregatedElement = VspZusammenUtil.aggregateElements(componentElement, aggregatedElement); } - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(processEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); - Optional savedElement = + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, aggregatedElement, "Create process"); - savedElement.ifPresent(element -> { - if (processEntity.getComponentId() == null) { - processEntity.setId(element.getSubElements().iterator().next() - .getElementId().getValue()); - } else { - processEntity.setId(element.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue()); - } - }); + 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 process) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(process.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(process.getVersion())); - - Optional elementOptional = - zusammenAdaptor.getElement(context, elementContext, process.getId()); - - if (elementOptional.isPresent()) { - Element element = elementOptional.get(); - process.setName(element.getInfo().getProperty(NAME)); - process.setArtifactName(element.getInfo().getProperty(ARTIFACT_NAME)); - process.setDescription(element.getInfo().getProperty(DESCRIPTION)); - process.setType(element.getInfo().getProperty - (PROCESS_TYPE) != null ? ProcessType.valueOf(element.getInfo().getProperty - (PROCESS_TYPE)) : null); - - process.setArtifact(ByteBuffer.wrap(FileUtils.toByteArray(element.getData()))); - return process; - } else { - return null; - } + 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) { - ZusammenElement processElement = buildProcessElement(processEntity, Action.UPDATE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(processEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + ProcessEntity retrieved = getArtifact(processEntity); + if (retrieved != null && retrieved.getArtifact() != null) { + processEntity.setArtifactName(retrieved.getArtifactName()); + processEntity.setArtifact(retrieved.getArtifact()); + } - Optional element = - zusammenAdaptor.saveElement(context, elementContext, processElement, "Create process"); - System.out.println(element.get().getElementId()); + update(processEntity, "Update process"); } @Override public void delete(ProcessEntity processEntity) { - ZusammenElement processElement = new ZusammenElement(); - processElement.setElementId(new Id(processEntity.getId())); - processElement.setAction(Action.DELETE); + ZusammenElement processElement = buildElement(new Id(processEntity.getId()), Action.DELETE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(processEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + 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())); @@ -138,69 +113,145 @@ public class ProcessDaoZusammenImpl implements ProcessDao { @Override public void deleteAll(ProcessEntity processEntity) { - ZusammenElement aggregatedElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Processes, Action.DELETE); + 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()); + + /* ZusammenElement aggregatedElement = + buildStructuralElement(ElementType.Processes, Action.DELETE); if (processEntity.getComponentId() != null) { ZusammenElement componentElement = createParentElement(processEntity); - aggregatedElement = VspZusammenUtil.aggregateElements(componentElement, + aggregatedElement = VspaggregateElements(componentElement, aggregatedElement); } - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(processEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, aggregatedElement, "Delete All processes"); + zusammenAdaptor.saveElement(context, elementContext, aggregatedElement, "Delete All + processes");*/ + + 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 deleteVspAll(String vspId, Version version) { - ProcessEntity processEntity = new ProcessEntity(); + /* ProcessEntity processEntity = new ProcessEntity(); processEntity.setVersion(version); processEntity.setVspId(vspId); - deleteAll(processEntity); + deleteAll(processEntity); */ + + 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 Collection list(ProcessEntity process) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(process.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(process.getVersion())); + 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 deleteArtifact(ProcessEntity processEntity) { + ProcessEntity retrieved = get(processEntity); + if (retrieved != null) { + retrieved.setArtifactName(null); + retrieved.setArtifact(null); + + update(retrieved, "Delete process artifact"); + } + } + + @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(process), StructureElement.Processes.name()); + 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 -> mapElementInfoToProcess( - process.getVspId(), process.getVersion(), process.getComponentId(), - elementInfo)) + .map(elementInfo -> convertToProcessEntity(elementInfo, convertor, processEntity)) .collect(Collectors.toList()); } - private Id extractParentElementId(ProcessEntity processEntity) { - return processEntity.getComponentId() == null ? null : new Id(processEntity.getComponentId()); + 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; } - private ProcessEntity mapElementInfoToProcess(String vspId, Version version, - String componentId, - ElementInfo elementInfo) { - ProcessEntity processEntity = new ProcessEntity(vspId, version, componentId, elementInfo - .getId().getValue()); - processEntity.setName((String) elementInfo.getInfo().getProperties().get(NAME)); - processEntity - .setArtifactName((String) elementInfo.getInfo().getProperties().get(ARTIFACT_NAME)); - processEntity.setDescription((String) elementInfo.getInfo().getProperties().get(DESCRIPTION)); - processEntity.setType( elementInfo.getInfo().getProperties().get(PROCESS_TYPE) != null ? - ProcessType.valueOf((String) elementInfo.getInfo().getProperties().get(PROCESS_TYPE)) : - null); - return processEntity; + 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); + } + + private Id extractParentElementId(ProcessEntity processEntity) { + return processEntity.getComponentId() == null ? null : new Id(processEntity.getComponentId()); } private ZusammenElement buildProcessElement(ProcessEntity process, Action action) { @@ -208,14 +259,12 @@ public class ProcessDaoZusammenImpl implements ProcessDao { Info info = new Info(); info.setName(process.getName()); info.addProperty(NAME, process.getName()); - info.addProperty(ELEMENT_TYPE, ElementType.Process); + 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 = new ZusammenElement(); - processElement.setElementId(new Id(process.getId())); - processElement.setAction(action); + ZusammenElement processElement = buildElement(new Id(process.getId()), action); processElement.setInfo(info); if (Objects.nonNull(process.getArtifact())) { processElement.setData(new ByteArrayInputStream(process.getArtifact().array())); @@ -223,10 +272,4 @@ public class ProcessDaoZusammenImpl implements ProcessDao { return processElement; } - private ZusammenElement createParentElement(ProcessEntity entity) { - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setElementId(new Id(entity.getComponentId())); - componentElement.setAction(Action.IGNORE); - 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/StructureElement.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/StructureElement.java deleted file mode 100644 index 6f15f5cdee..0000000000 --- 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/StructureElement.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; - -public enum StructureElement { - General, - OrchestrationTemplateCandidate, - OrchestrationTemplate, - OrchestrationTemplateValidationData, - OrchestrationTemplateContent, - OrchestrationTemplateCandidateValidationData, - OrchestrationTemplateCandidateContent, - Networks, - Components, - Nics, - Processes, - Mibs, - SNMP_TRAP, - SNMP_POLL, - VES_EVENTS, - Questionnaire, - ComponentDependencies, - Computes, - Images, - DeploymentFlavors -} 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 517a01e58d..aa192ede17 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 @@ -1,16 +1,15 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; 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 com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.ItemVersion; -import com.amdocs.zusammen.utils.fileutils.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToVSPGeneralConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToVSPQuestionnaireConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspQuestionnaireEntity; import org.openecomp.sdc.versioning.VersioningManagerFactory; @@ -20,10 +19,14 @@ import org.openecomp.sdc.versioning.types.VersionableEntityStoreType; import java.io.ByteArrayInputStream; import java.util.Collection; -import java.util.Date; 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) { @@ -33,7 +36,8 @@ public class VendorSoftwareProductInfoDaoZusammenImpl implements VendorSoftwareP @Override public void registerVersioning(String versionableEntityType) { VersionableEntityMetadata metadata = - new VersionableEntityMetadata(VersionableEntityStoreType.Zusammen, "vsp", null, null); + new VersionableEntityMetadata(VersionableEntityStoreType.Zusammen, "VendorSoftwareProduct", + null, null); VersioningManagerFactory.getInstance().createInterface() .register(versionableEntityType, metadata); @@ -41,113 +45,173 @@ public class VendorSoftwareProductInfoDaoZusammenImpl implements VendorSoftwareP @Override public Collection list(VspDetails entity) { - return zusammenAdaptor.listItems(ZusammenUtil.createSessionContext()).stream().filter - (vspEntity-> "vsp".equals(vspEntity.getInfo().getProperty("type"))) - .map(item -> mapInfoToVspDetails( - item.getId().getValue(), null, item.getInfo(), - item.getModificationTime(), item.getCreationTime())) + ElementToVSPGeneralConvertor convertor = new ElementToVSPGeneralConvertor(); + + + return zusammenAdaptor.listItems(createSessionContext()).stream() + .filter(item -> "VendorSoftwareProduct".equals(item.getInfo().getProperty("item_type"))) + .map(item -> convertor.convert(item)) .collect(Collectors.toList()); } + @Override public void create(VspDetails vspDetails) { - SessionContext context = ZusammenUtil.createSessionContext(); + ZusammenElement generalElement = mapVspDetailsToZusammenElement(vspDetails, Action.CREATE); - Id itemId = zusammenAdaptor.createItem(context, mapVspDetailsToZusammenItemInfo(vspDetails)); - Id versionId = - zusammenAdaptor.createVersion(context, itemId, null, ZusammenUtil.createFirstVersionData()); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, generalElement, + "Create VSP General Info Element"); - ZusammenElement generalElement = mapVspDetailsToZusammenElement(vspDetails, Action.CREATE); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, versionId), - generalElement, "Create VSP General Info Element"); + createVspStructure(context, elementContext); + } + + private void createVspStructure(SessionContext context, ElementContext elementContext) { + createOrchestrationTemplateCandidateStructure(context, elementContext); + createVspModelStructure(context, elementContext); - vspDetails.setId(itemId.getValue());//set id for caller + 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"); } - @Override - public void update(VspDetails vspDetails) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspDetails.getId()); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); + private void createOrchestrationTemplateCandidateStructure(SessionContext context, + ElementContext elementContext) { + ByteArrayInputStream emptyData = new ByteArrayInputStream(EMPTY_DATA.getBytes()); - zusammenAdaptor.updateItem(context, itemId, mapVspDetailsToZusammenItemInfo(vspDetails)); + ZusammenElement candidateContentElement = + buildStructuralElement(ElementType.OrchestrationTemplateCandidateContent, Action.CREATE); + candidateContentElement.setData(emptyData); - ZusammenElement generalElement = mapVspDetailsToZusammenElement(vspDetails, Action.UPDATE); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, versionId), - generalElement, "Update VSP General Info Element"); + ZusammenElement candidateElement = + buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.CREATE); + candidateElement.setData(emptyData); + candidateElement.addSubElement(candidateContentElement); + + zusammenAdaptor.saveElement(context, elementContext, candidateElement, + "Create Orchestration Template Candidate Elements"); } - @Override - public VspDetails get(VspDetails vspDetails) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspDetails.getId()); - ItemVersion itemVersion = VspZusammenUtil.getFirstVersion(context, itemId, zusammenAdaptor); - ElementContext elementContext = new ElementContext(itemId, itemVersion.getId(), - VspZusammenUtil.getVersionTag(vspDetails.getVersion())); + 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"); + } - return zusammenAdaptor - .getElementInfoByName(context, elementContext, null, StructureElement.General.name()) - .map(generalElementInfo -> mapInfoToVspDetails( - vspDetails.getId(), vspDetails.getVersion(), generalElementInfo.getInfo(), - itemVersion.getModificationTime(), itemVersion.getCreationTime())) - .orElse(null); + private ZusammenElement buildOrchestrationTemplateStructure() { + ByteArrayInputStream emptyData = new ByteArrayInputStream(EMPTY_DATA.getBytes()); + + ZusammenElement validationData = + buildStructuralElement(ElementType.OrchestrationTemplateValidationData, Action.CREATE); + validationData.setData(emptyData); + + ZusammenElement orchestrationTemplate = + buildStructuralElement(ElementType.OrchestrationTemplate, Action.CREATE); + orchestrationTemplate.setData(emptyData); + orchestrationTemplate.addSubElement(validationData); + + 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; + } @Override - public void delete(VspDetails entity) { + 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 void updateOldVersionIndication(VspDetails vspDetails) { - VspDetails retrieved = get(vspDetails); - if (retrieved != null) { - retrieved.setOldVersion(vspDetails.getOldVersion()); - update(retrieved); - } + public VspDetails get(VspDetails vspDetails) { + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()); + VspDetails vsp = zusammenAdaptor.getElementInfoByName(context, elementContext, null, + ElementType.VendorSoftwareProduct.name()) + .map(new ElementToVSPGeneralConvertor()::convert) + .orElse(null); + vsp.setId(vspDetails.getId()); + vsp.setVersion(vspDetails.getVersion()); + return vsp; + } + + @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); } @Override public void updateQuestionnaireData(String vspId, Version version, String questionnaireData) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); + SessionContext context = createSessionContext(); ZusammenElement questionnaireElement = mapQuestionnaireToZusammenElement(questionnaireData); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, versionId), + zusammenAdaptor.saveElement(context, new ElementContext(vspId, version.getId()), questionnaireElement, "Update VSP Questionnaire"); } - @Override + /* @Override public String getQuestionnaireData(String vspId, Version version) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); + SessionContext context = createSessionContext(); - return zusammenAdaptor.getElementByName(context, - new ElementContext(itemId, versionId, VspZusammenUtil.getVersionTag(version)), null, - StructureElement.Questionnaire.name()) + return zusammenAdaptor + .getElementByName(context, new ElementContext(vspId, version.getId()), null, + ElementType.Questionnaire.name()) .map(questionnaireElement -> new String(FileUtils.toByteArray(questionnaireElement.getData()))) .orElse(null); - } + }*/ @Override public VspQuestionnaireEntity getQuestionnaire(String vspId, Version version) { - VspQuestionnaireEntity entity = new VspQuestionnaireEntity(); + + SessionContext context = createSessionContext(); + ElementToVSPQuestionnaireConvertor convertor = new ElementToVSPQuestionnaireConvertor(); + VspQuestionnaireEntity entity = convertor.convert(zusammenAdaptor + .getElementByName(context, new ElementContext(vspId, version.getId()), null, + ElementType.VSPQuestionnaire.name()).map(element -> element).orElse(null)); entity.setId(vspId); entity.setVersion(version); - entity.setQuestionnaireData(getQuestionnaireData(vspId, version)); return entity; } - @Override - public void deleteAll(String vspId, Version version) { - - } - @Override public boolean isManual(String vspId, Version version) { final VspDetails vspDetails = get(new VspDetails(vspId, version)); @@ -159,29 +223,27 @@ public class VendorSoftwareProductInfoDaoZusammenImpl implements VendorSoftwareP return false; } - private Info mapVspDetailsToZusammenItemInfo(VspDetails vspDetails) { - Info info = new Info(); - info.setName(vspDetails.getName()); - info.setDescription(vspDetails.getDescription()); - info.addProperty("type", "vsp"); - addVspDetailsToInfo(info, vspDetails); - return info; - } - private ZusammenElement mapVspDetailsToZusammenElement(VspDetails vspDetails, Action action) { ZusammenElement generalElement = - VspZusammenUtil.buildStructuralElement(StructureElement.General, action); + buildStructuralElement(ElementType.VendorSoftwareProduct, action); addVspDetailsToInfo(generalElement.getInfo(), vspDetails); return generalElement; } private ZusammenElement mapQuestionnaireToZusammenElement(String questionnaireData) { ZusammenElement questionnaireElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Questionnaire, Action.UPDATE); + buildStructuralElement(ElementType.VSPQuestionnaire, Action.UPDATE); questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); return questionnaireElement; } + private ZusammenElement mapTestElementToZusammenElement(String elementData) { + ZusammenElement testElement = + buildStructuralElement(ElementType.test, Action.UPDATE); + testElement.setData(new ByteArrayInputStream(elementData.getBytes())); + return testElement; + } + private void addVspDetailsToInfo(Info info, VspDetails vspDetails) { info.addProperty(InfoPropertyName.name.name(), vspDetails.getName()); info.addProperty(InfoPropertyName.description.name(), vspDetails.getDescription()); @@ -191,45 +253,14 @@ public class VendorSoftwareProductInfoDaoZusammenImpl implements VendorSoftwareP info.addProperty(InfoPropertyName.vendorId.name(), vspDetails.getVendorId()); info.addProperty(InfoPropertyName.vendorName.name(), vspDetails.getVendorName()); if (vspDetails.getVlmVersion() != null) { - info.addProperty( - InfoPropertyName.vendorVersion.name(), vspDetails.getVlmVersion().toString()); + info.addProperty(InfoPropertyName.vendorVersion.name(), vspDetails.getVlmVersion().getId()); } info.addProperty(InfoPropertyName.licenseAgreement.name(), vspDetails.getLicenseAgreement()); info.addProperty(InfoPropertyName.featureGroups.name(), vspDetails.getFeatureGroups()); - info.addProperty(InfoPropertyName.oldVersion.name(), vspDetails.getOldVersion()); info.addProperty(InfoPropertyName.onboardingMethod.name(), vspDetails.getOnboardingMethod()); - info.addProperty(InfoPropertyName.obBoardingOrigin.name(), vspDetails.getOnboardingOrigin()); - info.addProperty(InfoPropertyName.networkPackageName.name(), vspDetails.getNetworkPackageName()); - } - - private VspDetails mapInfoToVspDetails(String vspId, Version version, Info info, - Date modificationTime, Date creationTime) { - VspDetails vspDetails = new VspDetails(vspId, version); - vspDetails.setName(info.getProperty(InfoPropertyName.name.name())); - vspDetails.setDescription(info.getProperty(InfoPropertyName.description.name())); - vspDetails.setCategory(info.getProperty(InfoPropertyName.category.name())); - vspDetails.setSubCategory(info.getProperty(InfoPropertyName.subCategory.name())); - vspDetails.setVendorId(info.getProperty(InfoPropertyName.vendorId.name())); - vspDetails.setVendorName(info.getProperty(InfoPropertyName.vendorName.name())); - vspDetails.setVlmVersion( - Version.valueOf(info.getProperty(InfoPropertyName.vendorVersion.name()))); - vspDetails.setLicenseAgreement(info.getProperty(InfoPropertyName.licenseAgreement.name())); - vspDetails.setFeatureGroups(info.getProperty(InfoPropertyName.featureGroups.name())); - - vspDetails.setWritetimeMicroSeconds( - modificationTime == null ? creationTime.getTime() : modificationTime.getTime()); - vspDetails.setVersion(version); - String oldVersion = info.getProperty(InfoPropertyName.oldVersion.name()); - - //Boolean oldVersion = ind == null || "true".equals( ind.toLowerCase()); - vspDetails.setOldVersion(oldVersion); - vspDetails.setOnboardingMethod(info.getProperty(InfoPropertyName.onboardingMethod.name())); - vspDetails.setOnboardingOrigin(info.getProperty(InfoPropertyName.obBoardingOrigin.name())); - vspDetails.setNetworkPackageName(info.getProperty(InfoPropertyName.networkPackageName.name())); - return vspDetails; - } - - private enum InfoPropertyName { + } + + public enum InfoPropertyName { name, description, icon, @@ -240,10 +271,7 @@ public class VendorSoftwareProductInfoDaoZusammenImpl implements VendorSoftwareP vendorVersion, licenseAgreement, featureGroups, - oldVersion, - onboardingMethod, - obBoardingOrigin, - networkPackageName + onboardingMethod } } 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 5e80d4c355..d4dc7e0c4b 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 @@ -1,49 +1,11 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; 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.ItemVersion; -import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.vendorsoftwareproduct.dao.errors.VendorSoftwareProductNotFoundErrorBuilder; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionStatus; import java.util.Objects; -import java.util.Optional; class VspZusammenUtil { - static ItemVersion getFirstVersion(SessionContext context, Id itemId, ZusammenAdaptor - zusammenAdaptor) { - - Optional itemVersion = zusammenAdaptor.getFirstVersion(context, itemId); - - if (!itemVersion.isPresent()) { - throw new CoreException( - new VendorSoftwareProductNotFoundErrorBuilder(itemId.getValue()).build()); - } - return itemVersion.get(); - } - - static Id getFirstVersionId(SessionContext context, Id itemId, ZusammenAdaptor zusammenAdaptor) { - return getFirstVersion(context, itemId, zusammenAdaptor).getId(); - } - - // TODO: 4/25/2017 remove upon working with more than one single version - static String getVersionTag(Version version) { - return version.getStatus() == VersionStatus.Locked - ? null - : version.toString(); - } - - static ZusammenElement buildStructuralElement(StructureElement structureElement, Action action) { - return ZusammenUtil.buildStructuralElement(structureElement.name(), action); - } - static ZusammenElement aggregateElements(ZusammenElement... elements) { ZusammenElement head = null; ZusammenElement father = 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/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 new file mode 100644 index 0000000000..ae88a7e6b0 --- /dev/null +++ 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 @@ -0,0 +1,38 @@ +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 org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; +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())); + } + +} 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 new file mode 100644 index 0000000000..0864ad3482 --- /dev/null +++ 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 @@ -0,0 +1,41 @@ +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 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())); + + } + +} 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 new file mode 100644 index 0000000000..dd3d122560 --- /dev/null +++ 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 @@ -0,0 +1,45 @@ +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 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())); + } + + +} 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 new file mode 100644 index 0000000000..1554a1cc10 --- /dev/null +++ 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 @@ -0,0 +1,21 @@ +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.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; + } +} 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 new file mode 100644 index 0000000000..f73da6af01 --- /dev/null +++ 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 @@ -0,0 +1,45 @@ +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.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; + +public class ElementToCompositionEntityConvertor extends ElementConvertor { + + @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; + } + } + +} 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 new file mode 100644 index 0000000000..0412e03690 --- /dev/null +++ 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 @@ -0,0 +1,40 @@ +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 org.openecomp.convertor.ElementConvertor; +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())); + } + +} 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 new file mode 100644 index 0000000000..7ac25762b0 --- /dev/null +++ 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 @@ -0,0 +1,19 @@ +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.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 new file mode 100644 index 0000000000..48265bf765 --- /dev/null +++ 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 @@ -0,0 +1,40 @@ +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 org.openecomp.convertor.ElementConvertor; +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())); + } + +} 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 new file mode 100644 index 0000000000..8aa59c52f5 --- /dev/null +++ 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 @@ -0,0 +1,40 @@ +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 org.openecomp.convertor.ElementConvertor; +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())); + } + +} 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 new file mode 100644 index 0000000000..2e9cfa0396 --- /dev/null +++ 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 @@ -0,0 +1,19 @@ +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.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 new file mode 100644 index 0000000000..5da9dc4271 --- /dev/null +++ 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 @@ -0,0 +1,23 @@ +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 static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.ARTIFACT_NAME; + +/** + * Created by ayalaben on 9/5/2017. + */ + +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; + } +} 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 new file mode 100644 index 0000000000..6ce24163e6 --- /dev/null +++ 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 @@ -0,0 +1,38 @@ +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 org.openecomp.convertor.ElementConvertor; +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())); + } + +} 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 new file mode 100644 index 0000000000..33788af4e1 --- /dev/null +++ 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 @@ -0,0 +1,39 @@ +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 org.openecomp.convertor.ElementConvertor; +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())); + } + +} 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 new file mode 100644 index 0000000000..ff53153269 --- /dev/null +++ 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 @@ -0,0 +1,21 @@ +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.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 new file mode 100644 index 0000000000..b07df95ecc --- /dev/null +++ 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 @@ -0,0 +1,20 @@ +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.core.utilities.json.JsonUtil; +import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure; + +/** + * Created by ayalaben on 9/6/2017 + */ +public class ElementToOrchestrationTemplateCandidateMapConvertor + extends ElementConvertor { + + @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 new file mode 100644 index 0000000000..5d3ebc32ad --- /dev/null +++ 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 @@ -0,0 +1,53 @@ +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 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 { + + @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; + } + + @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; + } + + + 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 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"; +} 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 new file mode 100644 index 0000000000..bb7e8bb3e8 --- /dev/null +++ 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 @@ -0,0 +1,20 @@ +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; + +/** + * 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; + } +} 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 new file mode 100644 index 0000000000..c5c2f91595 --- /dev/null +++ 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 @@ -0,0 +1,78 @@ +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 com.amdocs.zusammen.datatypes.item.Item; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.VendorSoftwareProductInfoDaoZusammenImpl; +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; + } + VspDetails vspDetails = mapInfoToVspDetails(item.getInfo()); + vspDetails.setId(item.getId().getValue()); + return vspDetails; + } + + @Override + public VspDetails convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + return mapInfoToVspDetails(elementInfo.getInfo()); + + } + + + private VspDetails mapInfoToVspDetails(Info info) { + + VspDetails vspDetails = new VspDetails(); + + vspDetails.setName(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl + .InfoPropertyName.name.name())); + vspDetails.setDescription(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.description.name())); + vspDetails.setIcon(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.icon.name())); + vspDetails.setCategory(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.category.name())); + vspDetails.setSubCategory(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.subCategory.name())); + vspDetails.setVendorId(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.vendorId.name())); + vspDetails.setVendorName(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.vendorName.name())); + if (info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.vendorVersion.name()) != null) { + vspDetails.setVlmVersion(new Version(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.vendorVersion.name()))); + } + + vspDetails.setLicenseAgreement(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.licenseAgreement.name())); + vspDetails.setFeatureGroups(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.featureGroups.name())); + vspDetails.setOnboardingMethod(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.onboardingMethod.name())); + + 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 new file mode 100644 index 0000000000..d51b8b23b3 --- /dev/null +++ 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 @@ -0,0 +1,17 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.utils.fileutils.FileUtils; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspQuestionnaireEntity; + +public class ElementToVSPQuestionnaireConvertor extends ElementConvertor { + @Override + public VspQuestionnaireEntity convert( Element element) { + if(element == null) return null; + VspQuestionnaireEntity entity = new VspQuestionnaireEntity(); + entity.setQuestionnaireData(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 d3c2a22fff..b4c0d29f74 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 @@ -60,9 +60,6 @@ public class VendorSoftwareProductErrorCodes { public static final String SAME_SOURCE_TARGET_COMPONENT = "SAME_SOURCE_TARGET_COMPONENT"; - public static final String VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED = - "VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED"; - 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"; @@ -129,4 +126,7 @@ public class VendorSoftwareProductErrorCodes { public static final String INVALID_EXTENSION = "INVALID_EXTENSION"; + public static final String VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED = + "VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED"; + } 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/CompositionEntityDataManagerFactoryImpl.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/CompositionEntityDataManagerFactoryImpl.java index a7e55bd290..08d911b686 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/CompositionEntityDataManagerFactoryImpl.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/CompositionEntityDataManagerFactoryImpl.java @@ -26,7 +26,6 @@ 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.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionEntityDataManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager; @@ -42,9 +41,8 @@ public class CompositionEntityDataManagerFactoryImpl extends CompositionEntityDa ComponentDaoFactory.getInstance().createInterface(), NicDaoFactory.getInstance().createInterface(), NetworkDaoFactory.getInstance().createInterface(), - ImageDaoFactory.getInstance().createInterface() , + ImageDaoFactory.getInstance().createInterface(), ComputeDaoFactory.getInstance().createInterface(), - DeploymentFlavorDaoFactory.getInstance().createInterface(), - VendorSoftwareProductDaoFactory.getInstance().createInterface()); + DeploymentFlavorDaoFactory.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/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 de29d5b8f0..78914aa0e5 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 @@ -23,8 +23,10 @@ package org.openecomp.sdc.vendorsoftwareproduct.quiestionnaire; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; +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; @@ -47,8 +49,9 @@ import java.util.List; * Created by TALIO on 11/22/2016 */ public class QuestionnaireDataServiceImpl implements QuestionnaireDataService { - private static final VendorSoftwareProductDao vendorSoftwareProductDao = - VendorSoftwareProductDaoFactory.getInstance().createInterface(); + private static final ComponentDao componentDao = + ComponentDaoFactory.getInstance().createInterface(); + private static final NicDao nicDao = NicDaoFactory.getInstance().createInterface(); private static final VendorSoftwareProductInfoDao vspInfoDao = VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); @@ -56,15 +59,11 @@ public class QuestionnaireDataServiceImpl implements QuestionnaireDataService { public InformationArtifactData generateQuestionnaireDataForInformationArtifact(String vspId, Version version) { - - mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); - VspDetails vspDetails = - vspInfoDao.get(new VspDetails(vspId, version)); - Collection componentEntities = - vendorSoftwareProductDao.listComponentsQuestionnaire(vspId, version); - Collection nicEntities = vendorSoftwareProductDao.listNicsByVsp(vspId, 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 = @@ -100,7 +99,6 @@ public class QuestionnaireDataServiceImpl implements QuestionnaireDataService { return componentQuestionnaireList; } - private List getListOfNicQuestionnaireFromJson(Collection entities) { List nicQuestionnaireList = new ArrayList<>(); @@ -112,5 +110,4 @@ public class QuestionnaireDataServiceImpl implements QuestionnaireDataService { 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 100425858f..73b9491e73 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 @@ -23,12 +23,12 @@ 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.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; @@ -57,10 +57,10 @@ import java.util.Optional; public class ManualVspDataCollectionService { - private static final VendorSoftwareProductDao vendorSoftwareProductDao = - VendorSoftwareProductDaoFactory.getInstance().createInterface(); 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 = @@ -75,16 +75,14 @@ public class ManualVspDataCollectionService { private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); - /** * Gets vendor name for the vsp. * * @param vspId the vsp id * @param version the version - * @param user the user * @return the release vendor name */ - public Optional getReleaseVendor(String vspId, Version version, String user) { + public Optional getReleaseVendor(String vspId, Version version) { String vendorName = null; VspDetails vspDetails = vendorSoftwareProductInfoDao.get(new VspDetails(vspId, version)); if (Objects.nonNull(vspDetails)) { @@ -98,14 +96,12 @@ public class ManualVspDataCollectionService { * * @param vspId the vsp id * @param version the version - * @param user the user * @return the allowed flavors */ - public Map getAllowedFlavors(String vspId, Version version, - String user) { + public Map getAllowedFlavors(String vspId, Version version) { Map allowedFlavors = new HashMap<>(); Collection deploymentFlavorEntities = - vendorSoftwareProductDao.listDeploymentFlavors(vspId, version); + deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); if (CollectionUtils.isNotEmpty(deploymentFlavorEntities)) { for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { DeploymentFlavor deploymentFlavorCompositionData = @@ -129,13 +125,12 @@ public class ManualVspDataCollectionService { LicenseFlavor licenseFlavor = getLicenseFlavor(featureGroupId); deploymentFlavorModel.setLicense_flavor(licenseFlavor); //Get sp_part_number - Optional partNumber = getPartNumber(vspVlmId, vlmVersion, featureGroupId, - user); + 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, user); + featureGroupId); vendorInfo.ifPresent(deploymentFlavorModel::setVendor_info); //Gather and set Compute info List componentComputeAssociations = @@ -146,7 +141,7 @@ public class ManualVspDataCollectionService { String componentId = componentComputeAssociation.getComponentId(); String computeFlavorId = componentComputeAssociation.getComputeFlavorId(); Optional computeFlavor = - getComputeFlavor(vspId, version, componentId, computeFlavorId, user); + getComputeFlavor(vspId, version, componentId, computeFlavorId); computeFlavor.ifPresent(deploymentFlavorModel::setCompute_flavor); } } @@ -164,15 +159,13 @@ public class ManualVspDataCollectionService { * * @param vspId the vsp id * @param version the version - * @param user the user * @return the vsp component images */ public Map> getVspComponentImages(String vspId, - Version version, - String user) { + Version version) { Map> vspComponentImages = new HashMap<>(); Collection deploymentFlavorEntities = - vendorSoftwareProductDao.listDeploymentFlavors(vspId, version); + deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { DeploymentFlavor deploymentFlavorCompositionData = deploymentFlavorEntity.getDeploymentFlavorCompositionData(); @@ -184,7 +177,7 @@ public class ManualVspDataCollectionService { componentComputeAssociations) { String componentId = componentComputeAssociation.getComponentId(); List componentImages = - getComponentImages(vspId, version, componentId, user); + getComponentImages(vspId, version, componentId); if (CollectionUtils.isNotEmpty(componentImages)) { vspComponentImages.put(componentId, componentImages); } @@ -199,13 +192,12 @@ public class ManualVspDataCollectionService { * * @param vspId the vsp id * @param version the version - * @param user the user * @return the vsp components */ - public Map getVspComponents(String vspId, Version version, String user) { + public Map getVspComponents(String vspId, Version version) { Map componentIdNameMap = new HashMap<>(); Collection deploymentFlavorEntities = - vendorSoftwareProductDao.listDeploymentFlavors(vspId, version); + deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { DeploymentFlavor deploymentFlavorCompositionData = deploymentFlavorEntity.getDeploymentFlavorCompositionData(); @@ -216,7 +208,7 @@ public class ManualVspDataCollectionService { for (ComponentComputeAssociation componentComputeAssociation : componentComputeAssociations) { String componentId = componentComputeAssociation.getComponentId(); - Optional componentName = getComponentName(vspId, version, componentId, user); + Optional componentName = getComponentName(vspId, version, componentId); componentName.ifPresent(name -> componentIdNameMap.put(componentId, name)); } } @@ -229,13 +221,12 @@ public class ManualVspDataCollectionService { * * @param vspId the vsp id * @param version the version - * @param user the user * @return the vsp component nics */ - public Map> getVspComponentNics(String vspId, Version version, String user) { + public Map> getVspComponentNics(String vspId, Version version) { Map> vspComponentNics = new HashMap<>(); Collection deploymentFlavorEntities = - vendorSoftwareProductDao.listDeploymentFlavors(vspId, version); + deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); if (CollectionUtils.isNotEmpty(deploymentFlavorEntities)) { for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { DeploymentFlavor deploymentFlavorCompositionData = @@ -247,7 +238,7 @@ public class ManualVspDataCollectionService { for (ComponentComputeAssociation componentComputeAssociation : componentComputeAssociations) { String componentId = componentComputeAssociation.getComponentId(); - List componentNics = getComponentNics(vspId, version, componentId, user); + List componentNics = getComponentNics(vspId, version, componentId); if (CollectionUtils.isNotEmpty(componentNics)) { vspComponentNics.put(componentId, componentNics); } @@ -259,8 +250,7 @@ public class ManualVspDataCollectionService { return vspComponentNics; } - private List getComponentNics(String vspId, Version version, String componentId, - String user) { + 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)) { @@ -283,8 +273,8 @@ public class ManualVspDataCollectionService { } private Optional getPartNumber(String vlmId, Version version, - String featureGroupId, String user) { - FeatureGroupModel featureGroup = getFeatureGroup(vlmId, version, featureGroupId, user); + String featureGroupId) { + FeatureGroupModel featureGroup = getFeatureGroup(vlmId, version, featureGroupId); if (Objects.nonNull(featureGroup)) { return Optional.ofNullable(featureGroup.getFeatureGroup().getPartNumber()); } @@ -292,9 +282,9 @@ public class ManualVspDataCollectionService { } private Optional getVendorInfo(String vlmId, String vendorModel, Version version, - String featureGroupId, String user) { + String featureGroupId) { VendorInfo vendorInfo = null; - FeatureGroupModel featureGroup = getFeatureGroup(vlmId, version, featureGroupId, user); + FeatureGroupModel featureGroup = getFeatureGroup(vlmId, version, featureGroupId); if (Objects.nonNull(featureGroup)) { //Process Feature group to get Manufacturer ref no. String manufacturerReferenceNumber = featureGroup.getEntityManufacturerReferenceNumber(); @@ -308,29 +298,28 @@ public class ManualVspDataCollectionService { } private Optional getComputeFlavor(String vspId, Version version, - String componentId, String computeFlavorId, - String user) { + String componentId, String computeFlavorId) { ComputeFlavor computeFlavor = null; ComputeEntity computeQuestionnaire = null; try { computeQuestionnaire = computeDao.getQuestionnaireData(vspId, version, componentId, computeFlavorId); } catch (Exception ex) { - log.debug("",ex); + log.debug("", ex); computeQuestionnaire = null; MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.COLLECT_MANUAL_VSP_TOSCA_DATA, ErrorLevel.INFO.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Failed to get compute questionnaire : " + ex.getMessage()); } - if (computeQuestionnaire != null && Objects.nonNull(computeQuestionnaire)) { + 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.debug("",ex); + log.debug("", ex); compute = null; MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.COLLECT_MANUAL_VSP_TOSCA_DATA, ErrorLevel.INFO.name(), @@ -354,17 +343,15 @@ public class ManualVspDataCollectionService { return Optional.ofNullable(computeFlavor); } - private FeatureGroupModel getFeatureGroup(String vlmId, Version version, String featureGroupId, - String user) { + 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, user); + return vendorLicenseFacade.getFeatureGroupModel(fgInput); } - private Optional getComponentName(String vspId, Version version, String componentId, - String user) { + private Optional getComponentName(String vspId, Version version, String componentId) { ComponentEntity componentEntity = componentDao.get(new ComponentEntity(vspId, version, componentId)); @@ -377,18 +364,16 @@ public class ManualVspDataCollectionService { } private List getComponentImages(String vspId, Version version, - String componentId, String user) { + String componentId) { List multiFlavorVfcImages = new ArrayList<>(); - MultiFlavorVfcImage multiFlavorVfcImage = null; + MultiFlavorVfcImage multiFlavorVfcImage; Collection componentImages = - vendorSoftwareProductDao.listImages(vspId, version, componentId); + imageDao.list(new ImageEntity(vspId, version, componentId, null)); if (Objects.nonNull(componentImages)) { for (ImageEntity componentImage : componentImages) { - String imageId = componentImage.getId(); - ImageEntity imageEntity = vendorSoftwareProductDao.getImage(vspId, version, componentId, - imageId); + ImageEntity imageEntity = imageDao.get(componentImage); ImageEntity imageQuestionnaireDataEntity = imageDao.getQuestionnaireData(vspId, version, - componentId, imageId); + componentId, componentImage.getId()); Image imageCompositionData = imageEntity.getImageCompositionData(); if (Objects.nonNull(imageEntity) && Objects.nonNull(imageQuestionnaireDataEntity) @@ -398,14 +383,14 @@ public class ManualVspDataCollectionService { imageDetails = JsonUtil.json2Object(imageQuestionnaireDataEntity .getQuestionnaireData(), ImageDetails.class); } catch (Exception ex) { - log.debug("",ex); + log.debug("", ex); imageDetails = null; MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.COLLECT_MANUAL_VSP_TOSCA_DATA, ErrorLevel.INFO.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Unable to parse image questionnaire : " + ex.getMessage()); } - if (imageDetails != null && Objects.nonNull(imageDetails) + 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 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 19e48eceaa..6b57649308 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 @@ -47,8 +47,8 @@ import org.openecomp.sdc.tosca.errors.ToscaInvalidSubstituteNodeTemplateErrorBui import org.openecomp.sdc.tosca.errors.ToscaMissingSubstitutionMappingForReqCapErrorBuilder; 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.tosca.services.ToscaExtensionYamlUtil; +import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Component; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentData; 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/CompositionEntityDataManagerImpl.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/CompositionEntityDataManagerImpl.java index 39534cf9b7..ab5ee6c64c 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/CompositionEntityDataManagerImpl.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/CompositionEntityDataManagerImpl.java @@ -37,7 +37,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.CompositionEntity; @@ -78,14 +77,14 @@ import java.util.Set; public class CompositionEntityDataManagerImpl implements CompositionEntityDataManager { private static final String COMPOSITION_ENTITY_DATA_MANAGER_ERR = - "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"; + "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); + LoggerFactory.getLogger(CompositionEntityDataManagerImpl.class); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private Map entities = new HashMap<>(); @@ -99,14 +98,12 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa private ImageDao imageDao; private ComputeDao computeDao; private DeploymentFlavorDao deploymentFlavorDao; - private VendorSoftwareProductDao vendorSoftwareProductDao; public CompositionEntityDataManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, ComponentDao componentDao, NicDao nicDao, NetworkDao networkDao, ImageDao imageDao, ComputeDao computeDao, - DeploymentFlavorDao deploymentFlavorDao, - VendorSoftwareProductDao vendorSoftwareProductDao) { + DeploymentFlavorDao deploymentFlavorDao) { this.vspInfoDao = vspInfoDao; this.componentDao = componentDao; this.nicDao = nicDao; @@ -114,7 +111,6 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa this.imageDao = imageDao; this.computeDao = computeDao; this.deploymentFlavorDao = deploymentFlavorDao; - this.vendorSoftwareProductDao = vendorSoftwareProductDao; } /** @@ -133,27 +129,27 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa 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()); + 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()); + 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()); + new CompositionEntityValidationData(entity.getType(), entity.getId()); String json = - schemaTemplateContext == SchemaTemplateContext.composition ? entity.getCompositionData() - : entity.getQuestionnaireData(); + schemaTemplateContext == SchemaTemplateContext.composition ? entity.getCompositionData() + : entity.getQuestionnaireData(); validationData.setErrors(JsonUtil.validate( - json == null ? JsonUtil.object2Json(new Object()) : json, - generateSchema(schemaTemplateContext, entity.getType(), schemaTemplateInput))); + json == null ? JsonUtil.object2Json(new Object()) : json, + generateSchema(schemaTemplateContext, entity.getType(), schemaTemplateInput))); mdcDataDebugMessage.debugExitMessage(null); return validationData; @@ -169,13 +165,13 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa 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()); + 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)); + new CompositionEntityData(entity, schemaTemplateInput)); } /** @@ -205,10 +201,10 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa @Override public void buildTrees() { Map entitiesValidationData = - new HashMap<>(); + new HashMap<>(); entities.entrySet().forEach( - entry -> addValidationDataEntity(entitiesValidationData, entry.getKey(), - entry.getValue().entity)); + entry -> addValidationDataEntity(entitiesValidationData, entry.getKey(), + entry.getValue().entity)); } public Collection getTrees() { @@ -259,14 +255,14 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa } Collection subEntitiesValidationData = - entity.getSubEntitiesValidationData(); + entity.getSubEntitiesValidationData(); return !CollectionUtils.isEmpty(subEntitiesValidationData) && - checkForErrorsInChildren(subEntitiesValidationData); + checkForErrorsInChildren(subEntitiesValidationData); } private boolean checkForErrorsInChildren( - Collection subEntitiesValidationData) { + Collection subEntitiesValidationData) { boolean result = false; for (CompositionEntityValidationData subEntity : subEntitiesValidationData) { if (CollectionUtils.isNotEmpty(subEntity.getErrors())) { @@ -360,10 +356,10 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa //component.setId(CommonMethods.nextUuId()); will be set by the dao component.setQuestionnaireData( - new JsonSchemaDataGenerator( - generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.component, - null)) - .generateData()); + new JsonSchemaDataGenerator( + generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.component, + null)) + .generateData()); componentDao.create(component); @@ -377,9 +373,9 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa //nic.setId(CommonMethods.nextUuId()); will be set by the dao nic.setQuestionnaireData( - new JsonSchemaDataGenerator( - generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.nic, null)) - .generateData()); + new JsonSchemaDataGenerator( + generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.nic, null)) + .generateData()); nicDao.create(nic); @@ -412,28 +408,26 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa return treeAsList; } - public void getEntityListWithErrors(CompositionEntityValidationData entity, + private void getEntityListWithErrors(CompositionEntityValidationData entity, Set compositionSet) { - Collection childNodes = - entity.getSubEntitiesValidationData(); + if(CollectionUtils.isNotEmpty(entity.getErrors())){ + addNodeWithErrors(entity, compositionSet); + } - if (CollectionUtils.isEmpty(childNodes)) { + if (CollectionUtils.isEmpty(entity.getSubEntitiesValidationData())) { return; } - for (CompositionEntityValidationData child : childNodes) { - if (CollectionUtils.isNotEmpty(child.getErrors())) { - addNodeWithErrors(child, compositionSet); - } + for (CompositionEntityValidationData child : entity.getSubEntitiesValidationData()) { getEntityListWithErrors(child, compositionSet); } } - public void addNodeWithErrors(CompositionEntityValidationData node, + private void addNodeWithErrors(CompositionEntityValidationData node, Set entitiesWithErrors) { CompositionEntityValidationData compositionNodeToAdd = new CompositionEntityValidationData(node - .getEntityType(), node.getEntityId()); + .getEntityType(), node.getEntityId()); compositionNodeToAdd.setErrors(node.getErrors()); compositionNodeToAdd.setSubEntitiesValidationData(null); @@ -446,9 +440,9 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa private CompositionEntityData getCompositionEntityDataById(CompositionEntityValidationData - entity) { + entity) { for (Map.Entry entityEntry : entities - .entrySet()) { + .entrySet()) { if (entityEntry.getKey().getId().equals(entity.getEntityId())) { return entityEntry.getValue(); } @@ -458,11 +452,11 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa private void updateValidationCompositionEntityName(Set - compositionSet) { + compositionSet) { for (CompositionEntityValidationData entity : compositionSet) { String compositionData = getCompositionDataAsString(entity); if (entity.getEntityType().equals(CompositionEntityType.vsp) || - Objects.nonNull(compositionData)) { + Objects.nonNull(compositionData)) { entity.setEntityName(getEntityNameByEntityType(compositionData, entity)); } } @@ -497,8 +491,8 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa CompositionEntityData vspEntity = getCompositionEntityDataById(entity); VspQuestionnaireEntity vspQuestionnaireEntity = (VspQuestionnaireEntity) vspEntity.entity; VspDetails vspDetails = - vspInfoDao.get(new VspDetails(vspQuestionnaireEntity.getId(), - vspQuestionnaireEntity.getVersion())); + vspInfoDao.get(new VspDetails(vspQuestionnaireEntity.getId(), + vspQuestionnaireEntity.getVersion())); return vspDetails.getName(); } @@ -514,7 +508,7 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa if (hasChildren(node)) { Collection subNodes = - new ArrayList<>(node.getSubEntitiesValidationData()); + new ArrayList<>(node.getSubEntitiesValidationData()); subNodes.forEach(subNode -> removeNodesWithoutErrors(subNode, node)); node.setSubEntitiesValidationData(subNodes); @@ -543,14 +537,14 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa private void addValidationDataEntity( - Map entitiesValidationData, - CompositionEntityId entityId, CompositionEntity entity) { + Map entitiesValidationData, + CompositionEntityId entityId, CompositionEntity entity) { if (entitiesValidationData.containsKey(entityId)) { return; } CompositionEntityValidationData validationData = - new CompositionEntityValidationData(entity.getType(), entity.getId()); + new CompositionEntityValidationData(entity.getType(), entity.getId()); entitiesValidationData.put(entityId, validationData); CompositionEntityId parentEntityId = entityId.getParentId(); @@ -578,16 +572,16 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa if (node.getSubEntitiesValidationData() != null) { node.getSubEntitiesValidationData() - .forEach(subNode -> addErrorsToTree(subNode, nodeId, errors)); + .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())); + "[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())) { @@ -596,20 +590,20 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa } return JsonUtil.validate( - compositionEntityData.entity.getQuestionnaireData() == null - ? JsonUtil.object2Json(new Object()) - : compositionEntityData.entity.getQuestionnaireData(), - getSchema(compositionEntityData.entity.getType(), SchemaTemplateContext.questionnaire, - compositionEntityData.schemaTemplateInput)); + 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); + ? nonDynamicSchemas.computeIfAbsent(compositionEntityType, + k -> generateSchema(schemaTemplateContext, compositionEntityType, null)) + : generateSchema(schemaTemplateContext, compositionEntityType, schemaTemplateInput); } private static class CompositionEntityData { @@ -630,7 +624,7 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa CompositionEntityType compositionEntityType, SchemaTemplateInput schemaTemplateInput) { return SchemaGenerator - .generate(schemaTemplateContext, compositionEntityType, schemaTemplateInput); + .generate(schemaTemplateContext, compositionEntityType, schemaTemplateInput); } @Override @@ -649,46 +643,33 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa image.setId(CommonMethods.nextUuId()); image.setQuestionnaireData( - new JsonSchemaDataGenerator(SchemaGenerator - .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.image, null)) - .generateData()); + new JsonSchemaDataGenerator(SchemaGenerator + .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.image, null)) + .generateData()); imageDao.create(image); mdcDataDebugMessage.debugExitMessage(null, null); return image; } - @Override - public ComputeEntity createCompute(ComputeEntity compute) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id", compute.getVspId(), - compute.getComponentId()); - - compute.setId(CommonMethods.nextUuId()); - compute.setQuestionnaireData( - new JsonSchemaDataGenerator(SchemaGenerator - .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.compute, - null)).generateData()); - - computeDao.create(compute); - - mdcDataDebugMessage.debugExitMessage("VSP id, component id", compute.getVspId(), - compute.getComponentId()); - return compute; - } - 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); - createCompute(computeEntity); + 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) { + componentId) { if (CollectionUtils.isNotEmpty(component.getImages())) { for (Image img : component.getImages()) { ImageEntity imageEntity = new ImageEntity(vspId, version, componentId, 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/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 640777e993..45746ed84e 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 @@ -72,577 +72,591 @@ import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class CandidateServiceImpl implements CandidateService { - protected static final Logger logger = LoggerFactory.getLogger(CandidateServiceImpl.class); - private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + protected static final Logger logger = LoggerFactory.getLogger(CandidateServiceImpl.class); + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private CandidateServiceValidator candidateServiceValidator = new CandidateServiceValidator(); - private ManifestCreator manifestCreator; - private OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDataDao; + private CandidateServiceValidator candidateServiceValidator = new CandidateServiceValidator(); + private ManifestCreator manifestCreator; + private OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDao; - public CandidateServiceImpl(ManifestCreator manifestCreator, - OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDataDao) { - this.manifestCreator = manifestCreator; - this.orchestrationTemplateCandidateDataDao = orchestrationTemplateCandidateDataDao; + public CandidateServiceImpl(ManifestCreator manifestCreator, + OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDao) { + this.manifestCreator = manifestCreator; + this.orchestrationTemplateCandidateDao = orchestrationTemplateCandidateDao; - } + } - public CandidateServiceImpl() { - } + public CandidateServiceImpl() { + } - @Override - public Optional validateNonEmptyFileToUpload(InputStream fileToUpload) { + @Override + public Optional validateNonEmptyFileToUpload(InputStream fileToUpload) { - mdcDataDebugMessage.debugEntryMessage(null); + mdcDataDebugMessage.debugEntryMessage(null); - if (Objects.isNull(fileToUpload)) { - return Optional.of(new ErrorMessage(ErrorLevel.ERROR, - Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); - } else { - try { - int available = fileToUpload.available(); - if (available == 0) { - mdcDataDebugMessage.debugExitMessage(null); - return Optional.of(new ErrorMessage(ErrorLevel.ERROR, - Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); - } - } catch (IOException e) { - logger.debug(e.getMessage(), e); - mdcDataDebugMessage.debugExitMessage(null); - return Optional.of(new ErrorMessage(ErrorLevel.ERROR, - Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); - } + if (Objects.isNull(fileToUpload)) { + return Optional.of(new ErrorMessage(ErrorLevel.ERROR, + Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); + } else { + try { + int available = fileToUpload.available(); + if (available == 0) { + mdcDataDebugMessage.debugExitMessage(null); + return Optional.of(new ErrorMessage(ErrorLevel.ERROR, + Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); } - + } catch (IOException e) { + logger.debug(e.getMessage(), e); mdcDataDebugMessage.debugExitMessage(null); - return Optional.empty(); + return Optional.of(new ErrorMessage(ErrorLevel.ERROR, + Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); + } } - @Override - public Optional validateRawZipData(byte[] uploadedFileData) { - if (Objects.isNull(uploadedFileData)) { - return Optional.of(new ErrorMessage(ErrorLevel.ERROR, - Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); - } - return Optional.empty(); - } - - private String heatStructureTreeToFileDataStructure(HeatStructureTree tree, - FileContentHandler zipContentMap, - Map> uploadErrors, - AnalyzedZipHeatFiles analyzedZipHeatFiles) - throws Exception { - FilesDataStructure structure = new FilesDataStructure(); - Set usedEnvFiles = new HashSet<>(); - addHeatsToFileDataStructure(tree, usedEnvFiles, structure, uploadErrors, - analyzedZipHeatFiles); - handleOtherResources(tree, usedEnvFiles, structure); - FilesDataStructure fileDataStructureFromManifest = - createFileDataStructureFromManifest(zipContentMap.getFileContent - (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) throws Exception { - - - mdcDataDebugMessage.debugEntryMessage(null); - - 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); - } + mdcDataDebugMessage.debugExitMessage(null); + return Optional.empty(); + } - mdcDataDebugMessage.debugExitMessage(null); - return new OrchestrationTemplateCandidateData( - ByteBuffer.wrap(candidateDataEntityTo.getUploadedFileData()), dataStructureJson); - } - - private void balanceManifestFilesWithZipFiles( - FilesDataStructure filesDataStructure, - FileContentHandler fileContentHandler, AnalyzedZipHeatFiles analyzedZipHeatFiles) - throws Exception { - Set zipFileList = fileContentHandler.getFileList(); - filesDataStructure.getNested().addAll(analyzedZipHeatFiles.getNestedFiles()); - List modules = filesDataStructure.getModules(); - if (CollectionUtils.isEmpty(modules)) { - return; - } + @Override + public Optional validateRawZipData(byte[] uploadedFileData) { + if (Objects.isNull(uploadedFileData)) { + return Optional.of(new ErrorMessage(ErrorLevel.ERROR, + Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); + } + return Optional.empty(); + } + + private String heatStructureTreeToFileDataStructure(HeatStructureTree tree, + FileContentHandler zipContentMap, + Map> uploadErrors, + AnalyzedZipHeatFiles analyzedZipHeatFiles) + throws Exception { + FilesDataStructure structure = new FilesDataStructure(); + Set usedEnvFiles = new HashSet<>(); + addHeatsToFileDataStructure(tree, usedEnvFiles, structure, uploadErrors, + analyzedZipHeatFiles); + handleOtherResources(tree, usedEnvFiles, structure); + FilesDataStructure fileDataStructureFromManifest = + createFileDataStructureFromManifest(zipContentMap.getFileContent + (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); + } - 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); - } - } - } - } + @Override + public OrchestrationTemplateCandidateData createCandidateDataEntity( + CandidateDataEntityTo candidateDataEntityTo, InputStream zipFileManifest, + AnalyzedZipHeatFiles analyzedZipHeatFiles) throws Exception { + + + mdcDataDebugMessage.debugEntryMessage(null); + + 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); + + mdcDataDebugMessage.debugExitMessage(null); + return candidateData; + } + + private void balanceManifestFilesWithZipFiles( + FilesDataStructure filesDataStructure, + FileContentHandler fileContentHandler, AnalyzedZipHeatFiles analyzedZipHeatFiles) + throws Exception { + 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().stream().collect(Collectors.toSet())); + fileNames.addAll(filesDataStructure.getNested().stream().collect(Collectors.toSet())); + fileNames.addAll(filesDataStructure.getUnassigned().stream().collect(Collectors.toSet())); + + return fileNames; + } + + private FilesDataStructure createFileDataStructureFromManifest(InputStream isManifestContent) { + + + mdcDataDebugMessage.debugEntryMessage(null); + + 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.setYaml(fileData.getFile()); + module.setIsBase(fileData.getBase()); + addHeatDependenciesToModule(module, fileData.getData()); + 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()); + } + } + + mdcDataDebugMessage.debugExitMessage(null); + 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()); + } + } + } - private void addFileToUnassigned(FilesDataStructure filesDataStructure, Set zipFileList, - String fileName) { - if (isFileExistInZipContains(zipFileList, fileName)) { - filesDataStructure.getUnassigned().add(fileName); - } - } + @Override + public void updateCandidateUploadData(String vspId, Version version, + OrchestrationTemplateCandidateData uploadData) { + mdcDataDebugMessage.debugEntryMessage(null); - private boolean isFileExistInZipContains(Set zipFileList, String fileName) { - return Objects.nonNull(fileName) && zipFileList.contains(fileName); - } + orchestrationTemplateCandidateDao.update(vspId, version, uploadData); - 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().stream().collect(Collectors.toSet())); - fileNames.addAll(filesDataStructure.getNested().stream().collect(Collectors.toSet())); - fileNames.addAll(filesDataStructure.getUnassigned().stream().collect(Collectors.toSet())); - - return fileNames; - } - - private FilesDataStructure createFileDataStructureFromManifest(InputStream isManifestContent) { - - - mdcDataDebugMessage.debugEntryMessage(null); - - 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.setYaml(fileData.getFile()); - module.setIsBase(fileData.getBase()); - addHeatDependenciesToModule(module, fileData.getData()); - 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()); - } - } + mdcDataDebugMessage.debugExitMessage(null); + } - mdcDataDebugMessage.debugExitMessage(null); - return structure; - } + @Override + public Optional getOrchestrationTemplateCandidateFileDataStructure( + String vspId, Version version) { - private void addHeatDependenciesToModule(Module module, List data) { - if (CollectionUtils.isEmpty(data)) { - return; - } + mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); - 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()); - } - } - } + Optional jsonFileDataStructure = + orchestrationTemplateCandidateDao.getStructure(vspId, version); - @Override - public void updateCandidateUploadData(OrchestrationTemplateCandidateData uploadData, - String itemId) { - mdcDataDebugMessage.debugEntryMessage(null); - orchestrationTemplateCandidateDataDao.update(itemId, uploadData); - mdcDataDebugMessage.debugExitMessage(null); + if (jsonFileDataStructure.isPresent() && JsonUtil.isValidJson(jsonFileDataStructure.get())) { + mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); + return Optional + .of(JsonUtil.json2Object(jsonFileDataStructure.get(), FilesDataStructure.class)); + } else { + mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); + return Optional.empty(); } + } - @Override - public Optional getOrchestrationTemplateCandidateFileDataStructure( - String vspId, Version version) { - - mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); - - Optional jsonFileDataStructure = - orchestrationTemplateCandidateDataDao.getStructure(vspId, version); + @Override + public void updateOrchestrationTemplateCandidateFileDataStructure(String vspId, Version version, + FilesDataStructure fileDataStructure) { + OrchestrationTemplateCandidateDaoFactory.getInstance().createInterface() + .updateStructure(vspId, version, fileDataStructure); + } - if (jsonFileDataStructure.isPresent() - && JsonUtil.isValidJson(jsonFileDataStructure.get())) { - mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); - return Optional - .of(JsonUtil.json2Object(jsonFileDataStructure.get(), FilesDataStructure.class)); - } else { - mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); - return Optional.empty(); - } - } + @Override + public OrchestrationTemplateCandidateData getOrchestrationTemplateCandidate(String vspId, + Version version) { + mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); + mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); - @Override - public void updateOrchestrationTemplateCandidateFileDataStructure(String vspId, Version version, - FilesDataStructure fileDataStructure) { - OrchestrationTemplateCandidateDaoFactory.getInstance().createInterface() - .updateStructure(vspId, version, fileDataStructure); - } + return orchestrationTemplateCandidateDao.get(vspId, version); + } - @Override - public OrchestrationTemplateCandidateData getOrchestrationTemplateCandidate(String vspId, - Version version) { - mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); - mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); + @Override + public OrchestrationTemplateCandidateData getOrchestrationTemplateCandidateInfo(String vspId, + Version version) { + mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); + mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); - return orchestrationTemplateCandidateDataDao.get(vspId, version); - } + return orchestrationTemplateCandidateDao.getInfo(vspId, version); + } @Override public String createManifest(VspDetails vspDetails, FilesDataStructure structure) { - mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); - - Optional manifest = manifestCreator.createManifest(vspDetails, structure); - if (!manifest.isPresent()) { - throw new RuntimeException(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()); - } + mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); - mdcDataDebugMessage.debugExitMessage("VSP Id", vspDetails.getId()); - return JsonUtil.object2Json(manifest.get()); - } - - @Override - public Optional createManifest(VspDetails vspDetails, - FileContentHandler fileContentHandler, - AnalyzedZipHeatFiles analyzedZipHeatFiles) { - - - mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); - - mdcDataDebugMessage.debugExitMessage("VSP Id", vspDetails.getId()); - 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, vspId, 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, String vspId, - 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(); - } - } - return baos.toByteArray(); + Optional manifest = manifestCreator.createManifest(vspDetails, structure); + if (!manifest.isPresent()) { + throw new RuntimeException(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()); } - @Override - public Optional> validateFileDataStructure( - FilesDataStructure filesDataStructure) { - return candidateServiceValidator.validateFileDataStructure(filesDataStructure); - } + mdcDataDebugMessage.debugExitMessage("VSP Id", vspDetails.getId()); + return JsonUtil.object2Json(manifest.get()); + } - 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); - } - } - } + @Override + public Optional createManifest(VspDetails vspDetails, + FileContentHandler fileContentHandler, + AnalyzedZipHeatFiles analyzedZipHeatFiles) { - private boolean isManifestNeedsToGetWritten(OnboardingTypesEnum type) { - return type.equals(OnboardingTypesEnum.CSAR); - } - private void handleArtifactsFromTree(HeatStructureTree tree, FilesDataStructure structure) { + mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); - 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())); - } - } + mdcDataDebugMessage.debugExitMessage("VSP Id", vspDetails.getId()); + return manifestCreator.createManifest(vspDetails, fileContentHandler, analyzedZipHeatFiles); + } - private void handleOtherResources(HeatStructureTree tree, Set usedEnvFiles, - FilesDataStructure structure) { - Set others = tree.getOther(); - if (Objects.isNull(others)) { - return; - } + @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, vspId, 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); + } - 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); + @Override + public byte[] replaceManifestInZip(ByteBuffer contentData, String manifest, String vspId, + 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); } - structure.getArtifacts().addAll(artifacts); - structure.getUnassigned().addAll(unassigned); + zos.closeEntry(); + } + if (!manifestWritten) { + writeManifest(manifest, type, zos); + zos.closeEntry(); + } } + return baos.toByteArray(); + } - private boolean isEnvFileUsedByHeatFile(Set usedEnvFiles, HeatStructureTree other) { - if (HeatFileAnalyzer.isEnvFile(other.getFileName())) { - if (usedEnvFiles.contains(other.getFileName())) { - return true; - } - } - return false; - } - - private void addHeatsToFileDataStructure(HeatStructureTree tree, Set usedEnvFiles, - FilesDataStructure structure, - Map> uploadErrors, - AnalyzedZipHeatFiles analyzedZipHeatFiles) - throws Exception { - 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); - + @Override + public Optional> validateFileDataStructure( + FilesDataStructure filesDataStructure) { + return candidateServiceValidator.validateFileDataStructure(filesDataStructure); + } + + 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); + } + } + } + + 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 boolean isEnvFileUsedByHeatFile(Set usedEnvFiles, HeatStructureTree other) { + if (HeatFileAnalyzer.isEnvFile(other.getFileName())) { + if (usedEnvFiles.contains(other.getFileName())) { + return true; + } + } + return false; + } + + private void addHeatsToFileDataStructure(HeatStructureTree tree, Set usedEnvFiles, + FilesDataStructure structure, + Map> uploadErrors, + AnalyzedZipHeatFiles analyzedZipHeatFiles) + throws Exception { + 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); - private boolean isFileModuleFile(String fileName, Set modulesFileNames) { - return modulesFileNames.contains(fileName); - } + } - private boolean isFileBaseFile(String fileName) { - return manifestCreator.isFileBaseFile(fileName); - } + private boolean isFileModuleFile(String fileName, Set modulesFileNames) { + return modulesFileNames.contains(fileName); + } - private void handleSingleHeat(FilesDataStructure structure, List modules, - HeatStructureTree heat, - Map> uploadErrors) { + private boolean isFileBaseFile(String fileName) { + return manifestCreator.isFileBaseFile(fileName); + } + private void handleSingleHeat(FilesDataStructure structure, List modules, + HeatStructureTree heat, + Map> uploadErrors) { - mdcDataDebugMessage.debugEntryMessage(null); - 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); + mdcDataDebugMessage.debugEntryMessage(null); - mdcDataDebugMessage.debugExitMessage(null); + 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) { + mdcDataDebugMessage.debugExitMessage(null); + } + private void handleVolumes(Module module, Set volumeSet, + FilesDataStructure structure, int inx, + Map> uploadErrors) { - mdcDataDebugMessage.debugEntryMessage(null); - for (HeatStructureTree volume : volumeSet) { - 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); - } + mdcDataDebugMessage.debugEntryMessage(null); - mdcDataDebugMessage.debugExitMessage(null); + for (HeatStructureTree volume : volumeSet) { + 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) { + mdcDataDebugMessage.debugExitMessage(null); + } + private void handleEnv(Module module, HeatStructureTree tree, boolean isVolEnv, + FilesDataStructure structure) { - mdcDataDebugMessage.debugEntryMessage(null); - if (Objects.nonNull(tree.getEnv())) { - if (isVolEnv) { - module.setVolEnv(tree.getEnv().getFileName()); - } else { - module.setEnv(tree.getEnv().getFileName()); - } - handleArtifactsFromTree(tree.getEnv(), structure); - } + mdcDataDebugMessage.debugEntryMessage(null); - mdcDataDebugMessage.debugExitMessage(null); + 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); - } + mdcDataDebugMessage.debugExitMessage(null); + } + + 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 eed575ff02..ce18097701 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 @@ -68,7 +68,7 @@ public class ManifestCreatorNamingConventionImpl implements ManifestCreator { addArtifactsToManifestFileDataList(filesDataStructure, fileDataList); ManifestContent manifestContent = createManifest(vspDetails, fileDataList); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); return Optional.of(manifestContent); } @@ -76,7 +76,7 @@ public class ManifestCreatorNamingConventionImpl implements ManifestCreator { FilesDataStructure filesDataStructure, List fileDataList) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); if (CollectionUtils.isNotEmpty(filesDataStructure.getNested())) { for (String nested : filesDataStructure.getNested()) { @@ -84,7 +84,7 @@ public class ManifestCreatorNamingConventionImpl implements ManifestCreator { } } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } @Override @@ -168,7 +168,7 @@ public class ManifestCreatorNamingConventionImpl implements ManifestCreator { FilesDataStructure filesDataStructure, List fileDataList) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); Collection forArtifacts = CollectionUtils .union(filesDataStructure.getArtifacts(), filesDataStructure.getUnassigned()); @@ -178,14 +178,14 @@ public class ManifestCreatorNamingConventionImpl implements ManifestCreator { } } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } private void addModulesToManifestFileDataList( FilesDataStructure filesDataStructure, List fileDataList) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); if (CollectionUtils.isNotEmpty(filesDataStructure.getModules())) { for (Module module : filesDataStructure.getModules()) { @@ -197,7 +197,7 @@ public class ManifestCreatorNamingConventionImpl implements ManifestCreator { } } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } private void addEnv(Module module, FileData fileData) { diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..982277dbaf --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/resources/factoryConfiguration.json @@ -0,0 +1,3 @@ +{ + "org.openecomp.sdc.vendorsoftwareproduct.dao.VspMergeDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.VspMergeDaoFactoryImpl" +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ServiceModelDaoFactoryTest.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ServiceModelDaoFactoryTest.java index 39c14e64fd..4690d75a68 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ServiceModelDaoFactoryTest.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ServiceModelDaoFactoryTest.java @@ -21,7 +21,9 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao; 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; @@ -32,15 +34,19 @@ 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.Tag; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.zusammen.api.ZusammenAdaptor; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.model.impl.zusammen.ServiceModelDaoZusammenImpl; -import org.openecomp.sdc.model.impl.zusammen.StructureElement; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.YamlUtil; +import org.openecomp.sdc.versioning.dao.types.Revision; import org.openecomp.sdc.versioning.dao.types.Version; import org.testng.Assert; import org.testng.annotations.Test; @@ -49,6 +55,7 @@ import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -59,6 +66,10 @@ public class ServiceModelDaoFactoryTest { private static final String baseServiceTemplateName = "baseYaml.yaml"; private static String artifact001; + static { + SessionContextProviderFactory.getInstance().createInterface().create("test"); + } + @Test public void storeServiceModelTest() { @@ -91,14 +102,19 @@ public class ServiceModelDaoFactoryTest { ElementInfo elementInfo = new ElementInfo(); Info info = new Info(); - info.addProperty("base","baseElement"); + info.addProperty("base", "baseElement"); elementInfo.setInfo(info); ElementInfo artifactElementInfo = new ElementInfo(); - artifactElementInfo.setInfo(info); + artifactElementInfo.setInfo(new Info()); + artifactElementInfo.getInfo().setName(ElementType.Artifacts.name()); ElementInfo templateElementInfo = new ElementInfo(); - artifactElementInfo.setInfo(info); + templateElementInfo.setInfo(new Info()); + templateElementInfo.getInfo().setName(ElementType.Templates.name()); + ElementInfo serviceModelElementInfo = new ElementInfo(); + serviceModelElementInfo.setInfo(new Info()); + serviceModelElementInfo.getInfo().setName(ElementType.ServiceModel.name()); ZusammenElement element = new ZusammenElement(); ServiceTemplate serviceTemplate = new ServiceTemplate(); YamlUtil yamlUtil = new YamlUtil(); @@ -111,9 +127,11 @@ public class ServiceModelDaoFactoryTest { zusammenAdaptor); zusammenAdaptor.setItemVersion(itemVersionmock); - zusammenAdaptor.addElementInfo("null"+StructureElement.ServiceModel.name(),elementInfo); - zusammenAdaptor.addElementInfo("null"+StructureElement.Artifacts.name(),artifactElementInfo); - zusammenAdaptor.addElementInfo("null"+StructureElement.Templates.name(),templateElementInfo); + zusammenAdaptor.addElementInfo("null" + ElementType.ServiceModel.name(), elementInfo); + zusammenAdaptor.addElementInfo("null" + ElementType.Artifacts.name(), artifactElementInfo); + zusammenAdaptor.addElementInfo("null" + ElementType.Templates.name(), templateElementInfo); + zusammenAdaptor.addElementInfo("null" + ElementType.ServiceModel.name(), + serviceModelElementInfo); zusammenAdaptor.addElement(element); Object model = @@ -126,11 +144,11 @@ public class ServiceModelDaoFactoryTest { } } - private static void setArtifact(ToscaServiceModel model) - { + private static void setArtifact(ToscaServiceModel model) { artifact001 = - (String) (model).getArtifactFiles().getFileList().toArray()[0]; + (String) (model).getArtifactFiles().getFileList().toArray()[0]; } + private ToscaServiceModel getToscaServiceModel() { Map serviceTemplates = getServiceTemplates(baseServiceTemplateName); @@ -171,128 +189,225 @@ public class ServiceModelDaoFactoryTest { return serviceTemplate; } - private class ZusammenAdaptorMock implements ZusammenAdaptor - { + private class ZusammenAdaptorMock implements ZusammenAdaptor { private ItemVersion itemVersion; - private Map elementInfoMap = new HashMap(); - private Collection elements = new ArrayList<>(); + private Map elementInfoMap = new HashMap(); + private Collection elements = new ArrayList<>(); - public void setItemVersion(ItemVersion itemVersion){ + public void setItemVersion(ItemVersion itemVersion) { this.itemVersion = itemVersion; } - public void addElementInfo(String key,ElementInfo elementInfo){ - elementInfoMap.put(key,elementInfo); + public void addElementInfo(String key, ElementInfo elementInfo) { + elementInfoMap.put(key, elementInfo); } - public void addElement(Element element){ - elements.add(element); + + public void addElement(Element element) { + elements.add(element); } + @Override public Optional getFirstVersion(SessionContext context, Id itemId) { return Optional.ofNullable(itemVersion); } - @Override - public Optional getElement(SessionContext context, ElementContext elementContext, - String elementId) { - return null; - } + @Override + public Collection listPublicVersions(SessionContext context, Id itemId) { + return null; + } - @Override - public Optional getElementByName(SessionContext context, + @Override + public ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId) { + return null; + } + + @Override + public Optional getElement(SessionContext context, ElementContext elementContext, + String elementId) { + return null; + } + + @Override + public Optional getElementByName(SessionContext context, + ElementContext elementContext, + Id parentElementId, String elementName) { + return null; + } + + @Override + public Collection listElements(SessionContext context, ElementContext elementContext, - Id parentElementId, String elementName) { - return null; - } + Id parentElementId) { + return null; + } - @Override - public Collection listElements(SessionContext context, - ElementContext elementContext, - Id parentElementId) { - return null; - } + @Override + public Collection listElementData(SessionContext context, + ElementContext elementContext, + Id parentElementId) { + return elements; + } - @Override - public Collection listElementData(SessionContext context, - ElementContext elementContext, - Id parentElementId) { - return elements; - } + @Override + public Collection listElementsByName(SessionContext context, + ElementContext elementContext, + Id parentElementId, String elementName) { - @Override - public Collection listElementsByName(SessionContext context, - ElementContext elementContext, - Id parentElementId, String elementName) { - return null; + if(elementName.equals(ElementType.VspModel.name())){ + return elementInfoMap.values(); } - @Override - public Optional getElementInfoByName(SessionContext context, - ElementContext elementContext, - Id parentElementId, String elementName) { - return Optional.ofNullable(elementInfoMap.get(parentElementId+elementName)); - } + return null; + } - @Override - public Optional saveElement(SessionContext context, ElementContext elementContext, - ZusammenElement element, String message) { - return null; - } + @Override + public Optional getElementInfoByName(SessionContext context, + ElementContext elementContext, + Id parentElementId, String elementName) { - @Override - public Collection checkHealth(SessionContext context) { - return null; - } + if(elementName.equals(ElementType.Templates.name())){ + return Optional.ofNullable(elementInfoMap.get("null" + elementName)); + }else if(elementName.equals(ElementType.Artifacts.name())) { + return Optional.ofNullable(elementInfoMap.get("null" + elementName)); + } - @Override - public Id createItem(SessionContext context, Info info) { - return null; - } + return Optional.empty(); + } + + @Override + public Element saveElement(SessionContext context, ElementContext elementContext, + ZusammenElement element, String message) { + return null; + } - @Override - public void updateItem(SessionContext context, Id itemId, Info info) { + @Override + public void resolveElementConflict(SessionContext context, ElementContext elementContext, + ZusammenElement element, Resolution resolution) { - } + } + + @Override + public Collection checkHealth(SessionContext context) { + return null; + } - @Override - public Id createVersion(SessionContext context, Id itemId, Id baseVersionId, + @Override + public Id createItem(SessionContext context, Info info) { + return null; + } + + @Override + public void updateItem(SessionContext context, Id itemId, Info info) { + + } + + @Override + public Id createVersion(SessionContext context, Id itemId, Id baseVersionId, + ItemVersionData itemVersionData) { + return null; + } + + @Override + public void updateVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData) { - return null; - } - @Override - public void updateVersion(SessionContext context, Id itemId, Id versionId, - ItemVersionData itemVersionData) { + } - } + @Override + public ItemVersion getVersion(SessionContext context, Id itemId, Id versionId) { + return null; + } - @Override - public void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag) { + @Override + public ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId) { + return null; + } - } + @Override + public ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId) { + return null; + } - @Override - public void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String changeRef) { + @Override + public void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag) { - } + } - @Override - public Optional getElementInfo(SessionContext context, - ElementContext elementContext, - Id elementId) { - return null; - } + @Override + public void resetVersionHistory(SessionContext context, Id itemId, Id versionId, + String changeRef) { - @Override - public String getVersion(SessionContext sessionContext) { - return null; - } - @Override - public Collection listItems(SessionContext context) { - return null; - } } + + /*@Override + public void revertVersionToRevision(SessionContext context, Id itemId, Id versionId, + Id revisionId) { + + } + + @Override + public ItemVersionRevisions listVersionRevisions(SessionContext context, Id itemId, + Id versionId) { + return null; + }*/ + + @Override + public void publishVersion(SessionContext context, Id itemId, Id versionId, String message) { + + } + + @Override + public void syncVersion(SessionContext sessionContext, Id itemId, Id versionId) { + + } + + @Override + public void forceSyncVersion(SessionContext context, Id itemId, Id versionId) { + + } + + @Override + public Optional getElementInfo(SessionContext context, + ElementContext elementContext, + Id elementId) { + return null; + } + + @Override + public String getVersion(SessionContext sessionContext) { + return null; + } + + @Override + public void revert(SessionContext sessionContext, String itemId, String versionId, + String revisionId) { + + } + + @Override + public List listRevisions(SessionContext sessionContext, String itemId, + String versionId) { + return null; + } + + @Override + public Optional getElementConflict(SessionContext context, + ElementContext elementContext, + Id id) { + return null; + } + + @Override + public Collection listItems(SessionContext context) { + return null; + } + + @Override + public Item getItem(SessionContext context, Id itemId) { + return null; + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImplTest.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImplTest.java index 9f2f733a64..dde8d83dea 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImplTest.java @@ -21,41 +21,9 @@ package org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.HEADER; -import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VFC_COMPUTE_CPU_OVER_SUBSCRIPTION; - -import org.junit.Assert; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; -import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.InformationArtifactData; import org.openecomp.sdc.vendorsoftwareproduct.questionnaire.QuestionnaireDataService; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.ComponentQuestionnaire; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.compute.Compute; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.compute.GuestOS; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.compute.NumOfVMs; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.general.Hypervisor; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.general.Recovery; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.network.NetworkCapacity; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic.IpConfiguration; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic.Network; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic.NicQuestionnaire; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic.Protocols; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.VspQuestionnaire; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general.Availability; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general.General; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general.StorageDataReplication; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; public class TxtInformationArtifactGeneratorImplTest { diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/pom.xml b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/pom.xml index d11362c3a3..dcf2c6a10d 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/pom.xml +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/pom.xml @@ -13,6 +13,21 @@ + + org.openecomp.sdc.core + openecomp-session-lib + ${project.version} + + + org.openecomp.sdc + openecomp-item-permissions-core + ${project.version} + + + org.openecomp.sdc + openecomp-item-permissions-api + ${project.version} + org.openecomp.sdc.core openecomp-facade-core 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 new file mode 100644 index 0000000000..ee58902a49 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManager.java @@ -0,0 +1,20 @@ +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; + +public interface ItemManager { + + Collection list(Predicate predicate); + + Item get(String itemId); + + Item create(Item item); + + void updateVersionStatus(String itemId, VersionStatus addedVersionStatus, + VersionStatus removedVersionStatus); + +} 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 new file mode 100644 index 0000000000..314ffceadb --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManagerFactory.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +public abstract class ItemManagerFactory extends AbstractComponentFactory { + + 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 7fab25456c..c03769462b 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 @@ -20,11 +20,14 @@ package org.openecomp.sdc.versioning; +import org.openecomp.sdc.versioning.dao.types.Revision; import org.openecomp.sdc.versioning.dao.types.Version; +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.List; import java.util.Map; public interface VersioningManager { @@ -54,4 +57,24 @@ public interface VersioningManager { Map listDeletedEntitiesVersionInfo(String entityType, String user, VersionableEntityAction action); + + List list(String itemId); // TODO: 5/24/2017 filter (by status for example) + + Version get(String itemId, Version version); + + Version create(String itemId, Version version, + VersionCreationMethod creationMethod); + + void submit(String itemId, Version version, String submitDescription); + + void publish(String itemId, Version version, String message); + + void sync(String itemId, Version version); + + void forceSync(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/VersioningNotificationConstansts.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningNotificationConstansts.java new file mode 100644 index 0000000000..42161dfef7 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningNotificationConstansts.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.versioning; + +/** + * @author avrahamg + * @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"; + public static final String VERSION_NAME = "versionName"; + public static final String VERSION_ID = "versionId"; +} 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 new file mode 100644 index 0000000000..f1edc1e0c0 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDao.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.versioning.dao; + +import org.openecomp.sdc.versioning.types.Item; + +import java.util.Collection; + +public interface ItemDao { + Collection list(); + + Item get(Item item); + + Item create(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 new file mode 100644 index 0000000000..36edaa9aa9 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDaoFactory.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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); + } +} 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 new file mode 100644 index 0000000000..f557e4d4ec --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDao.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.versioning.dao; + +import org.openecomp.sdc.versioning.dao.types.Revision; +import org.openecomp.sdc.versioning.dao.types.Version; + +import java.util.List; +import java.util.Optional; + +public interface VersionDao { + List list(String itemId); + + void create(String itemId, Version version); + + void update(String itemId, Version version); + + Optional get(String itemId, Version version); + + void delete(String itemId, Version version); + + void publish(String itemId, Version version, String message); + + void sync(String itemId, Version version); + + void forceSync(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 new file mode 100644 index 0000000000..845b248d7e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDaoFactory.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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); + } +} 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 new file mode 100644 index 0000000000..492e75fdbb --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Revision.java @@ -0,0 +1,42 @@ +package org.openecomp.sdc.versioning.dao.types; + +import java.util.Date; + +public class Revision { + private String id; + private String message; + private Date time; + private String user; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public void setMessage(String message) { + this.message = message; + } + + public void setTime(Date time) { + this.time = time; + } + + public String getMessage() { + return message; + } + + public Date getTime() { + return time; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = 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 new file mode 100644 index 0000000000..f0142d3e70 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/SynchronizationState.java @@ -0,0 +1,17 @@ +package org.openecomp.sdc.versioning.dao.types; + +public enum SynchronizationState { + UpToDate("Up to date"), + OutOfSync("Out of sync"), + Merging("Merging"); + + private String displayName; + + SynchronizationState(String displayName) { + this.displayName = 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/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 82b79c6bda..b1f0b71d90 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 @@ -22,23 +22,44 @@ package org.openecomp.sdc.versioning.dao.types; import com.datastax.driver.mapping.annotations.Transient; import com.datastax.driver.mapping.annotations.UDT; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; + +import java.util.Date; +import java.util.Map; @UDT(name = "version", keyspace = "dox") public class Version { - private static final Logger logger = LoggerFactory.getLogger(Version.class); public static final String VERSION_STRING_VIOLATION_MSG = "Version string must be in the format of: {integer}.{integer}"; - private int major; - private int minor; @Transient - private VersionStatus status = VersionStatus.Available; + 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() { } + public Version(String id) { + this.id = id; + } + + @Deprecated public Version(int major, int minor) { this.major = major; this.minor = minor; @@ -62,7 +83,6 @@ public class Version { try { version = new Version(Integer.parseInt(versionLevels[0]), Integer.parseInt(versionLevels[1])); } catch (Exception ex) { - logger.debug(ex.getMessage(), ex); throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); } @@ -85,6 +105,54 @@ public class Version { this.minor = minor; } + 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 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 VersionStatus getStatus() { return status; } @@ -93,6 +161,14 @@ public class Version { this.status = status; } + public VersionState getState() { + return state; + } + + public void setState(VersionState state) { + this.state = state; + } + public Version calculateNextCandidate() { return new Version(major, minor + 1); } @@ -105,6 +181,14 @@ public class Version { return major != 0 && minor == 0; } + public Map getAdditionalInfo() { + return additionalInfo; + } + + public void setAdditionalInfo(Map additionalInfo) { + this.additionalInfo = additionalInfo; + } + @Override public int hashCode() { int result = major; @@ -138,6 +222,21 @@ public class Version { @Override public String toString() { - return major + "." + minor; + 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 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 new file mode 100644 index 0000000000..8d489802b7 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionState.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.versioning.dao.types; + +public class VersionState { + private SynchronizationState synchronizationState; + private boolean dirty; + + public SynchronizationState getSynchronizationState() { + return synchronizationState; + } + + public void setSynchronizationState( + SynchronizationState synchronizationState) { + this.synchronizationState = synchronizationState; + } + + public boolean isDirty() { + return dirty; + } + + public void setDirty(boolean dirty) { + this.dirty = 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 cf980d6b51..e330b9506a 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 @@ -21,7 +21,7 @@ package org.openecomp.sdc.versioning.dao.types; public enum VersionStatus { - Available, - Locked, - Final + Draft, + Locked, /* todo remove!!*/ + Certified } 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 4de5618e75..367a93b630 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 @@ -20,11 +20,11 @@ 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. */ 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 new file mode 100644 index 0000000000..0075403acf --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/RevisionIdNotFoundErrorBuilder.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning.errors; + +import org.openecomp.sdc.common.errors.BaseErrorBuilder; +import org.openecomp.sdc.common.errors.ErrorCategory; + +/** + * The mandatory field revision id not found error builder. + */ +public class RevisionIdNotFoundErrorBuilder extends BaseErrorBuilder { + + private 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/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 77be83f427..f717e5dbdc 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 @@ -53,7 +53,7 @@ public class VersionableSubEntityNotFoundErrorBuilder extends BaseErrorBuilder { getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); getErrorCodeBuilder().withMessage(String .format(SUB_ENTITY_NOT_FOUND_MSG, entityType, entityId, containingEntityType, - containingEntityId, version.toString())); + containingEntityId, version.getId())); } /** 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 c1c6b96bfd..3dd87d5a3f 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 @@ -40,4 +40,10 @@ public class VersioningErrorCodes { 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 new file mode 100644 index 0000000000..329ac52133 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/Item.java @@ -0,0 +1,103 @@ +package org.openecomp.sdc.versioning.types; + +import org.openecomp.sdc.versioning.dao.types.VersionStatus; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +public class Item { + private String id; + private String type; + private String name; + private String description; + private Map properties = new HashMap<>(); + private Map versionStatusCounters = new HashMap<>(); + private Date creationTime; + private Date modificationTime; + + 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 Map getProperties() { + return properties; + } + + public void addProperty(String key, Object value) { + properties.put(key, value); + } + + public void setProperties(Map properties) { + this.properties = properties; + } + + public Map getVersionStatusCounters() { + return versionStatusCounters; + } + + public void setVersionStatusCounters(Map versionStatusCounters) { + this.versionStatusCounters = versionStatusCounters; + } + + 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 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; + } +} 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 new file mode 100644 index 0000000000..b62f7b53e1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/NotificationEventTypes.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.versioning.types; + +/** + * @author avrahamg + * @since July 10, 2017 + */ +public enum NotificationEventTypes { + SUBMIT("submit"), + COMMIT("commit"); + + private String eventName; + + NotificationEventTypes(String eventName) { + this.eventName = eventName; + } + + public String getEventName() { + return eventName; + } +} 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 new file mode 100644 index 0000000000..6404b6b280 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionCreationMethod.java @@ -0,0 +1,8 @@ +package org.openecomp.sdc.versioning.types; + +public enum VersionCreationMethod { + /*parent_level, + same_level, + sub_level*/ + major,minor +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/resources/factoryConfiguration.json index e38ad1a8b4..90d11f1700 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/resources/factoryConfiguration.json +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/resources/factoryConfiguration.json @@ -1,6 +1,10 @@ { + "org.openecomp.sdc.versioning.ItemManagerFactory": "org.openecomp.sdc.versioning.impl.ItemManagerFactoryImpl", "org.openecomp.sdc.versioning.VersioningManagerFactory": "org.openecomp.sdc.versioning.impl.VersioningManagerFactoryImpl", "org.openecomp.sdc.versioning.dao.VersionableEntityDaoFactory": "org.openecomp.sdc.versioning.dao.impl.VersionableEntityDaoFactoryImpl", "org.openecomp.sdc.versioning.dao.VersionInfoDaoFactory": "org.openecomp.sdc.versioning.dao.impl.VersionInfoDaoFactoryImpl", - "org.openecomp.sdc.versioning.dao.VersionInfoDeletedDaoFactory": "org.openecomp.sdc.versioning.dao.impl.VersionInfoDeletedDaoFactoryImpl" + "org.openecomp.sdc.versioning.dao.VersionInfoDeletedDaoFactory": "org.openecomp.sdc.versioning.dao.impl.VersionInfoDeletedDaoFactoryImpl", + "org.openecomp.sdc.versioning.dao.ItemDaoFactory": "org.openecomp.sdc.versioning.dao.impl.ItemDaoFactoryImpl", + "org.openecomp.sdc.versioning.dao.VersionDaoFactory": "org.openecomp.sdc.versioning.dao.impl.VersionDaoFactoryImpl", + "org.openecomp.sdc.versioning.dao.HealthCheckDaoFactory": "org.openecomp.sdc.model.impl.HealthCheckDaoFactoryImpl" } \ No newline at end of file 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 new file mode 100644 index 0000000000..dc9ac7b325 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculator.java @@ -0,0 +1,12 @@ +package org.openecomp.sdc.versioning; + +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); +} 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 new file mode 100644 index 0000000000..85f02cd267 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculatorFactory.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +public abstract class VersionCalculatorFactory extends AbstractComponentFactory { + + 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 new file mode 100644 index 0000000000..0f9c9065d4 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/ItemDaoFactoryImpl.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning.dao.impl; + +import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; +import org.openecomp.sdc.versioning.dao.ItemDao; +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; + } +} 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 new file mode 100644 index 0000000000..f8b0d71eb7 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionDaoFactoryImpl.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning.dao.impl; + +import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; +import org.openecomp.sdc.versioning.dao.VersionDao; +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; + } +} 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 5673da7070..0845beaa2f 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 @@ -24,12 +24,12 @@ import com.datastax.driver.core.ColumnDefinitions; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.mapping.UDTMapper; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.core.util.UniqueValueUtil; import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.versioning.dao.VersionableEntityDao; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.types.UniqueValueMetadata; 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 new file mode 100644 index 0000000000..8fdcf71d59 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/ItemZusammenDaoImpl.java @@ -0,0 +1,104 @@ +package org.openecomp.sdc.versioning.dao.impl.zusammen; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.item.Info; +import org.openecomp.core.zusammen.api.ZusammenAdaptor; +import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.versioning.dao.ItemDao; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; +import org.openecomp.sdc.versioning.types.Item; + +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; + } + + @Override + public void update(Item item) { + zusammenAdaptor + .updateItem(ZusammenUtil.createSessionContext(), new Id(item.getId()), + mapToZusammenItemInfo(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()); + 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_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); + } + } + + 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_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 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 new file mode 100644 index 0000000000..195973bf5c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImpl.java @@ -0,0 +1,165 @@ +package org.openecomp.sdc.versioning.dao.impl.zusammen; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +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 org.openecomp.core.zusammen.api.ZusammenAdaptor; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; +import org.openecomp.sdc.versioning.dao.VersionDao; +import org.openecomp.sdc.versioning.dao.impl.zusammen.convertor.ItemVersionToVersionConvertor; +import org.openecomp.sdc.versioning.dao.types.Revision; +import org.openecomp.sdc.versioning.dao.types.SynchronizationState; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionState; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + +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 revert(String itemId, Version version, String revisionId) { + zusammenAdaptor.revert(createSessionContext(), itemId, version.getId(), revisionId); + } + + @Override + public List listRevisions(String itemId, Version version) { + return zusammenAdaptor.listRevisions(createSessionContext(), itemId, version.getId()); + } + + private void updateVersionStatus(SessionContext context, Id itemId, Id versionId, + VersionState versionState, ItemVersion itemVersion) { + if (versionState.getSynchronizationState() != SynchronizationState.UpToDate || + versionState.isDirty()) { + 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()); + } + } +} 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 new file mode 100644 index 0000000000..f47b5aa612 --- /dev/null +++ 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 @@ -0,0 +1,49 @@ +package org.openecomp.sdc.versioning.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.Item; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.versioning.dao.impl.zusammen.VersionZusammenDaoImpl; +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 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/ItemManagerFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerFactoryImpl.java new file mode 100644 index 0000000000..ba5bd07d42 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerFactoryImpl.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning.impl; + +import org.openecomp.sdc.itempermissions.PermissionsServicesFactory; +import org.openecomp.sdc.notification.factories.SubscriptionServiceFactory; +import org.openecomp.sdc.versioning.ItemManager; +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(), + PermissionsServicesFactory.getInstance().createInterface(), + SubscriptionServiceFactory.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 new file mode 100644 index 0000000000..79284542fb --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerImpl.java @@ -0,0 +1,68 @@ +package org.openecomp.sdc.versioning.impl; + +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.itempermissions.PermissionsServices; +import org.openecomp.sdc.notification.services.SubscriptionService; +import org.openecomp.sdc.versioning.ItemManager; +import org.openecomp.sdc.versioning.dao.ItemDao; +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 java.util.stream.Collectors; + +public class ItemManagerImpl implements ItemManager { + public static final String CREATE_ITEM = "Create_Item"; + + private ItemDao itemDao; + private PermissionsServices permissionsServices; + private SubscriptionService subscriptionService; + + public ItemManagerImpl(ItemDao itemDao, PermissionsServices permissionsServices, + SubscriptionService subscriptionService) { + this.itemDao = itemDao; + this.permissionsServices = permissionsServices; + this.subscriptionService = subscriptionService; + } + + @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) { + Item createdItem = itemDao.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 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); + } +} 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 new file mode 100644 index 0000000000..2300f62180 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorFactoryImpl.java @@ -0,0 +1,14 @@ +package org.openecomp.sdc.versioning.impl; + +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; + } +} 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 new file mode 100644 index 0000000000..91c59e0efd --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorImpl.java @@ -0,0 +1,53 @@ +package org.openecomp.sdc.versioning.impl; + +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) { + + 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, '.'); + } + + @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. + } + } + 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 new file mode 100644 index 0000000000..155aa9c5e6 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorFactoryImpl.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + * ============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; + } +} 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 new file mode 100644 index 0000000000..b7008de867 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorImpl.java @@ -0,0 +1,155 @@ +package org.openecomp.sdc.versioning.impl; + +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 VersionCalculatorImpl 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}"; + private static final String PARENT_LEVEL_VERSION_CANNOT_BE_CREATED_FROM_TOP_LEVEL = + "Creation of parent level version on top level version is invalid."; + private static final String SUB_LEVEL_VERSION_CANNOT_BE_CREATED_FROM_LOWEST_LEVEL = + "Creation of parent level version on top level version is invalid."; + + private static final String VERSION_CALCULATION_ERROR_MSG = + "Version calculation error."; + + private static final String INVALID_CREATION_METHOD_MSG = "Invalid creation method-"; + + + @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, '.'); + } + + + // version calculator when there are no version restrictions + /* @Override + public String calculate(String baseVersion, VersionCreationMethod creationMethod) { + + return calculate(baseVersion,creationMethod,2); + } + + private String calculate(String baseVersion, VersionCreationMethod creationMethod,int + maxVersionLevels) { + if (baseVersion == null) { + return INITIAL_VERSION; + } + + String[] versionLevels = baseVersion.split("\\."); + if (versionLevels.length > maxVersionLevels) { + throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); + } + + int index; + int versionLevel = calcVersionLevel(versionLevels); + if (versionLevel == -1) { + throw new IllegalArgumentException( + VERSION_STRING_VIOLATION_MSG + " given version:" + baseVersion); + } + int requiredVersionLevelIncrease; + switch (creationMethod) { + case parent_level: + if (versionLevel == 0) { + throw new IllegalArgumentException( + PARENT_LEVEL_VERSION_CANNOT_BE_CREATED_FROM_TOP_LEVEL + " version:" + baseVersion); + + } + requiredVersionLevelIncrease = versionLevel - 1; + versionLevels[versionLevel] = "0"; + index = Integer.getInteger(versionLevels[requiredVersionLevelIncrease]); + index++; + versionLevels[requiredVersionLevelIncrease] = Integer.toString(index); + break; + case same_level: + requiredVersionLevelIncrease = versionLevel; + index = Integer.valueOf(versionLevels[requiredVersionLevelIncrease]); + index++; + versionLevels[requiredVersionLevelIncrease] = Integer.toString(index); + break; + case sub_level: + if (versionLevel == versionLevels.length - 1) { + throw new IllegalArgumentException( + SUB_LEVEL_VERSION_CANNOT_BE_CREATED_FROM_LOWEST_LEVEL + " version:" + baseVersion); + } + requiredVersionLevelIncrease = versionLevel + 1; + if(requiredVersionLevelIncrease>maxVersionLevels){ + throw new IllegalArgumentException(INVALID_CREATION_METHOD_MSG+" max " + + "levels:"+maxVersionLevels + "requested level:"+requiredVersionLevelIncrease); + } + String newVersion = baseVersion + ".1"; + versionLevels = newVersion.split("\\."); + + break; + default: + throw new IllegalArgumentException(VERSION_CALCULATION_ERROR_MSG + " base " + + "version:" + baseVersion + " creation method:" + creationMethod); + + } + + 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) { + //not a valid creation method. + } + } + } + version.getAdditionalInfo().put("OptionalCreationMethods", optionalCreationMethods); + + } + + + private int calcVersionLevel(String[] versionLevels) { + for (int i = versionLevels.length - 1; i >= 0; i--) { + if (!versionLevels[i].equals("0")) { + return i; + } + } + return -1; + } +} 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 8ab5c608bf..b4dbcf3a08 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 @@ -20,16 +20,21 @@ package org.openecomp.sdc.versioning.impl; +import org.openecomp.sdc.versioning.ItemManagerFactory; +import org.openecomp.sdc.versioning.VersionCalculatorFactory; import org.openecomp.sdc.versioning.VersioningManager; import org.openecomp.sdc.versioning.VersioningManagerFactory; +import org.openecomp.sdc.versioning.dao.VersionDaoFactory; import org.openecomp.sdc.versioning.dao.VersionInfoDaoFactory; import org.openecomp.sdc.versioning.dao.VersionInfoDeletedDaoFactory; public class VersioningManagerFactoryImpl extends VersioningManagerFactory { private static final VersioningManager INSTANCE = new VersioningManagerImpl( VersionInfoDaoFactory.getInstance().createInterface(), - VersionInfoDeletedDaoFactory.getInstance().createInterface() - ); + VersionInfoDeletedDaoFactory.getInstance().createInterface(), + VersionDaoFactory.getInstance().createInterface(), + VersionCalculatorFactory.getInstance().createInterface(), + ItemManagerFactory.getInstance().createInterface()); @Override public VersioningManager 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 4a49d5391f..7f983477cf 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 @@ -21,25 +21,31 @@ package org.openecomp.sdc.versioning.impl; import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.versioning.ItemManager; +import org.openecomp.sdc.versioning.VersionCalculator; import org.openecomp.sdc.versioning.VersioningManager; +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.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.VersionHistoryEntity; 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.dao.types.VersionType; -import org.openecomp.sdc.versioning.dao.types.VersionableEntityId; import org.openecomp.sdc.versioning.errors.CheckinOnEntityLockedByOtherErrorBuilder; import org.openecomp.sdc.versioning.errors.CheckinOnUnlockedEntityErrorBuilder; import org.openecomp.sdc.versioning.errors.CheckoutOnLockedEntityErrorBuilder; @@ -52,6 +58,7 @@ 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; @@ -66,18 +73,27 @@ import java.util.Set; import java.util.stream.Collectors; public class VersioningManagerImpl implements VersioningManager { - + private static final Logger LOGGER = LoggerFactory.getLogger(VersioningManagerImpl.class); private static final Version INITIAL_ACTIVE_VERSION = new Version(0, 0); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private static Map> versionableEntities = new HashMap<>(); - private VersionInfoDao versionInfoDao; - private VersionInfoDeletedDao versionInfoDeletedDao; + private final VersionInfoDao versionInfoDao; + private final VersionInfoDeletedDao versionInfoDeletedDao; + private VersionDao versionDao; + private VersionCalculator versionCalculator; + private ItemManager itemManager; public VersioningManagerImpl(VersionInfoDao versionInfoDao, - VersionInfoDeletedDao versionInfoDeletedDao) { + VersionInfoDeletedDao versionInfoDeletedDao, + VersionDao versionDao, + VersionCalculator versionCalculator, + ItemManager itemManager) { this.versionInfoDao = versionInfoDao; this.versionInfoDeletedDao = versionInfoDeletedDao; + this.versionDao = versionDao; + this.versionCalculator = versionCalculator; + this.itemManager = itemManager; } private static VersionInfo getVersionInfo(VersionInfoEntity versionInfoEntity, String user, @@ -146,8 +162,12 @@ public class VersioningManagerImpl implements VersioningManager { 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)); + if (latestFinalVersion != null) { + latestFinalVersion.setStatus(status); + } + if (viewableVersions != null) { + viewableVersions.forEach(version -> version.setStatus(status)); + } versionInfo.setActiveVersion(activeVersion); versionInfo.setLatestFinalVersion(latestFinalVersion); versionInfo.setViewableVersions(toSortedList(viewableVersions)); @@ -166,11 +186,9 @@ public class VersioningManagerImpl implements VersioningManager { private static List toSortedList( Set versions) { // changing the Set to List in DB will require migration... - return versions.stream().sorted((o1, o2) -> { - return o1.getMajor() > o2.getMajor() ? 1 - : o1.getMajor() == o2.getMajor() ? (o1.getMinor() > o2.getMinor() ? 1 - : o1.getMinor() == o2.getMinor() ? 0 : -1) : -1; - }).collect(Collectors.toList()); + 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) { @@ -263,8 +281,8 @@ public class VersioningManagerImpl implements VersioningManager { LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Can't checkout versionable entity"); throw new CoreException(new CheckoutOnLockedEntityErrorBuilder(entityType, entityId, versionInfoEntity.getCandidate().getUser()).build()); - case Final: - case Available: + case Certified: + case Draft: checkoutVersion = doCheckout(versionInfoEntity, user); break; default: @@ -300,8 +318,8 @@ public class VersioningManagerImpl implements VersioningManager { } activeVersion = undoCheckout(versionInfoEntity); break; - case Final: - case Available: + case Certified: + case Draft: MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.UNDO_CHECKOUT_ENTITY, ErrorLevel.ERROR.name(), LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), @@ -320,8 +338,9 @@ public class VersioningManagerImpl implements VersioningManager { deleteVersionFromEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), versionInfoEntity.getCandidate().getVersion(), versionInfoEntity.getActiveVersion()); - versionInfoEntity.setStatus(versionInfoEntity.getActiveVersion().isFinal() ? VersionStatus.Final - : VersionStatus.Available); + versionInfoEntity + .setStatus(versionInfoEntity.getActiveVersion().isFinal() ? VersionStatus.Certified + : VersionStatus.Draft); versionInfoEntity.setCandidate(null); versionInfoDao.update(versionInfoEntity); return versionInfoEntity.getActiveVersion(); @@ -341,8 +360,8 @@ public class VersioningManagerImpl implements VersioningManager { Version checkedInVersion = null; switch (versionInfoEntity.getStatus()) { - case Available: - case Final: + case Draft: + case Certified: MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.CHECKIN_ENTITY, ErrorLevel.ERROR.name(), LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Can't checkin versionable entity"); @@ -379,7 +398,7 @@ public class VersioningManagerImpl implements VersioningManager { Version submitVersion = null; switch (versionInfoEntity.getStatus()) { - case Final: + case Certified: MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.SUBMIT_ENTITY, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Can't submit versionable entity"); @@ -391,7 +410,7 @@ public class VersioningManagerImpl implements VersioningManager { LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Can't submit versionable entity"); throw new CoreException(new SubmitLockedEntityNotAllowedErrorBuilder(entityType, entityId, versionInfoEntity.getCandidate().getUser()).build()); - case Available: + case Draft: submitVersion = doSubmit(versionInfoEntity, user, submitDescription); break; default: @@ -444,6 +463,143 @@ public class VersioningManagerImpl implements VersioningManager { 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); + itemManager.updateVersionStatus(itemId, VersionStatus.Draft, null); + + publish(itemId, version, String.format("Initial 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); + + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY, + LoggerTragetServiceName.CREATE_VERSION, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), errorDescription); + + 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); + + itemManager.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()); + + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.SUBMIT_ENTITY, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), errorDescription); + + 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, @@ -491,7 +647,7 @@ public class VersioningManagerImpl implements VersioningManager { versionInfoEntity.setCandidate(null); versionInfoEntity.setActiveVersion(userCandidateVersion.getVersion()); versionInfoEntity.getViewableVersions().add(versionInfoEntity.getActiveVersion()); - versionInfoEntity.setStatus(VersionStatus.Available); + versionInfoEntity.setStatus(VersionStatus.Draft); closeVersionOnEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), versionInfoEntity.getActiveVersion()); @@ -519,22 +675,12 @@ public class VersioningManagerImpl implements VersioningManager { versionInfoEntity.setViewableVersions(viewableVersions); versionInfoEntity.setActiveVersion(finalVersion); versionInfoEntity.setLatestFinalVersion(finalVersion); - versionInfoEntity.setStatus(VersionStatus.Final); + versionInfoEntity.setStatus(VersionStatus.Certified); versionInfoDao.update(versionInfoEntity); return finalVersion; } - private void createVersionHistory(VersionableEntityId entityId, Version version, String user, - String description, VersionType type) { - VersionHistoryEntity versionHistory = new VersionHistoryEntity(entityId); - versionHistory.setVersion(version); - versionHistory.setUser(user); - versionHistory.setDescription(description); - versionHistory.setType(type); - //versionHistoryDao.create(versionHistory); - } - private void initVersionOnEntity(String entityType, String entityId, Version baseVersion, Version newVersion) { Set entityMetadatas = versionableEntities.get(entityType); diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..d2d16eff37 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/resources/factoryConfiguration.json @@ -0,0 +1,3 @@ +{ + "org.openecomp.sdc.versioning.VersionCalculatorFactory": "org.openecomp.sdc.versioning.impl.MajorVersionCalculatorFactoryImpl" +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImplTest.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImplTest.java new file mode 100644 index 0000000000..1f1efdf6cb --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImplTest.java @@ -0,0 +1,265 @@ +package org.openecomp.sdc.versioning.dao.impl.zusammen; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.UserInfo; +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 org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.core.zusammen.api.ZusammenAdaptor; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.isNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; + +public class VersionZusammenDaoImplTest { + + private static final String USER = "user1"; + @Mock + private ZusammenAdaptor zusammenAdaptorMock; + @InjectMocks + private VersionZusammenDaoImpl versionDao; + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + SessionContextProviderFactory.getInstance().createInterface().create(USER); + } + + @Test + public void testList() throws Exception { + String itemId = "itemId"; + Id versionId1 = new Id("v1_id"); + Id versionId2 = new Id("v2_id"); + Id versionId3 = new Id("v3_id"); + + List zusammenVersions = Stream.of( + createZusammenVersion(versionId1, null, "version desc", "1.0", VersionStatus.Certified), + createZusammenVersion(versionId2, versionId1, "version desc", "2.0", VersionStatus.Certified + ), + createZusammenVersion(versionId3, versionId2, "version desc", "3.0", VersionStatus.Draft)) + .collect(Collectors.toList()); + doReturn(zusammenVersions).when(zusammenAdaptorMock) + .listPublicVersions(eq(createZusammenContext()), eq(new Id(itemId))); + + List versions = versionDao.list(itemId); + Assert.assertEquals(versions.size(), 3); + + int zusammenVersionIndex; + for (Version version : versions) { + zusammenVersionIndex = versionId1.getValue().equals(version.getId()) + ? 0 + : versionId2.getValue().equals(version.getId()) + ? 1 + : 2; + assetVersionEquals(version, zusammenVersions.get(zusammenVersionIndex)); + } + } + + @Test + public void testCreate() throws Exception { + testCreate(null); + } + + @Test + public void testCreateBasedOn() throws Exception { + testCreate("baseId"); + } + + private void testCreate(String baseId) { + String itemId = "itemId"; + Version version = new Version(1, 0); + version.setBaseId(baseId); + version.setName("version name"); + version.setDescription("version description"); + version.setStatus(VersionStatus.Draft); + + doReturn(new Id("versionId")).when(zusammenAdaptorMock) + .createVersion(eq(createZusammenContext()), eq(new Id(itemId)), + baseId == null ? isNull(Id.class) : eq(new Id(baseId)), any(ItemVersionData.class)); + + ArgumentCaptor capturedZusammenVersion = + ArgumentCaptor.forClass(ItemVersionData.class); + + versionDao.create(itemId, version); + + verify(zusammenAdaptorMock) + .createVersion(eq(createZusammenContext()), eq(new Id(itemId)), + baseId == null ? isNull(Id.class) : eq(new Id(baseId)), + capturedZusammenVersion.capture()); + + Info capturedInfo = capturedZusammenVersion.getValue().getInfo(); + Assert.assertEquals(capturedInfo.getName(), version.getName()); + Assert.assertEquals(capturedInfo.getDescription(), version.getDescription()); + Assert.assertEquals(VersionStatus + .valueOf(capturedInfo.getProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS)), + version.getStatus()); + Assert.assertEquals(capturedInfo.getProperty(VersionZusammenDaoImpl.ZusammenProperty.LABEL), + version.toString()); + } + + @Test + public void testUpdate() throws Exception { + String itemId = "itemId"; + Version version = new Version(1, 0); + version.setId("versionId"); + version.setBaseId("baseId"); + version.setName("version name"); + version.setDescription("version description"); + version.setStatus(VersionStatus.Certified); + + ArgumentCaptor capturedZusammenVersion = + ArgumentCaptor.forClass(ItemVersionData.class); + + versionDao.update(itemId, version); + + verify(zusammenAdaptorMock) + .updateVersion(eq(createZusammenContext()), eq(new Id(itemId)), eq(new Id(version.getId())), + capturedZusammenVersion.capture()); + + Info capturedInfo = capturedZusammenVersion.getValue().getInfo(); + Assert.assertEquals(capturedInfo.getName(), version.getName()); + Assert.assertEquals(capturedInfo.getDescription(), version.getDescription()); + Assert.assertEquals(VersionStatus + .valueOf(capturedInfo.getProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS)), + version.getStatus()); + Assert.assertEquals(capturedInfo.getProperty(VersionZusammenDaoImpl.ZusammenProperty.LABEL), + version.toString()); + } + + @Test + public void testGetNonExisting() throws Exception { + Optional version = versionDao.get("itemId", new Version("versionId")); + + Assert.assertEquals(version, Optional.empty()); + } + + @Test + public void testGet() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + + SessionContext zusammenContext = createZusammenContext(); + Id itemIdObj = new Id(itemId); + Id versionIdObj = new Id(versionId); + + ItemVersion zusammenPrivateVersion = + createZusammenVersion(versionIdObj, new Id("baseId"), "version desc updated", "2.0", + VersionStatus.Draft); + doReturn(zusammenPrivateVersion).when(zusammenAdaptorMock) + .getVersion(eq(zusammenContext), eq(itemIdObj), eq(versionIdObj)); + + doReturn(new ItemVersionStatus(SynchronizationStatus.UP_TO_DATE, true)) + .when(zusammenAdaptorMock) + .getVersionStatus(eq(zusammenContext), eq(itemIdObj), eq(versionIdObj)); + + ItemVersion zusammenPublicVersion = + createZusammenVersion(versionIdObj, new Id("baseId"), "version desc", "2.0", + VersionStatus.Certified); + doReturn(zusammenPublicVersion).when(zusammenAdaptorMock) + .getPublicVersion(eq(zusammenContext), eq(itemIdObj), eq(versionIdObj)); + + Optional version = versionDao.get(itemId, new Version(versionId)); + + Assert.assertTrue(version.isPresent()); + zusammenPrivateVersion.getData().getInfo() + .addProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS, + VersionStatus.Certified.name()); + assetVersionEquals(version.get(), zusammenPrivateVersion); + } + + // TODO: 12/20/2017 complete tests + /* @Test + public void testDelete() throws Exception { + + } + + @Test + public void testPublish() throws Exception { + + } + + @Test + public void testSync() throws Exception { + + } + + @Test + public void testForceSync() throws Exception { + + } + + @Test + public void testRevert() throws Exception { + + } + + @Test + public void testListRevisions() throws Exception { + + }*/ + + private void assetVersionEquals(Version version, ItemVersion zusammenVersion) { + Assert.assertEquals(version.getId(), zusammenVersion.getId().getValue()); + Assert.assertEquals(version.getBaseId(), + zusammenVersion.getBaseId() == null ? null : zusammenVersion.getBaseId().getValue()); + Info info = zusammenVersion.getData().getInfo(); + Assert.assertEquals(version.getName(), info.getName()); + Assert.assertEquals(version.getDescription(), info.getDescription()); + Assert.assertEquals(version.getStatus(), + VersionStatus.valueOf(info.getProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS))); + String label = info.getProperty(VersionZusammenDaoImpl.ZusammenProperty.LABEL).toString(); + Assert + .assertEquals(version.getMajor(), Integer.parseInt(label.substring(0, label.indexOf('.')))); + Assert.assertEquals(version.getMinor(), + Integer.parseInt(label.substring(label.indexOf('.') + 1, label.length()))); + Assert.assertEquals(version.getCreationTime(), zusammenVersion.getCreationTime()); + Assert.assertEquals(version.getModificationTime(), zusammenVersion.getModificationTime()); + } + + private ItemVersion createZusammenVersion(Id id, Id baseId, String description, String label, + VersionStatus status) { + ItemVersion version = new ItemVersion(); + version.setId(id); + version.setBaseId(baseId); + Info info = new Info(); + info.setName(id + "_name"); + info.setDescription(description); + info.addProperty(VersionZusammenDaoImpl.ZusammenProperty.LABEL, label); + info.addProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS, status.name()); + ItemVersionData data = new ItemVersionData(); + data.setInfo(info); + version.setData(data); + version.setCreationTime(new Date()); + version.setModificationTime(new Date()); + return version; + } + + private SessionContext createZusammenContext() { + SessionContext sessionContext = new SessionContext(); + sessionContext.setUser(new UserInfo(USER)); + sessionContext.setTenant("dox"); + return sessionContext; + } + +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/ItemManagerImplTest.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/ItemManagerImplTest.java new file mode 100644 index 0000000000..755bfb4442 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/ItemManagerImplTest.java @@ -0,0 +1,124 @@ +package org.openecomp.sdc.versioning.impl; + +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.itempermissions.PermissionsServices; +import org.openecomp.sdc.notification.services.SubscriptionService; +import org.openecomp.sdc.versioning.dao.ItemDao; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; +import org.openecomp.sdc.versioning.types.Item; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Collection; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +public class ItemManagerImplTest { + + @Mock + private ItemDao itemDao; + @Mock + private PermissionsServices permissionsServices; + @Mock + private SubscriptionService subscriptionService; + @InjectMocks + private ItemManagerImpl itemManager; + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testList() throws Exception { + doReturn(Stream.of( + createItem("item1", "A"), + createItem("item2", "B"), + createItem("item3", "B"), + createItem("item4", "A")) + .collect(Collectors.toList())).when(itemDao).list(); + + Collection items = itemManager.list(item -> "B".equals(item.getType())); + Assert.assertEquals(items.size(), 2); + Assert.assertTrue(items.stream().anyMatch(item -> "item2".equals(item.getName()))); + Assert.assertTrue(items.stream().anyMatch(item -> "item3".equals(item.getName()))); + } + + @Test + public void testGetNotExisting() throws Exception { + Item item = itemManager.get("item1"); + Assert.assertNull(item); + } + + @Test + public void testGet() throws Exception { + Item toBeReturned = new Item(); + toBeReturned.setId("itemId"); + doReturn(toBeReturned).when(itemDao).get(any(Item.class)); + + Item item = itemManager.get("itemId"); + Assert.assertEquals(item.getId(), "itemId"); + } + + @Test + public void testCreate() throws Exception { + SessionContextProviderFactory.getInstance().createInterface().create("user1"); + + Item toBeReturned = new Item(); + toBeReturned.setId("itemId"); + doReturn(toBeReturned).when(itemDao).create(any(Item.class)); + + Item item = itemManager.create(createItem("item1", "A")); + Assert.assertEquals(item.getId(), "itemId"); + } + + @Test + public void testUpdateNotExistingVersionStatus() throws Exception { + itemManager.updateVersionStatus("itemId", VersionStatus.Certified, VersionStatus.Draft); + verify(itemDao, never()).update(any(Item.class)); + } + + @Test + public void testUpdateVersionStatusWhenNone() throws Exception { + Item item = new Item(); + item.setId("itemId"); + doReturn(item).when(itemDao).get(any(Item.class)); + + itemManager.updateVersionStatus("itemId", VersionStatus.Certified, VersionStatus.Draft); + verify(itemDao).update(item); + Assert.assertEquals(item.getVersionStatusCounters().get(VersionStatus.Certified).intValue(), 1); + Assert.assertNull(item.getVersionStatusCounters().get(VersionStatus.Draft)); + } + + @Test + public void testUpdateVersionStatus() throws Exception { + Item item = new Item(); + item.setId("itemId"); + item.getVersionStatusCounters().put(VersionStatus.Certified, 2); + item.getVersionStatusCounters().put(VersionStatus.Draft, 5); + doReturn(item).when(itemDao).get(any(Item.class)); + + itemManager.updateVersionStatus("itemId", VersionStatus.Certified, VersionStatus.Draft); + verify(itemDao).update(item); + Assert.assertEquals(item.getVersionStatusCounters().get(VersionStatus.Certified).intValue(), 3); + Assert.assertEquals(item.getVersionStatusCounters().get(VersionStatus.Draft).intValue(), 4); + } + + private Item createItem(String name, String type) { + Item item = new Item(); + item.setId(name); + item.setName(name); + item.setType(type); + return item; + } + +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/VersioningManagerImplTest.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/VersioningManagerImplTest.java index d35de4f3d1..2d1109abe6 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/VersioningManagerImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/VersioningManagerImplTest.java @@ -21,39 +21,326 @@ package org.openecomp.sdc.versioning.impl; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.verify; - import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.versioning.dao.VersionInfoDao; -import org.openecomp.sdc.versioning.dao.VersionInfoDeletedDao; -import org.openecomp.sdc.versioning.dao.types.UserCandidateVersion; +import org.openecomp.sdc.versioning.ItemManager; +import org.openecomp.sdc.versioning.VersionCalculator; +import org.openecomp.sdc.versioning.dao.VersionDao; +import org.openecomp.sdc.versioning.dao.types.Revision; +import org.openecomp.sdc.versioning.dao.types.SynchronizationState; 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.VersionState; import org.openecomp.sdc.versioning.dao.types.VersionStatus; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; +import org.openecomp.sdc.versioning.types.VersionCreationMethod; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.openecomp.sdc.versioning.dao.types.SynchronizationState.OutOfSync; +import static org.openecomp.sdc.versioning.dao.types.SynchronizationState.UpToDate; +import static org.openecomp.sdc.versioning.dao.types.VersionStatus.Certified; +import static org.openecomp.sdc.versioning.dao.types.VersionStatus.Draft; public class VersioningManagerImplTest { + @Mock + private VersionDao versionDaoMock; + @Mock + private VersionCalculator versionCalculatorMock; + @Mock + private ItemManager itemManagerMock; + @InjectMocks + private VersioningManagerImpl versioningManager; + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testList() throws Exception { + String itemId = "itemId"; + + List returnedVersions = Stream.of(createVersion("1", null, null, false), + createVersion("2", null, null, false), + createVersion("3", null, null, false)).collect(Collectors.toList()); + doReturn(returnedVersions).when(versionDaoMock).list(itemId); + + List versions = versioningManager.list(itemId); + Assert.assertEquals(versions, returnedVersions); + } + + @Test(expectedExceptions = Exception.class) + public void testGetNonExisting() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + + doReturn(Optional.empty()).when(versionDaoMock).get(itemId, version); + doThrow(new Exception()).when(versionDaoMock).sync(itemId, version); + + versioningManager.get(itemId, version); + } + + @Test + public void testGetNonExistingForUser() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version requestedVersion = new Version(versionId); + + Version returnedVersion = createVersion(versionId, Draft, UpToDate, false); + doReturn(Optional.empty()).doReturn(Optional.of(returnedVersion)) + .when(versionDaoMock).get(itemId, requestedVersion); + + Version version = versioningManager.get(itemId, requestedVersion); + Assert.assertEquals(version, returnedVersion); + + verify(versionDaoMock, times(2)).get(itemId, requestedVersion); + verify(versionDaoMock).sync(itemId, requestedVersion); + } + + @Test + public void testGetOutOfSyncCertified() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version requestedVersion = new Version(versionId); + + Version returnedVersion = createVersion(versionId, Certified, UpToDate, false); + doReturn(Optional.of(createVersion(versionId, Certified, OutOfSync, false))) + .doReturn(Optional.of(returnedVersion)) + .when(versionDaoMock).get(itemId, requestedVersion); + + Version version = versioningManager.get(itemId, requestedVersion); + Assert.assertEquals(version, returnedVersion); + + verify(versionDaoMock, times(2)).get(itemId, requestedVersion); + verify(versionDaoMock).forceSync(itemId, requestedVersion); + } + + @Test + public void testGet() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version requestedVersion = new Version(versionId); + + Version returnedVersion = createVersion(versionId, Draft, OutOfSync, true); + doReturn(Optional.of(returnedVersion)).when(versionDaoMock).get(itemId, requestedVersion); + + Version version = versioningManager.get(itemId, requestedVersion); + Assert.assertEquals(version, returnedVersion); + + verify(versionDaoMock).get(itemId, requestedVersion); + verify(versionDaoMock, never()).sync(any(), any()); + verify(versionDaoMock, never()).forceSync(any(), any()); + } + + @Test + public void testCreate() throws Exception { + String itemId = "itemId"; + Version requestedVersion = new Version(); + + String versionName = "versionName"; + doReturn(versionName).when(versionCalculatorMock).calculate(null, VersionCreationMethod.major); + + doReturn(Stream.of(createVersion("1", null, null, false), + createVersion("2", null, null, false), + createVersion("3", null, null, false)).collect(Collectors.toList())) + .when(versionDaoMock).list(itemId); + + Version version = + versioningManager.create(itemId, requestedVersion, VersionCreationMethod.major); + Assert.assertNotNull(version); + Assert.assertEquals(version.getName(), versionName); + + verify(versionDaoMock).create(itemId, requestedVersion); + verify(itemManagerMock).updateVersionStatus(itemId, Draft, null); + verify(versionDaoMock).publish(eq(itemId), eq(requestedVersion), anyString()); + } + + @Test + public void testCreateBasedOn() throws Exception { + String itemId = "itemId"; + Version requestedVersion = new Version(); + requestedVersion.setBaseId("baseVersionId"); + + Version baseVersion = createVersion(requestedVersion.getBaseId(), Certified, UpToDate, false); + // TODO: 12/13/2017 fix to eq(new Version("baseVersionId")) when version.equals will be fixed + doReturn(Optional.of(baseVersion)).when(versionDaoMock).get(eq(itemId), any(Version.class)); + + String versionName = "4.0"; + doReturn(versionName) + .when(versionCalculatorMock).calculate(baseVersion.getName(), VersionCreationMethod.major); + + doReturn(Stream.of(createVersion("1", null, null, false), + createVersion("2", null, null, false), + createVersion("3", null, null, false)).collect(Collectors.toList())) + .when(versionDaoMock).list(itemId); + + Version version = + versioningManager.create(itemId, requestedVersion, VersionCreationMethod.major); + Assert.assertNotNull(version); + Assert.assertEquals(version.getName(), versionName); + + verify(versionDaoMock).create(itemId, requestedVersion); + verify(itemManagerMock).updateVersionStatus(itemId, Draft, null); + verify(versionDaoMock).publish(eq(itemId), eq(requestedVersion), anyString()); + } + + @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = + "Item itemId: create version failed, a version with the name 2.0 already exist") + public void testCreateWithExistingName() throws Exception { + String itemId = "itemId"; + Version version = new Version(); + version.setBaseId("baseVersionId"); + + Version baseVersion = createVersion(version.getBaseId(), Certified, UpToDate, false); + // TODO: 12/13/2017 fix to eq(new Version("baseVersionId")) when version.equals will be fixed + doReturn(Optional.of(baseVersion)).when(versionDaoMock).get(eq(itemId), any(Version.class)); + + String versionName = "2.0"; + doReturn(versionName) + .when(versionCalculatorMock).calculate(baseVersion.getName(), VersionCreationMethod.major); + + doReturn(Stream.of(createVersion("1", null, null, false), + createVersion("2", null, null, false), + createVersion("3", null, null, false)).collect(Collectors.toList())) + .when(versionDaoMock).list(itemId); + + versioningManager.create(itemId, version, VersionCreationMethod.major); + } + + @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = + "Item itemId: submit version failed, version versionId is already Certified") + public void testSubmitCertified() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + + Version returnedVersion = createVersion(versionId, Certified, UpToDate, false); + doReturn(Optional.of(returnedVersion)).when(versionDaoMock).get(itemId, version); + + versioningManager.submit(itemId, version, "Submit message"); + } + + @Test + public void testSubmit() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + + ArgumentCaptor versionArgumentCaptor = ArgumentCaptor.forClass(Version.class); + + Version returnedVersion = createVersion(versionId, Draft, UpToDate, false); + doReturn(Optional.of(returnedVersion)).when(versionDaoMock).get(itemId, version); + + String submitDescription = "Submit message"; + versioningManager.submit(itemId, version, submitDescription); + + verify(versionDaoMock).update(eq(itemId), versionArgumentCaptor.capture()); + Assert.assertEquals(Certified, versionArgumentCaptor.getValue().getStatus()); + verify(versionDaoMock).publish(itemId, version, submitDescription); + verify(itemManagerMock).updateVersionStatus(itemId, Certified, Draft); + } + + @Test + public void testPublish() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + String publishDescription = "Publish message"; + + versioningManager.publish(itemId, version, publishDescription); + + verify(versionDaoMock).publish(itemId, version, publishDescription); + } + + @Test + public void testSync() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + + versioningManager.sync(itemId, version); + + verify(versionDaoMock).sync(itemId, version); + } + + @Test + public void testForceSync() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + + versioningManager.forceSync(itemId, version); + + verify(versionDaoMock).forceSync(itemId, version); + } + + @Test + public void testRevert() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + String revisionId = "revisionId"; + + versioningManager.revert(itemId, version, revisionId); + + verify(versionDaoMock).revert(itemId, version, revisionId); + } + + @Test + public void testListRevisions() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + + List returnedRevisions = + Stream.of(new Revision(), new Revision()).collect(Collectors.toList()); + doReturn(returnedRevisions) + .when(versionDaoMock).listRevisions(itemId, version); + + List revisions = versioningManager.listRevisions(itemId, version); + Assert.assertEquals(revisions, returnedRevisions); + } + + private Version createVersion(String id, VersionStatus status, + SynchronizationState syncState, boolean dirty) { + Version version = new Version(id); + version.setName(id + ".0"); + version.setDescription(id + " desc"); + version.setStatus(status); + + VersionState state = new VersionState(); + state.setSynchronizationState(syncState); + state.setDirty(dirty); + version.setState(state); + return version; + } + +/* private static final String USR1 = "usr1"; private static final String USR2 = "usr2"; private static final String TYPE1 = "Type1"; -/* private static final String TYPE2 = "Type2";*/ +*/ +/* private static final String TYPE2 = "Type2";*//* + private static final String ID1 = "Id1"; +*/ /* private static final String ID2 = "Id2"; private static final String ID3 = "Id3"; private static final String TYPE1_TABLE_NAME = "vendor_license_model"; @@ -61,17 +348,20 @@ public class VersioningManagerImplTest { private static final String TYPE1_VERSION_NAME = "version"; private static final String TYPE2_TABLE_NAME = "feature_group"; private static final String TYPE2_ID_NAME = "vlm_id"; - private static final String TYPE2_VERSION_NAME = "version";*/ + private static final String TYPE2_VERSION_NAME = "version";*//* + private static final Version VERSION0 = new Version(0, 0); private static final Version VERSION01 = new Version(0, 1); private static final Version VERSION02 = new Version(0, 2); private static final Version VERSION10 = new Version(1, 0); private static final Version VERSION11 = new Version(1, 1); - /* private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + */ +/* private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); private static UDTMapper versionMapper = - noSqlDb.getMappingManager().udtMapper(Version.class);*/ + noSqlDb.getMappingManager().udtMapper(Version.class);*//* + @Mock private VersionInfoDao versionInfoDaoMock; @Mock @@ -87,7 +377,8 @@ public class VersioningManagerImplTest { MockitoAnnotations.initMocks(this); } - /* @BeforeClass + */ +/* @BeforeClass private void init() { versionInfoDaoMock.delete(new VersionInfoEntity(TYPE1, ID1)); versionInfoDaoMock.delete(new VersionInfoEntity(TYPE1, ID2)); @@ -103,8 +394,10 @@ public class VersioningManagerImplTest { new VersionableEntityMetadata(TYPE1_TABLE_NAME, TYPE1_ID_NAME, TYPE1_VERSION_NAME)); versioningManager.register(TYPE2, new VersionableEntityMetadata(TYPE2_TABLE_NAME, TYPE2_ID_NAME, TYPE2_VERSION_NAME)); - }*/ + }*//* + +*/ /* @Test public void testRegister() throws Exception { VersionableEntityMetadata entityMetadata = @@ -116,7 +409,8 @@ public class VersioningManagerImplTest { Set type1Entities = versionableEntities.get(TYPE1); Assert.assertNotNull(type1Entities); Assert.assertTrue(type1Entities.contains(entityMetadata)); - }*/ + }*//* + @Test(expectedExceptions = CoreException.class) public void testCreateAlreadyExisting() { @@ -129,8 +423,10 @@ public class VersioningManagerImplTest { Version version = versioningManager.create(TYPE1, ID1, USR1); Assert.assertEquals(version, VERSION01); +*/ /* createVersionableEntityRecord(TYPE1_TABLE_NAME, TYPE1_ID_NAME, TYPE1_VERSION_NAME, ID1, - version);*/ + version);*//* + verify(versionInfoDaoMock).create(versionInfoEntityArg.capture()); VersionInfoEntity versionInfoEntity = versionInfoEntityArg.getValue(); assretVersionInfoEntity(versionInfoEntity, TYPE1, ID1, new Version(0, 0), VERSION01, USR1, @@ -152,7 +448,7 @@ public class VersioningManagerImplTest { @Test public void testDelete() { VersionInfoEntity versionInfoEntity = new VersionInfoEntity(); - versionInfoEntity.setStatus(VersionStatus.Available); + versionInfoEntity.setStatus(VersionStatus.Draft); doReturn(versionInfoEntity).when(versionInfoDaoMock).get(anyObject()); versioningManager.delete(TYPE1, ID1, USR1); @@ -171,13 +467,14 @@ public class VersioningManagerImplTest { @Test public void testUndoDelete() { VersionInfoDeletedEntity versionInfoDeletedEntity = new VersionInfoDeletedEntity(); - versionInfoDeletedEntity.setStatus(VersionStatus.Available); + versionInfoDeletedEntity.setStatus(VersionStatus.Draft); doReturn(versionInfoDeletedEntity).when(versionInfoDeletedDaoMock).get(anyObject()); versioningManager.undoDelete(TYPE1, ID1, USR1); verify(versionInfoDeletedDaoMock).delete(versionInfoDeletedEntity); verify(versionInfoDaoMock).create(versionInfoEntityArg.capture()); +*/ /* VersionInfoDeletedEntity versionInfoDeletedEntity = versionInfoDeletedDaoMock.get(new VersionInfoDeletedEntity(TYPE1, ID1)); @@ -190,7 +487,8 @@ public class VersioningManagerImplTest { Assert.assertNull(versionInfoEntity); versioningManager.undoDelete(TYPE1, ID1, USR1); versionInfoEntity = versionInfoDaoMock.get(new VersionInfoEntity(TYPE1, ID1)); - Assert.assertNotNull(versionInfoEntity);*/ + Assert.assertNotNull(versionInfoEntity);*//* + } @Test(expectedExceptions = CoreException.class) @@ -216,7 +514,7 @@ public class VersioningManagerImplTest { public void testCheckoutOnFinalized() { Set viewableVersions = new HashSet<>(); viewableVersions.add(VERSION10); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Final, VERSION10, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Certified, VERSION10, null, viewableVersions, VERSION10); Version version = versioningManager.checkout(TYPE1, ID1, USR1); @@ -225,18 +523,20 @@ public class VersioningManagerImplTest { VersionInfoEntity versionInfoEntity = versionInfoDaoMock.get(new VersionInfoEntity(TYPE1, ID1)); assretVersionInfoEntity(versionInfoEntity, TYPE1, ID1, VERSION10, VERSION11, USR1, VersionStatus.Locked, viewableVersions, VERSION10); +*/ /* ResultSet results = loadVersionableEntityRecord(TYPE1_TABLE_NAME, TYPE1_ID_NAME, TYPE1_VERSION_NAME, ID1, VERSION11); - Assert.assertTrue(results.iterator().hasNext());*/ + Assert.assertTrue(results.iterator().hasNext());*//* + } @Test public void testCheckout() { Set viewableVersions = new HashSet<>(); viewableVersions.add(VERSION01); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Available, VERSION01, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Draft, VERSION01, null, viewableVersions, null); Version version = versioningManager.checkout(TYPE1, ID1, USR1); @@ -248,10 +548,12 @@ public class VersioningManagerImplTest { assretVersionInfoEntity(versionInfoEntity, TYPE1, ID1, VERSION01, VERSION02, USR1, VersionStatus.Locked, viewableVersions, null); +*/ /* ResultSet results = loadVersionableEntityRecord(TYPE1_TABLE_NAME, TYPE1_ID_NAME, TYPE1_VERSION_NAME, ID1, VERSION02); - Assert.assertTrue(results.iterator().hasNext());*/ + Assert.assertTrue(results.iterator().hasNext());*//* + } @Test(expectedExceptions = CoreException.class) @@ -263,7 +565,7 @@ public class VersioningManagerImplTest { public void testUndoCheckoutOnAvailable() { Set viewableVersions = new HashSet<>(); viewableVersions.add(VERSION01); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Available, VERSION01, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Draft, VERSION01, null, viewableVersions, null); versioningManager.undoCheckout(TYPE1, ID1, USR1); @@ -273,7 +575,7 @@ public class VersioningManagerImplTest { public void testUndoCheckouOnFinalized() { Set viewableVersions = new HashSet<>(); viewableVersions.add(VERSION10); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Final, VERSION10, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Certified, VERSION10, null, viewableVersions, VERSION10); versioningManager.undoCheckout(TYPE1, ID1, USR2); } @@ -298,12 +600,14 @@ public class VersioningManagerImplTest { VersionInfoEntity versionInfoEntity = versionInfoDaoMock.get(new VersionInfoEntity(TYPE1, ID1)); assretVersionInfoEntity(versionInfoEntity, TYPE1, ID1, VERSION01, null, null, - VersionStatus.Available, viewableVersions, null); + VersionStatus.Draft, viewableVersions, null); +*/ /* ResultSet results = loadVersionableEntityRecord(TYPE1_TABLE_NAME, TYPE1_ID_NAME, TYPE1_VERSION_NAME, ID1, VERSION02); - Assert.assertFalse(results.iterator().hasNext());*/ + Assert.assertFalse(results.iterator().hasNext());*//* + } @Test(expectedExceptions = CoreException.class) @@ -315,7 +619,7 @@ public class VersioningManagerImplTest { public void testCheckinOnAvailable() { Set viewableVersions = new HashSet<>(); viewableVersions.add(VERSION01); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Available, VERSION01, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Draft, VERSION01, null, viewableVersions, null); versioningManager.checkin(TYPE1, ID1, USR1, "fail checkin"); @@ -326,7 +630,7 @@ public class VersioningManagerImplTest { public void testCheckinOnFinalized() { Set viewableVersions = new HashSet<>(); viewableVersions.add(VERSION10); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Final, VERSION10, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Certified, VERSION10, null, viewableVersions, VERSION10); versioningManager.checkin(TYPE1, ID1, USR1, "failed checkin"); @@ -354,7 +658,7 @@ public class VersioningManagerImplTest { viewableVersions.add(VERSION01); assretVersionInfoEntity(versionInfoEntity, TYPE1, ID1, VERSION01, null, null, - VersionStatus.Available, viewableVersions, null); + VersionStatus.Draft, viewableVersions, null); } @Test(expectedExceptions = CoreException.class) @@ -374,7 +678,7 @@ public class VersioningManagerImplTest { public void testSubmitOnFinalized() { Set viewableVersions = new HashSet<>(); viewableVersions.add(VERSION10); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Final, VERSION10, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Certified, VERSION10, null, viewableVersions, VERSION10); versioningManager.submit(TYPE1, ID1, USR2, "failed submit"); } @@ -390,7 +694,7 @@ public class VersioningManagerImplTest { viewableVersions.add(new Version(3, 0)); viewableVersions.add(new Version(3, 1)); viewableVersions.add(version32); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Available, version32, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Draft, version32, null, viewableVersions, new Version(3, 0)); Version version = versioningManager.submit(TYPE1, ID1, USR1, "submit msg"); @@ -403,12 +707,14 @@ public class VersioningManagerImplTest { VersionInfoEntity versionInfoEntity = versionInfoEntityArg.getValue(); assretVersionInfoEntity(versionInfoEntity, TYPE1, ID1, version40, null, null, - VersionStatus.Final, viewableVersions, version40); + VersionStatus.Certified, viewableVersions, version40); +*/ /* ResultSet results = loadVersionableEntityRecord(TYPE1_TABLE_NAME, TYPE1_ID_NAME, TYPE1_VERSION_NAME, ID1, VERSION10); - Assert.assertTrue(results.iterator().hasNext());*/ + Assert.assertTrue(results.iterator().hasNext());*//* + } @Test(expectedExceptions = CoreException.class) @@ -420,12 +726,12 @@ public class VersioningManagerImplTest { public void testGetVersionInfoForReadOnAvailable() { Set viewableVersions = new HashSet<>(); viewableVersions.add(VERSION01); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Available, VERSION01, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Draft, VERSION01, null, viewableVersions, null); VersionInfo versionInfo = versioningManager.getEntityVersionInfo(TYPE1, ID1, USR1, VersionableEntityAction.Read); - assertVersionInfo(versionInfo, VERSION01, VersionStatus.Available, null, + assertVersionInfo(versionInfo, VERSION01, VersionStatus.Draft, null, viewableVersions, null); } @@ -433,7 +739,7 @@ public class VersioningManagerImplTest { public void testGetVersionInfoForWriteOnAvailable() { Set viewableVersions = new HashSet<>(); viewableVersions.add(VERSION01); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Available, VERSION01, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Draft, VERSION01, null, viewableVersions, null); versioningManager.getEntityVersionInfo(TYPE1, ID1, USR1, VersionableEntityAction.Write); @@ -488,6 +794,7 @@ public class VersioningManagerImplTest { assertVersionInfo(versionInfo, VERSION02, VersionStatus.Locked, USR1, viewableVersions, null); } +*/ /* private void createVersionableEntityRecord(String tableName, String idName, String versionName, String id, Version version) { noSqlDb.execute( @@ -500,7 +807,8 @@ public class VersioningManagerImplTest { return noSqlDb.execute( String.format("select * from %s where %s=? and %s=?", tableName, idName, versionName), id, versionMapper.toUDT(version)); - }*/ + }*//* + private static void assretVersionInfoEntity(VersionInfoEntity actual, String entityType, @@ -553,4 +861,5 @@ public class VersioningManagerImplTest { doReturn(mock).when(versionInfoDaoMock).get(anyObject()); return mock; } +*/ } 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 f9a3da2e75..daeb570086 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 @@ -5,15 +5,14 @@ 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. Reason - %s"; + "Can't create %s from %s."; private static final String IMPORT_TOSCA = "IMPORT_TOSCA"; public CreateToscaObjectErrorBuilder(String className, - String objectId, - String reason) { + String objectId) { getErrorCodeBuilder() .withId(IMPORT_TOSCA) .withCategory(ErrorCategory.APPLICATION) - .withMessage(String.format(CANT_CREATE_OBJECT_FROM_CLASS, className, objectId, reason)); + .withMessage(String.format(CANT_CREATE_OBJECT_FROM_CLASS, className, objectId)); } } 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 e7ff3aa8ee..39a53b499d 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 @@ -12,7 +12,17 @@ import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import org.openecomp.sdc.tosca.datatypes.model.*; +import org.openecomp.sdc.tosca.datatypes.model.ArtifactDefinition; +import org.openecomp.sdc.tosca.datatypes.model.CapabilityAssignment; +import org.openecomp.sdc.tosca.datatypes.model.Import; +import org.openecomp.sdc.tosca.datatypes.model.InterfaceDefinition; +import org.openecomp.sdc.tosca.datatypes.model.NodeFilter; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.datatypes.model.SubstitutionMapping; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; @@ -21,11 +31,28 @@ import org.yaml.snakeyaml.error.YAMLException; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; -import java.util.*; +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 java.util.jar.Manifest; import java.util.regex.Pattern; -import static org.openecomp.core.converter.datatypes.Constants.*; +import static org.openecomp.core.converter.datatypes.Constants.capabilities; +import static org.openecomp.core.converter.datatypes.Constants.definitionsDir; +import static org.openecomp.core.converter.datatypes.Constants.globalStName; +import static org.openecomp.core.converter.datatypes.Constants.globalSubstitution; +import static org.openecomp.core.converter.datatypes.Constants.inputs; +import static org.openecomp.core.converter.datatypes.Constants.mainStName; +import static org.openecomp.core.converter.datatypes.Constants.manifestFileName; +import static org.openecomp.core.converter.datatypes.Constants.metadataFile; +import static org.openecomp.core.converter.datatypes.Constants.nodeType; +import static org.openecomp.core.converter.datatypes.Constants.openecompHeatIndex; +import static org.openecomp.core.converter.datatypes.Constants.outputs; +import static org.openecomp.core.converter.datatypes.Constants.requirements; import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.GLOBAL_SUBSTITUTION_SERVICE_FILE_NAME; public class ToscaConverterImpl implements ToscaConverter { @@ -89,9 +116,8 @@ public class ToscaConverterImpl implements ToscaConverter { } } catch (YAMLException ye) { throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withMessage("Invalid YAML content in file " + key + ". reason - " - + ye.getMessage()) - .withCategory(ErrorCategory.APPLICATION).build()); + .withMessage("Invalid YAML content in file " + key) + .withCategory(ErrorCategory.APPLICATION).build(), ye); } } @@ -181,9 +207,8 @@ public class ToscaConverterImpl implements ToscaConverter { } catch (YAMLException ye) { throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withMessage("Invalid YAML content in file" + serviceTemplateName + ". reason - " - + ye.getMessage()) - .withCategory(ErrorCategory.APPLICATION).build()); + .withMessage("Invalid YAML content in file" + serviceTemplateName) + .withCategory(ErrorCategory.APPLICATION).build(), ye); } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterManagerImpl.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterManagerImpl.java index 520e41817e..4917533dd8 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterManagerImpl.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterManagerImpl.java @@ -5,6 +5,8 @@ import org.openecomp.core.converter.api.ToscaConverterManager; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.utilities.json.JsonUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import java.lang.reflect.Constructor; @@ -14,8 +16,10 @@ import java.util.Map; public class ToscaConverterManagerImpl implements ToscaConverterManager { + private static final Logger LOGGER = LoggerFactory.getLogger(ToscaConverterManagerImpl.class.getName()); private static List toscaConverters; private static final String toscaConverterFileName = "ToscaConverters.json"; + private static final String TOSCA_CONVERTER_IMPL_FORMAT_ERROR = "Failed to construct TOSCA converter for '%s' implementation."; static { toscaConverters = getConvertersList(); @@ -40,7 +44,8 @@ public class ToscaConverterManagerImpl implements ToscaConverterManager { Class clazz = Class.forName(implClassName); Constructor constructor = clazz.getConstructor(); toscaConvertersList.add((ToscaConverter) constructor.newInstance()); - }catch (Exception e){ + }catch (Exception ex){ + LOGGER.debug(String.format(TOSCA_CONVERTER_IMPL_FORMAT_ERROR, implClassName), ex); continue; } } 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 20ac6413e7..d34d46796d 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 @@ -4,6 +4,8 @@ import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.openecomp.core.converter.errors.CreateToscaObjectErrorBuilder; import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import java.lang.reflect.Field; import java.util.HashSet; @@ -20,6 +22,8 @@ public class ToscaConverterUtil { private static final String DEFAULT_CAPITAL = "Default"; private static Set defaultValueKeys; + private static Logger LOGGER = LoggerFactory.getLogger(ToscaConverterUtil.class.getName()); + static { defaultValueKeys = Stream.of(DEFAULT, DEFAULT_CAPITAL).collect(Collectors.toSet()); @@ -30,10 +34,10 @@ public class ToscaConverterUtil { Class classToCreate) { try { return createObjectUsingSetters(objectCandidate, classToCreate); - } catch (Exception e) { + } catch (Exception ex) { throw new CoreException( - new CreateToscaObjectErrorBuilder(classToCreate.getSimpleName(), objectId, e.getMessage()) - .build()); + new CreateToscaObjectErrorBuilder(classToCreate.getSimpleName(), objectId) + .build(), ex); } } @@ -68,6 +72,8 @@ public class ToscaConverterUtil { return Objects.nonNull(fieldValueToAssign) && Objects.nonNull(classToCreate.getMethod(methodName, field.getType())); } catch (NoSuchMethodException e) { + LOGGER.debug(String.format("Could not extract method '%s' from class '%s'. returning false " + + "with filedType '%s'.", methodName, classToCreate, field.getType()), e); return false; } } 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 22780af343..ee39af98c9 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 @@ -7,7 +7,14 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; -import static org.openecomp.core.converter.datatypes.Constants.*; +import static org.openecomp.core.converter.datatypes.Constants.definitionVersion; +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.nodeTemplates; +import static org.openecomp.core.converter.datatypes.Constants.nodeTypes; +import static org.openecomp.core.converter.datatypes.Constants.outputs; +import static org.openecomp.core.converter.datatypes.Constants.substitutionMappings; +import static org.openecomp.core.converter.datatypes.Constants.topologyTemplate; public class ServiceTemplateReaderServiceImpl implements ServiceTemplateReaderService { diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConverterImplTest.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConverterImplTest.java index 5ee96aba07..df34b89cbb 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConverterImplTest.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConverterImplTest.java @@ -2,7 +2,6 @@ package org.openecomp.core.converter.impl; import org.apache.commons.collections.CollectionUtils; import org.junit.Assert; -import org.junit.Ignore; import org.junit.Test; import org.openecomp.core.converter.ToscaConverter; import org.openecomp.core.impl.ToscaConverterImpl; diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConvertorDefinitionsTest.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConvertorDefinitionsTest.java index 1ee8f6c05f..82a36950f3 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConvertorDefinitionsTest.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConvertorDefinitionsTest.java @@ -13,9 +13,15 @@ import java.net.URL; import java.util.Map; import java.util.Set; -import static org.openecomp.sdc.common.utils.CommonUtil.*; -import static org.junit.Assert.*; -import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.DEFININTION_VERSION; +import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.GLOBAL_SUBSTITUTION_SERVICE_FILE_NAME; +import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.HEAT_INDEX; +import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.TEMPLATE_NAME_PROPERTY; +import static org.openecomp.sdc.common.utils.CommonUtil.validateAndUploadFileContent; public class ToscaConvertorDefinitionsTest { 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 45e6c3deef..30e767beeb 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 @@ -53,8 +53,8 @@ import org.openecomp.sdc.tosca.errors.ToscaNodeTypeNotFoundErrorBuilder; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; +import org.openecomp.sdc.tosca.services.ToscaUtil; import java.util.ArrayList; import java.util.Collection; diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java index aad21634a8..d082d2febf 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java @@ -20,12 +20,6 @@ package org.openecomp.sdc.tosca.services.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; @@ -58,6 +52,12 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + /** * @author Avrahamg diff --git a/openecomp-be/lib/pom.xml b/openecomp-be/lib/pom.xml index ea1faaec4b..d031dd4d04 100644 --- a/openecomp-be/lib/pom.xml +++ b/openecomp-be/lib/pom.xml @@ -10,7 +10,7 @@ openecomp-sdc org.openecomp.sdc 1.2.0-SNAPSHOT - .. + .. @@ -33,5 +33,8 @@ openecomp-sdc-activity-log-lib openecomp-tosca-converter-lib openecomp-sdc-orchestration-lib + openecomp-sdc-notification-lib + openecomp-item-permissions-lib + openecomp-conflict-lib diff --git a/openecomp-be/pom.xml b/openecomp-be/pom.xml index 02da3b9e46..dba8d0f755 100644 --- a/openecomp-be/pom.xml +++ b/openecomp-be/pom.xml @@ -21,7 +21,7 @@ /lib /configuration /tools/swagger-ui - /tools/migration/1702_to_1707_zusammen + /tools/zusammen-tools /backend @@ -159,7 +159,7 @@ - + + <!– Execute an ant task within maven –> @@ -212,7 +212,7 @@ ${jacoco.version} - + --> @@ -262,7 +262,7 @@ classmate ${classmate.version} - + org.slf4j @@ -274,7 +274,7 @@ groovy-all ${groovy.version} - + org.codehaus.janino janino ${janino.version} diff --git a/openecomp-be/tools/build/scripts/cassandra-commands.json b/openecomp-be/tools/build/scripts/cassandra-commands.json index 2935acad4a..34916fe74d 100644 --- a/openecomp-be/tools/build/scripts/cassandra-commands.json +++ b/openecomp-be/tools/build/scripts/cassandra-commands.json @@ -5,22 +5,7 @@ "version_info": "CREATE TABLE IF NOT EXISTS version_info (entity_type text, entity_id text, active_version frozen, status text, candidate frozen, viewable_versions set>, latest_final_version frozen, PRIMARY KEY (entity_type, entity_id))", "version_info_deleted": "CREATE TABLE IF NOT EXISTS version_info_deleted (entity_type text, entity_id text, active_version frozen, status text, candidate frozen, viewable_versions set>, latest_final_version frozen, PRIMARY KEY (entity_type, entity_id))", "unique_value" : "CREATE TABLE IF NOT EXISTS unique_value (type text, value text, PRIMARY KEY ((type, value)))", - "choice_or_other": "CREATE TYPE IF NOT EXISTS choice_or_other (result text)", - "multi_choice_or_other": "CREATE TYPE IF NOT EXISTS multi_choice_or_other (results set)", - "vendor_license_model": "CREATE TABLE IF NOT EXISTS vendor_license_model (vlm_id text, version frozen, vendor_name text, description text, icon text, PRIMARY KEY ((vlm_id, version)))", - "license_agreement": "CREATE TABLE IF NOT EXISTS license_agreement (vlm_id text, version frozen, la_id text, name text, description text, lic_term frozen, req_const text, fg_ids set, PRIMARY KEY ((vlm_id, version), la_id))", - "feature_group": "CREATE TABLE IF NOT EXISTS feature_group (vlm_id text, version frozen, fg_id text, name text, description text, part_num text, ep_ids set, lkg_ids set, ref_la_ids set, PRIMARY KEY ((vlm_id, version), fg_id))", - "license_key_group": "CREATE TABLE IF NOT EXISTS license_key_group (vlm_id text, version frozen, lkg_id text,name text,description text, type text, operational_scope frozen, ref_fg_ids set, version_uuid text, PRIMARY KEY ((vlm_id, version), lkg_id))", - "entitlement_pool": "CREATE TABLE IF NOT EXISTS entitlement_pool (vlm_id text, version frozen, ep_id text,name text,description text,threshold float,threshold_unit text,entitlement_metric frozen,increments text,aggregation_func frozen, operational_scope frozen, time frozen,manufacturer_ref_num text,ref_fg_ids set, version_uuid text, PRIMARY KEY ((vlm_id, version), ep_id))", - "vsp_information": "CREATE TABLE IF NOT EXISTS vsp_information (VSP_ID text, version frozen, NAME text,DESCRIPTION text,CATEGORY text,SUB_CATEGORY text,ICON text,PACKAGE_NAME text,PACKAGE_VERSION text,vendor_name text, vendor_id text,LICENSE_AGREEMENT text,FEATURE_GROUPS list,VALIDATION_DATA text,CONTENT_DATA blob, questionnaire_data text, vlm_version frozen, is_old_version text, onboarding_method text, PRIMARY KEY ((VSP_ID, version)))", - "package_details": "CREATE TABLE IF NOT EXISTS package_details (VSP_ID text, version frozen,DISPLAY_NAME text,vsp_name text,vsp_description text,VENDOR_NAME text,CATEGORY text,SUB_CATEGORY text,VENDOR_RELEASE text,PACKAGE_CHECKSUM text,PACKAGE_TYPE text,TRANSLATE_CONTENT blob,PRIMARY KEY ((VSP_ID, version)))", - "vsp_network": "CREATE TABLE IF NOT EXISTS vsp_network (vsp_id text, version frozen, network_id text, composition_data text, questionnaire_data text, PRIMARY KEY ((vsp_id, version), network_id))", - "vsp_component": "CREATE TABLE IF NOT EXISTS vsp_component (vsp_id text, version frozen, component_id text, composition_data text, questionnaire_data text, PRIMARY KEY ((vsp_id, version), component_id))", - "vsp_component_nic": "CREATE TABLE IF NOT EXISTS vsp_component_nic (vsp_id text, version frozen, component_id text, nic_id text, composition_data text, questionnaire_data text, PRIMARY KEY ((vsp_id, version), component_id, nic_id))", - "vsp_component_image": "CREATE TABLE IF NOT EXISTS vsp_component_image (vsp_id text, version frozen, component_id text, image_id text, composition_data text, questionnaire_data text, PRIMARY KEY ((vsp_id, version), component_id, image_id))", - "vsp_process" : "CREATE TABLE IF NOT EXISTS vsp_process (vsp_id text, version frozen, component_id text, process_id text, name text, description text, type text, artifact_name text, artifact blob, PRIMARY KEY ((vsp_id, version), component_id, process_id))", - "vsp_service_artifact" : "CREATE TABLE IF NOT EXISTS vsp_service_artifact (vsp_id text, version frozen, name text, content_data blob, PRIMARY KEY ((vsp_id, version), name))", - "vsp_service_template" : "CREATE TABLE IF NOT EXISTS vsp_service_template (vsp_id text, version frozen, base_name text static, name text, content_data blob, PRIMARY KEY ((vsp_id, version), name))", + "package_details": "CREATE TABLE IF NOT EXISTS package_details (VSP_ID text, version text,DISPLAY_NAME text,vsp_name text,vsp_description text,VENDOR_NAME text,CATEGORY text,SUB_CATEGORY text,VENDOR_RELEASE text,PACKAGE_CHECKSUM text,PACKAGE_TYPE text,TRANSLATE_CONTENT blob,PRIMARY KEY ((VSP_ID, version)))", "vsp_enriched_service_template" : "CREATE TABLE IF NOT EXISTS vsp_enriched_service_template (vsp_id text, version frozen, base_name text static, name text, content_data blob, PRIMARY KEY ((vsp_id, version), name))", "vsp_enriched_service_artifact" : "CREATE TABLE IF NOT EXISTS vsp_enriched_service_artifact (vsp_id text, version frozen, name text, content_data blob, PRIMARY KEY ((vsp_id, version), name))", "application_config" : "CREATE TABLE IF NOT EXISTS application_config (namespace text, key text, value text, PRIMARY KEY (namespace, key))", @@ -31,37 +16,22 @@ "vendor_list_index" : "CREATE INDEX IF NOT EXISTS action_vendor_list ON dox.Action (vendor_list)", "actionUUID_index" : "CREATE INDEX IF NOT EXISTS action_actionUUID ON dox.Action (actionUUID)", "ecomp_component": "CREATE TABLE IF NOT EXISTS dox.ecompcomponent(id text PRIMARY KEY, name text)", - "vsp_component_artifact": "CREATE TABLE IF NOT EXISTS vsp_component_artifact (vsp_id text, version frozen, component_id text, artifact_type text, artifact_id text, name text, description text, artifact blob, PRIMARY KEY ((vsp_id, version), component_id, artifact_type, artifact_id))", "name_index": "CREATE INDEX IF NOT EXISTS action_name ON dox.Action (name)", "action_artifact":"CREATE TABLE IF NOT EXISTS action_artifact(artifactuuid text, effective_version int, artifact blob, PRIMARY KEY(artifactuuid, effective_version)) WITH CLUSTERING ORDER BY (effective_version DESC)", - "vsp_orchestration_template_candidate" : "CREATE TABLE IF NOT EXISTS vsp_orchestration_template_candidate (vsp_id text, version frozen, files_data_structure text, content_data blob, PRIMARY KEY ((vsp_id, version)))", - "vsp_deployment_flavor" : "CREATE TABLE IF NOT EXISTS vsp_deployment_flavor (vsp_id text, version frozen, deployment_flavor_id text, composition_data text, questionnaire_data text, PRIMARY KEY ((vsp_id, version), deployment_flavor_id))", - "vsp_component_compute": "CREATE TABLE IF NOT EXISTS vsp_component_compute (vsp_id text, version frozen, component_id text, compute_id text, composition_data text, questionnaire_data text, PRIMARY KEY ((vsp_id, version), component_id, compute_id))", - "vsp_component_dependency_model" : "CREATE TABLE IF NOT EXISTS vsp_component_dependency_model (vsp_id text, version frozen, dependency_id text, sourcecomponent_id text, targetcomponent_id text, relation text, PRIMARY KEY ((vsp_id, version), dependency_id))", "activity_log" : "CREATE TABLE IF NOT EXISTS activity_log (item_id text, version_id text, activity_id text, type text, user text, timestamp timestamp, success boolean, message text, comment text, PRIMARY KEY (item_id, version_id, activity_id))", - "migration": "CREATE TABLE IF NOT EXISTS migration (id text, ismigrated boolean, primary key(id))" + "healing" : "CREATE TABLE IF NOT EXISTS healing (space text,item_id text,version_id text, healing_needed boolean,old_version text, PRIMARY KEY((space,item_id),version_id))", + "migration": "CREATE TABLE IF NOT EXISTS migration (id text, ismigrated boolean, primary key (id))", + "item_permissions" : "CREATE TABLE IF NOT EXISTS item_permissions (item_id text,user_id text, permission text, PRIMARY KEY(item_id,user_id)) WITH CLUSTERING ORDER BY (user_id DESC)", + "notification_subscribers": "CREATE TABLE IF NOT EXISTS NOTIFICATION_SUBSCRIBERS (entity_id text PRIMARY KEY, subscribers set)", + "last_notification": "CREATE TABLE IF NOT EXISTS last_notification (owner_id text PRIMARY KEY, event_id timeuuid)", + "notifications": "CREATE TABLE IF NOT EXISTS notifications (owner_id text, event_id timeuuid, read boolean, originator_id text, event_type text, event_attributes text, PRIMARY KEY (owner_id, event_id)) WITH CLUSTERING ORDER BY (event_id DESC)", + "vsp_merge_hint": "CREATE TABLE IF NOT EXISTS vsp_merge_hint (space text, item_id text, version_id text, model_id text, model_resolution text, PRIMARY KEY ((space, item_id, version_id)))" }, "drop": { - "version_info": "DROP TABLE IF EXISTS version_info", "version_info_deleted": "DROP TABLE IF EXISTS version_info_deleted", "unique_value": "DROP TABLE IF EXISTS unique_value", - "entitlement_pool": "DROP TABLE IF EXISTS entitlement_pool", - "vendor_license_model": "DROP TABLE IF EXISTS vendor_license_model", - "license_agreement": "DROP TABLE IF EXISTS license_agreement", - "feature_group": "DROP TABLE IF EXISTS feature_group", - "license_key_group": "DROP TABLE IF EXISTS license_key_group", - "vsp_information": "DROP TABLE IF EXISTS vsp_information", "package_details": "DROP TABLE IF EXISTS package_details", - "vsp_network": "DROP TABLE IF EXISTS vsp_network", - "vsp_component_image": "DROP TABLE IF EXISTS vsp_component_image", - "vsp_component": "DROP TABLE IF EXISTS vsp_component", - "vsp_component_nic": "DROP TABLE IF EXISTS vsp_component_nic", - "vsp_process":"DROP TABLE IF EXISTS vsp_process", - "choice_or_other": "DROP TYPE IF EXISTS choice_or_other", - "multi_choice_or_other": "DROP TYPE IF EXISTS multi_choice_or_other", "application_config" : "DROP TABLE IF EXISTS application_config", - "vsp_service_artifact" :"DROP TABLE IF EXISTS vsp_service_artifact", - "vsp_service_template" :"DROP TABLE IF EXISTS vsp_service_template", "vsp_enriched_service_artifact" :"DROP TABLE IF EXISTS vsp_enriched_service_artifact", "vsp_enriched_service_template" :"DROP TABLE IF EXISTS vsp_enriched_service_template", "action" : "DROP TABLE IF EXISTS action", @@ -72,22 +42,16 @@ "actionUUID_index" : "DROP INDEX IF EXISTS dox.action_actionUUID", "name_index" : "DROP INDEX IF EXISTS dox.action_name", "ecomp_component": "DROP TABLE IF EXISTS dox.ecompcomponent", - "vsp_component_artifact": "DROP TABLE IF EXISTS dox.vsp_component_artifact", "action_artifact":"DROP TABLE IF EXISTS action_artifact", - "vsp_orchestration_template_candidate":"DROP TABLE IF EXISTS vsp_orchestration_template_candidate", - "vsp_deployment_flavor":"DROP TABLE IF EXISTS vsp_deployment_flavor", - "vsp_component_dependency_model":"DROP TABLE IF EXISTS vsp_component_dependency_model", "activity_log": "DROP TABLE IF EXISTS activity_log", - "migration": "DROP TABLE IF EXISTS migration" + "migration": "DROP TABLE IF EXISTS migration", + "item_permissions": "DROP TABLE IF EXISTS item_permissions", + "notification_subscribers": "DROP TABLE IF EXISTS notification_subscribers", + "last_notification": "DROP TABLE IF EXISTS last_notification", + "notifications": "DROP TABLE IF EXISTS notifications", + "vsp_merge_hint": "DROP TABLE IF EXISTS vsp_merge_hint" }, "alter": { - "vsp_information": "ALTER TABLE vsp_information ADD questionnaire_data text", - "vsp_information_1": "ALTER TABLE vsp_information ADD vlm_version frozen", - "vsp_information_2": "ALTER TABLE vsp_information ADD onboarding_method text", - "vsp_process": "ALTER TABLE vsp_process ADD type text", - "entitlement_pool": "alter table entitlement_pool ADD version_uuid text", - "license_key_group": "alter table license_key_group ADD version_uuid text", - "application_config": "delete from application_config where namespace='vsp.monitoring' and key = 'component.ceilometer'" }, "actions": { "truncate_configuration": "truncate configuration" diff --git a/openecomp-be/tools/build/scripts/zusammen-cassandra-commands.json b/openecomp-be/tools/build/scripts/zusammen-cassandra-commands.json index 1395fec8f1..5ddb1d7024 100644 --- a/openecomp-be/tools/build/scripts/zusammen-cassandra-commands.json +++ b/openecomp-be/tools/build/scripts/zusammen-cassandra-commands.json @@ -1,19 +1,26 @@ { "create": { "item": "CREATE TABLE IF NOT EXISTS item (item_id text primary key, item_info text, creation_time timestamp, modification_time timestamp)", - "version": "CREATE TABLE IF NOT EXISTS version (space text, item_id text, version_id text,base_version_id text,info text,relations text,creation_time timestamp,modification_time timestamp,PRIMARY KEY (( space, item_id ), version_id))", - "version_elements": "CREATE TABLE IF NOT EXISTS version_elements (space text,item_id text,version_id text,element_ids set,PRIMARY KEY (( space, item_id, version_id )))", - "element_namespace": "CREATE TABLE IF NOT EXISTS element_namespace (space text, item_id text, element_id text, namespace text, PRIMARY KEY ((space, item_id, element_id)))", - "element": "CREATE TABLE IF NOT EXISTS element (space text,item_id text,version_id text,element_id text,parent_id text,namespace text,info text,relations text,data blob,searchable_data blob,visualization blob,sub_element_ids set,PRIMARY KEY (( space, item_id, version_id, element_id )))" + "version": "CREATE TABLE IF NOT EXISTS version (space text, item_id text, version_id text,base_version_id text,info text,relations text,creation_time timestamp,modification_time timestamp ,PRIMARY KEY (( space, item_id ), version_id))", + "version_elements": "CREATE TABLE IF NOT EXISTS version_elements (space text,item_id text,version_id text,revision_id text,element_ids Map, dirty_element_ids set,stage_element_ids set, conflict_element_ids set, publish_time timestamp,user text,message text, PRIMARY KEY (( space, item_id, version_id ),revision_id))", + "element_namespace": "CREATE TABLE IF NOT EXISTS element_namespace (item_id text, element_id text, namespace text, PRIMARY KEY ((item_id, element_id)))", + "element": "CREATE TABLE IF NOT EXISTS element (space text,item_id text,version_id text,element_id text,revision_id text,parent_id text,namespace text,info text,relations text,data blob,searchable_data blob,visualization blob,sub_element_ids set ,element_hash text,PRIMARY KEY (( space, item_id, version_id, element_id ),revision_id))", + "element_synchronization_state": "CREATE TABLE IF NOT EXISTS element_synchronization_state (space text, item_id text, version_id text, element_id text,revision_id text, publish_time timestamp, dirty boolean, PRIMARY KEY (( space, item_id, version_id ), element_id,revision_id))", + "element_stage": "CREATE TABLE IF NOT EXISTS element_stage (space text, item_id text,version_id text, element_id text, parent_id text, namespace text, info text, relations text,data blob, searchable_data blob, visualization blob, sub_element_ids set,element_hash text, publish_time timestamp, action text, conflicted boolean,conflict_dependent_ids set, PRIMARY KEY (( space, item_id, version_id, element_id )))", + "version_stage": "CREATE TABLE IF NOT EXISTS version_stage (space text, item_id text, version_id text, base_version_id text, creation_time timestamp,modification_time timestamp, publish_time timestamp, action text, PRIMARY KEY (( space, item_id ), version_id))" }, "drop": { "item": "DROP TABLE IF EXISTS item", "version": "DROP TABLE IF EXISTS version", "version_elements": "DROP TABLE IF EXISTS version_elements", "element_namespace": "DROP TABLE IF EXISTS element_namespace", - "element": "DROP TABLE IF EXISTS element" + "element": "DROP TABLE IF EXISTS element", + "element_synchronization_state": "DROP TABLE IF EXISTS element_synchronization_state", + "element_stage": "DROP TABLE IF EXISTS element_stage", + "version_stage": "DROP TABLE IF EXISTS version_stage" }, "alter": { + }, "actions": { } diff --git a/openecomp-be/tools/install/database/schemaTemplates/questionnaire/vsp.ftl b/openecomp-be/tools/install/database/schemaTemplates/questionnaire/vsp.ftl index 96f77b7f23..0f9be1c3e3 100644 --- a/openecomp-be/tools/install/database/schemaTemplates/questionnaire/vsp.ftl +++ b/openecomp-be/tools/install/database/schemaTemplates/questionnaire/vsp.ftl @@ -63,6 +63,7 @@ }, "storageReplicationSize": { "type": "number", + "minimum": 0, "maximum": 100, "exclusiveMaximum": true }, diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/pom.xml b/openecomp-be/tools/migration/1702_to_1707_zusammen/pom.xml deleted file mode 100644 index c2dbc943e5..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/pom.xml +++ /dev/null @@ -1,241 +0,0 @@ - - 4.0.0 - - - - 2.4.7 - 2.7.7 - - - - - - openecomp-zusammen-migration - - - org.openecomp.sdc - openecomp-sdc-vendor-software-product-api - ${project.version} - - - openecomp-zusammen-plugin - org.openecomp.sdc.core - ${project.version} - - - org.openecomp.sdc - openecomp-sdc-vendor-software-product-core - ${project.version} - - - org.openecomp.sdc - openecomp-sdc-vendor-license-api - ${project.version} - - - org.openecomp.sdc - openecomp-sdc-model-impl - ${project.version} - - - org.openecomp.sdc.core - openecomp-zusammen-core - ${project.version} - - - com.amdocs.zusammen.plugin - zusammen-state-store-cassandra-plugin - ${zusammen-state-store.version} - - - org.hibernate - hibernate-validator - ${hibernate.validator.version} - - - org.openecomp.sdc - openecomp-sdc-vendor-license-core - ${project.version} - - - openecomp-zusammen-migration - org.openecomp.sdc.core.migration - 1.2.0-SNAPSHOT - - org.openecomp.sdc - openecomp-sdc-lib - ../../../lib - 1.2.0-SNAPSHOT - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.5.1 - true - - 1.8 - 1.8 - - - - - org.codehaus.mojo - license-maven-plugin - 1.10 - - false - - ============LICENSE_START======================================================= - - - ============LICENSE_END========================================================= - - - ================================================================================ - - apache_v2 - 2017 - AT&T Intellectual Property. All rights reserved. - - SDC - true - true - true - true - false - - **/*.java - **/*.js - **/*.ts - - - src - app - server-mock - typings - - - - - first - - update-file-header - - - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.8 - - - copy-dependencies - install - - copy-dependencies - - - ${project.build.directory}/lib - false - false - true - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - - package - - - - - - true - custom - - lib/${artifact.artifactId}-${baseVersion}.${artifact.extension} - - org.openecomp.core.migration.MigrationMain - - - - lib/ - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.19.1 - - false - true - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - ant-test - package - - - - - - - run - - - - - - maven-assembly-plugin - ${mvn.assembly.version} - - - Generate assembly - install - - single - - - - - - ${basedir}/src/main/assembly/migration-lib-assembly.xml - - - openecomp-zusammen-migration-lib - - - - - - - diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/assembly/migration-lib-assembly.xml b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/assembly/migration-lib-assembly.xml deleted file mode 100644 index 42296baa6e..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/assembly/migration-lib-assembly.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - zip - - - false - - - - - - ${basedir}/.. - - cassandra2zusammen.sh - - / - 0755 - - - ${basedir}/target - - - openecomp-zusammen*.jar - - - / - - - ${basedir}/target/lib - /lib - - - - diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/MigrationMain.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/MigrationMain.java deleted file mode 100644 index 1711e41a65..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/MigrationMain.java +++ /dev/null @@ -1,469 +0,0 @@ -package org.openecomp.core.migration; - -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.UserInfo; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.impl.ItemCassandraDao; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.impl.VersionCassandraDao; -import org.openecomp.core.migration.convertors.ComponentConvertor; -import org.openecomp.core.migration.convertors.EntitlementPoolConvertor; -import org.openecomp.core.migration.convertors.FeatureGroupConvertor; -import org.openecomp.core.migration.convertors.LKGConvertor; -import org.openecomp.core.migration.convertors.LicenseAgreementConvertor; -import org.openecomp.core.migration.convertors.MibConvertor; -import org.openecomp.core.migration.convertors.NetworkConvertor; -import org.openecomp.core.migration.convertors.NicConvertor; -import org.openecomp.core.migration.convertors.OrchestrationTemplateCandidateConvertor; -import org.openecomp.core.migration.convertors.ProcessConvertor; -import org.openecomp.core.migration.convertors.VlmConvertor; -import org.openecomp.core.migration.convertors.VspInformationConvertor; -import org.openecomp.core.migration.convertors.VspServiceArtifactConvertor; -import org.openecomp.core.migration.convertors.VspServiceTemplateConvertor; -import org.openecomp.core.migration.loaders.ComponentCassandraLoader; -import org.openecomp.core.migration.loaders.EntitlementPoolCassandraLoader; -import org.openecomp.core.migration.loaders.FeatureGroupCassandraLoader; -import org.openecomp.core.migration.loaders.LKGCassandraLoader; -import org.openecomp.core.migration.loaders.LicenseAgreementCassandraLoader; -import org.openecomp.core.migration.loaders.MibCassandraLoader; -import org.openecomp.core.migration.loaders.NetworkCassandraLoader; -import org.openecomp.core.migration.loaders.NicCassandraLoader; -import org.openecomp.core.migration.loaders.OrchestrationTemplateCandidateCassandraLoader; -import org.openecomp.core.migration.loaders.ProcessCassandraLoader; -import org.openecomp.core.migration.loaders.ServiceArtifactCassandraLoader; -import org.openecomp.core.migration.loaders.ServiceTemplateCassandraLoader; -import org.openecomp.core.migration.loaders.VendorLicenseModelCassandraLoader; -import org.openecomp.core.migration.loaders.VendorSoftwareProductInfoLoader; -import org.openecomp.core.migration.loaders.VersionInfoCassandraLoader; -import org.openecomp.core.migration.loaders.VspInformation; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.core.migration.store.ItemHandler; -import org.openecomp.core.migration.util.marker.MigrationMarker; -import org.openecomp.core.model.types.ServiceArtifact; -import org.openecomp.core.model.types.ServiceTemplate; -import org.openecomp.core.zusammen.impl.CassandraConnectionInitializer; -import org.openecomp.core.zusammen.plugin.dao.impl.CassandraElementRepository; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; -import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; -import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionInfoEntity; - -import java.time.Duration; -import java.time.Instant; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import static org.openecomp.core.migration.util.Utils.printMessage; - -public class MigrationMain { - private static final String GLOBAL_USER = "GLOBAL_USER"; - private static Logger logger = LoggerFactory.getLogger(MigrationMain.class); - private static int status = 0; - - private static Map versionInfoMap = new HashMap<>(); - - public static void main(String[] args) { - CassandraElementRepository cassandraElementRepository = new CassandraElementRepository(); - CassandraConnectionInitializer.setCassandraConnectionPropertiesToSystem(); - printMessage(logger, "Checking whether a migration has already been run."); - if (MigrationMarker.isMigrated()) { - printMessage(logger, "The DB has already been migrated, this script will now exit."); - System.exit(status); - } - ItemCassandraDao itemCassandraDao = new ItemCassandraDao(); - VersionCassandraDao versionCassandraDao = new VersionCassandraDao(); - SessionContext context = new SessionContext(); - context.setUser(new UserInfo(GLOBAL_USER)); - context.setTenant("dox"); - printMessage(logger, "Starting migration.\n"); - Instant startTime = Instant.now(); - - migrateToZusammen(cassandraElementRepository, itemCassandraDao, versionCassandraDao, context); - - Instant stopTime = Instant.now(); - Duration duration = Duration.between(startTime, stopTime); - long minutesPart = duration.toMinutes(); - long secondsPart = duration.minusMinutes(minutesPart).getSeconds(); - - if (status == 0) { - MigrationMarker.markMigrated(); - } - printMessage(logger, - "Migration finished . Total run time was : " + minutesPart + ":" + secondsPart - + " minutes"); - System.exit(status); - } - - - private static void migrateToZusammen(CassandraElementRepository cassandraElementRepository, - ItemCassandraDao itemCassandraDao, - VersionCassandraDao versionCassandraDao, - SessionContext context) { - loadVersionInfo(); - - - try { - convertVsp(context, itemCassandraDao, versionCassandraDao, cassandraElementRepository); - printMessage(logger, "Converted VSPs\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - - try { - convertOrchestrationTemplateCandidate(context, cassandraElementRepository); - printMessage(logger, "Converted OrchestrationTemplateCandidates\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - - - try { - convertComponent(context, cassandraElementRepository); - printMessage(logger, "Converted Components\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - try { - convertNic(context, cassandraElementRepository); - printMessage(logger, "Converted Nics\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - try { - convertNetwork(context, cassandraElementRepository); - printMessage(logger, "Converted Networks\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - try { - convertMibs(context, cassandraElementRepository); - printMessage(logger, "Converted MIBs\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - try { - convertServiceArtifact(context, cassandraElementRepository); - printMessage(logger, "Converted Service Artifacts\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - try { - convertServiceTemplate(context, cassandraElementRepository); - printMessage(logger, "Converted Service Templates\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - try { - convertProcesses(context, cassandraElementRepository); - printMessage(logger, "Converted Processes\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - - - try { - convertVlm(context, itemCassandraDao, versionCassandraDao, cassandraElementRepository); - printMessage(logger, "Converted VLMs\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - try { - convertLKG(context, cassandraElementRepository); - printMessage(logger, "Converted LKGs\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - try { - convertFeatureGroup(context, cassandraElementRepository); - printMessage(logger, "Converted Feature Groups\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - try { - convertEP(context, cassandraElementRepository); - printMessage(logger, "Converted EPs\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - try { - convertLicenseAgreement(context, cassandraElementRepository); - printMessage(logger, "Converted License Agreements\n"); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - status = -1; - } - } - - private static void convertOrchestrationTemplateCandidate(SessionContext context, - CassandraElementRepository cassandraElementRepository) { - OrchestrationTemplateCandidateCassandraLoader orchestrationTemplateCandidateCassandraLoader = - new OrchestrationTemplateCandidateCassandraLoader(); - - orchestrationTemplateCandidateCassandraLoader.list().stream() - .filter(entity -> needMigration(entity.getId(), entity.getVersion()) && - entity.getContentData()!=null && entity.getFilesDataStructure()!=null) - .forEach(entity -> ElementHandler - .save(context, cassandraElementRepository, entity.getId(), entity.getVersion(), - OrchestrationTemplateCandidateConvertor - .convertOrchestrationTemplateCandidateToElement(entity))); - } - - private static void loadVersionInfo() { - - VersionInfoCassandraLoader versionInfoCassandraLoader = new VersionInfoCassandraLoader(); - Collection versions = - versionInfoCassandraLoader.list(); - - versions.forEach(versionInfoEntity -> versionInfoMap.put(versionInfoEntity.getEntityId - (), versionInfoEntity)); - - - } - - private static void convertMibs(SessionContext context, - CassandraElementRepository cassandraElementRepository) { - MibCassandraLoader cassandraLoader = new MibCassandraLoader(); - Collection mibs = cassandraLoader.list(); - mibs.stream().filter(mibEntity -> needMigration(mibEntity.getVspId(), mibEntity.getVersion())) - .forEach - (mibEntity -> { - ElementHandler.save(context, cassandraElementRepository, - mibEntity - .getVspId(), mibEntity.getVersion(), - MibConvertor.convertMibToElement - (mibEntity)); - }); - } - - private static void convertProcesses(SessionContext context, - CassandraElementRepository cassandraElementRepository) { - ProcessCassandraLoader cassandraLoader = new ProcessCassandraLoader(); - Collection processes = cassandraLoader.list(); - processes.stream() - .filter(processEntity -> needMigration(processEntity.getVspId(), processEntity.getVersion - ())).forEach(processEntity -> { - ElementHandler.save( - context, - cassandraElementRepository, - processEntity - .getId(), processEntity.getVersion(), - ProcessConvertor.convertProcessToElement(processEntity)); - }); - } - - private static void convertVsp(SessionContext context, ItemCassandraDao itemCassandraDao, - VersionCassandraDao versionCassandraDao, - CassandraElementRepository cassandraElementRepository) { - VendorSoftwareProductInfoLoader vendorSoftwareProductInfoLoader = new - VendorSoftwareProductInfoLoader(); - Collection vsps = - vendorSoftwareProductInfoLoader.list(); - vsps.stream().filter(vspInformation -> needMigration(vspInformation.getId(), - vspInformation.getVersion())).forEach - (vspInformation - -> - ItemHandler.save(context, - itemCassandraDao, - versionCassandraDao, - vspInformation.getId(), vspInformation - .getVersion(), - VspInformationConvertor - .getVspInfo - (vspInformation), - VspInformationConvertor.getItemVersionData(vspInformation), - vspInformation.getWritetimeMicroSeconds())); - - vsps.stream().filter(vspInformation -> needMigration(vspInformation.getId(), - vspInformation.getVersion())) - .forEach(vspInformation -> ElementHandler.save(context, cassandraElementRepository, - vspInformation.getId(), vspInformation.getVersion(), - VspInformationConvertor.convertVspToElement - (vspInformation))); - } - - private static void convertVlm(SessionContext context, ItemCassandraDao itemCassandraDao, - VersionCassandraDao versionCassandraDao, - CassandraElementRepository cassandraElementRepository) { - VendorLicenseModelCassandraLoader - vendorLicenseModelCassandraDao = new VendorLicenseModelCassandraLoader(); - Collection vlms = - vendorLicenseModelCassandraDao.list(); - vlms.stream().filter(vlm -> needMigration(vlm.getId(), vlm.getVersion())).forEach(vlmEntity -> - ItemHandler.save - (context, itemCassandraDao, - versionCassandraDao, - vlmEntity.getId(), vlmEntity.getVersion(), - VlmConvertor.getVlmInfo - (vlmEntity), - VlmConvertor.getItemVersionData(vlmEntity), new Date().getTime())); - vlms.stream().filter(vlm -> needMigration(vlm.getId(), vlm.getVersion())) - .forEach(vlmEntity -> ElementHandler.save(context, cassandraElementRepository, - vlmEntity.getId(), vlmEntity.getVersion(), - VlmConvertor.convertVlmToElement - (vlmEntity))); - - } - - private static void convertNic(SessionContext context, - CassandraElementRepository cassandraElementRepository) { - NicCassandraLoader nicCassandraLoader = new NicCassandraLoader(); - Collection nics = nicCassandraLoader.list(); - nics.stream().filter(entity -> needMigration(entity.getVspId(), entity.getVersion - ())).forEach(nicEntity -> ElementHandler.save(context, cassandraElementRepository, - nicEntity.getVspId(), nicEntity.getVersion(), NicConvertor.convertNicToElement - (nicEntity))); - - } - - private static void convertNetwork(SessionContext context, - CassandraElementRepository cassandraElementRepository) { - NetworkCassandraLoader networkCassandraLoader = new NetworkCassandraLoader(); - Collection networks = networkCassandraLoader.list(); - networks.stream().filter(entity -> needMigration(entity.getVspId(), entity.getVersion - ())).forEach(networkEntity -> ElementHandler.save(context, cassandraElementRepository, - networkEntity.getVspId(), networkEntity.getVersion(), NetworkConvertor - .convertNetworkToElement(networkEntity))); - - } - - private static void convertComponent(SessionContext context, - CassandraElementRepository cassandraElementRepository) { - ComponentCassandraLoader componentCassandraLoader = new ComponentCassandraLoader(); - Collection components = componentCassandraLoader.list(); - components.stream().filter(entity -> needMigration(entity.getVspId(), entity.getVersion - ())).forEach(componentEntity -> ElementHandler.save(context, cassandraElementRepository, - componentEntity - .getVspId(), componentEntity.getVersion(), ComponentConvertor - .convertComponentToElement(componentEntity))); - - } - - private static void convertServiceArtifact(SessionContext context, - CassandraElementRepository cassandraElementRepository) { - ServiceArtifactCassandraLoader serviceArtifactCassandraLoader = - new ServiceArtifactCassandraLoader(); - Collection serviceArtifacts = serviceArtifactCassandraLoader.list(); - serviceArtifacts.stream().filter(entity -> needMigration(entity.getVspId(), entity.getVersion - ())).forEach(serviceArtifact -> ElementHandler.save(context, - cassandraElementRepository, - serviceArtifact - .getVspId(), serviceArtifact.getVersion(), - VspServiceArtifactConvertor - .convertServiceArtifactToElement(serviceArtifact))); - - } - - private static void convertServiceTemplate(SessionContext context, - CassandraElementRepository cassandraElementRepository) { - ServiceTemplateCassandraLoader serviceTemplateCassandraLoader = - new ServiceTemplateCassandraLoader(); - Collection serviceTemplates = serviceTemplateCassandraLoader.list(); - serviceTemplates.stream().filter(entity -> needMigration(entity.getVspId(), entity.getVersion - ())).forEach(serviceTemplate -> ElementHandler.save(context, - cassandraElementRepository, - serviceTemplate - .getVspId(), serviceTemplate.getVersion(), - VspServiceTemplateConvertor - .convertServiceTemplateToElement(serviceTemplate))); - - } - - private static void convertLKG(SessionContext context, - CassandraElementRepository cassandraElementRepository) { - LKGCassandraLoader LKGCassandraLoader = new LKGCassandraLoader(); - Collection lkgs = LKGCassandraLoader.list(); - lkgs.stream().filter(entity -> needMigration(entity.getVendorLicenseModelId(), entity.getVersion - ())) - .forEach(licenseKeyGroupEntity -> ElementHandler.save(context, cassandraElementRepository, - licenseKeyGroupEntity - .getVendorLicenseModelId(), licenseKeyGroupEntity.getVersion(), - LKGConvertor.convertLKGToElement - (licenseKeyGroupEntity))); - } - - private static void convertEP(SessionContext context, - CassandraElementRepository cassandraElementRepository) { - EntitlementPoolCassandraLoader entitlementPoolCassandraLoader = - new EntitlementPoolCassandraLoader(); - Collection entitlementPools = entitlementPoolCassandraLoader.list(); - entitlementPools.stream() - .filter(entity -> needMigration(entity.getVendorLicenseModelId(), entity.getVersion - ())) - .forEach(entitlementPoolEntity -> ElementHandler.save(context, cassandraElementRepository, - entitlementPoolEntity - .getVendorLicenseModelId(), entitlementPoolEntity.getVersion(), - EntitlementPoolConvertor.convertEntitlementPoolToElement(entitlementPoolEntity))); - } - - private static void convertFeatureGroup(SessionContext context, - CassandraElementRepository cassandraElementRepository) { - FeatureGroupCassandraLoader featureGroupCassandraLoader = new FeatureGroupCassandraLoader(); - Collection featureGroupEntities = featureGroupCassandraLoader.list(); - featureGroupEntities.stream() - .filter(entity -> needMigration(entity.getVendorLicenseModelId(), entity.getVersion - ())) - .forEach(featureGroupEntity -> ElementHandler.save(context, cassandraElementRepository, - featureGroupEntity - .getVendorLicenseModelId(), featureGroupEntity.getVersion(), - FeatureGroupConvertor.convertFeatureGroupToElement(featureGroupEntity))); - } - - private static void convertLicenseAgreement(SessionContext context, - CassandraElementRepository cassandraElementRepository) { - LicenseAgreementCassandraLoader licenseAgreementCassandraLoader = - new LicenseAgreementCassandraLoader(); - Collection licenseAgreementEntities = - licenseAgreementCassandraLoader.list(); - licenseAgreementEntities.stream() - .filter(entity -> needMigration(entity.getVendorLicenseModelId(), entity.getVersion - ())) - .forEach(licenseAgreementEntity -> ElementHandler.save(context, cassandraElementRepository, - licenseAgreementEntity - .getVendorLicenseModelId(), licenseAgreementEntity.getVersion(), - LicenseAgreementConvertor.convertLicenseAgreementToElement(licenseAgreementEntity))); - } - - - private static boolean needMigration(String itemId, Version versionId) { - - VersionInfoEntity versionInfo = - MigrationMain.versionInfoMap.get(itemId); - if (versionInfo == null) { - printMessage(logger, "ItemId: " + itemId + " is not in version_info table."); - return false; - } - return (versionInfo.getCandidate() != null && versionId.equals(versionInfo.getCandidate() - .getVersion())) - || (versionInfo - .getViewableVersions() != null && versionInfo - .getViewableVersions().contains(versionId)); - } - - public static Map getVersionInfoMap() - { - return versionInfoMap; - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/ComponentConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/ComponentConvertor.java deleted file mode 100644 index fb597d5a3e..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/ComponentConvertor.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.MigrationMain; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ElementPropertyName; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ElementType; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.StructureElement; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * @author katyr - * @since April 23, 2017 - */ - -public class ComponentConvertor { - - private static Set componentsLoaded = new HashSet<>(); - private static Logger logger = LoggerFactory.getLogger(MigrationMain.class); - - public static CollaborationElement[] convertComponentToElement(ComponentEntity componentEntity) { - - CollaborationElement[] componentElements; - List componentNamespace = getComponentNamespace(); - - int index = 0; - String componentsEntityId = StructureElement.Components.name(); - String uniqueId = componentEntity.getVspId()+"_"+componentEntity.getVersion().toString(); - if (componentsLoaded.contains(uniqueId)) { -// printMessage(logger, "Components structural elements exist for component " + -// componentEntity.getId()); - componentElements = new CollaborationElement[2]; - } else { - componentsLoaded.add(uniqueId); -// printMessage(logger, "Creating Components structural elements for component " + -// componentEntity.getId()); - componentElements = new CollaborationElement[3]; - componentElements[index] = ElementHandler.getElementEntity( - componentEntity.getVspId(), componentEntity.getVersion().toString(), componentsEntityId, - componentNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.Components.name()), - null, - null, - null); - index++; - } - - componentNamespace.add(componentsEntityId); - componentElements[index] = ElementHandler.getElementEntity( - componentEntity.getVspId(), componentEntity.getVersion().toString(), - componentEntity.getId(), - componentNamespace, - getComponentInfo(componentEntity), - null, - null, - (componentEntity.getCompositionData() != null) ? componentEntity.getCompositionData().getBytes() - : null); - index++; - - componentNamespace.add(componentEntity.getId()); - componentElements[index] = ElementHandler.getElementEntity( - componentEntity.getVspId(), componentEntity.getVersion().toString(),StructureElement.Questionnaire.name() + "_" + componentEntity.getId(), - componentNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.Questionnaire.name()), - null, - null, - (componentEntity.getQuestionnaireData() != null) ? componentEntity.getQuestionnaireData().getBytes() - : null); - - return componentElements; - } - - private static Info getComponentInfo(ComponentEntity componentEntity) { - Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.Component); - info.addProperty(ElementPropertyName.compositionData.name(), - componentEntity.getCompositionData()); - - return info; - } - - private static List getComponentNamespace() { - return ElementHandler.getElementPath(); - } - - public static ElementEntityContext convertComponentToElementContext( - ComponentEntity componentEntity) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(componentEntity.getVspId(), componentEntity.getVersion().toString())); - } - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/EntitlementPoolConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/EntitlementPoolConvertor.java deleted file mode 100644 index 86faf15837..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/EntitlementPoolConvertor.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.RelationType; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.StructureElement; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.VlmZusammenUtil; -import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * Created by ayalaben on 4/24/2017 - */ -public class EntitlementPoolConvertor { - - private static Set EntitlementPoolsLoaded = new HashSet<>(); - - public static ElementEntityContext convertEntitlementPoolToElementContext( - EntitlementPoolEntity entitlementPoolEntity) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(entitlementPoolEntity.getVendorLicenseModelId(), - entitlementPoolEntity.getVersion().toString())); - } - - public static CollaborationElement[] convertEntitlementPoolToElement( - EntitlementPoolEntity entitlementPoolEntity) { -// printMessage(logger, "source EntitlementPoolEntity -> " + entitlementPoolEntity.toString()); - CollaborationElement[] elements; - List entitlementPoolNamespace = getEntitlementPoolNamespace(entitlementPoolEntity); - - int index = 0; - String entitlememtPoolsEntityId = StructureElement.EntitlementPools.name(); - String uniqueId = entitlementPoolEntity.getVendorLicenseModelId() + "_" + - entitlementPoolEntity.getVersion().toString(); - - if (EntitlementPoolsLoaded.contains(uniqueId)) { - elements = new CollaborationElement[1]; - } else { - EntitlementPoolsLoaded.add(uniqueId); - elements = new CollaborationElement[2]; - elements[index] = ElementHandler.getElementEntity( - entitlementPoolEntity.getVendorLicenseModelId(), - entitlementPoolEntity.getVersion().toString(), - entitlememtPoolsEntityId, entitlementPoolNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.EntitlementPools.name()), - null, null, null); - index++; - } - - entitlementPoolNamespace.add(entitlememtPoolsEntityId); - - elements[index] = ElementHandler.getElementEntity( - entitlementPoolEntity.getVendorLicenseModelId(), - entitlementPoolEntity.getVersion().toString(), - entitlementPoolEntity.getId(), entitlementPoolNamespace, - getEntitelementPoolInfo(entitlementPoolEntity), - entitlementPoolEntity.getReferencingFeatureGroups().stream().map(rel -> - VlmZusammenUtil - .createRelation( RelationType.EntitlmentPoolToReferencingFeatureGroup, rel)) - .collect(Collectors.toList()), null, null); - - return elements; - } - - private static Info getEntitelementPoolInfo(EntitlementPoolEntity entitlementPool) { - - Info info = new Info(); - info.setName(entitlementPool.getName()); - info.setDescription(entitlementPool.getDescription()); - info.addProperty("thresholdValue", entitlementPool.getThresholdValue()); - info.addProperty("threshold_unit", entitlementPool.getThresholdUnit()); - //info.addProperty("entitlement_metric", entitlementPool.getEntitlementMetric()); - info.addProperty("increments", entitlementPool.getIncrements()); - info.addProperty("operational_scope", entitlementPool.getOperationalScope()); - - return info; - } - - private static List getEntitlementPoolNamespace( - EntitlementPoolEntity entitlementPoolEntity) { - return ElementHandler.getElementPath(""); - } - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/FeatureGroupConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/FeatureGroupConvertor.java deleted file mode 100644 index eac5ce64ea..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/FeatureGroupConvertor.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.Relation; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.RelationType; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.StructureElement; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.VlmZusammenUtil; -import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; - -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; - -/** - * Created by ayalaben on 4/25/2017 - */ -public class FeatureGroupConvertor { - - private static Logger logger = LoggerFactory.getLogger(FeatureGroupConvertor.class); - private static Set FeatureGroupsLoaded = new HashSet<>(); - - public static ElementEntityContext convertFeatureGroupToElementContext(FeatureGroupEntity featureGroupEntity) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(featureGroupEntity.getVendorLicenseModelId(), featureGroupEntity.getVersion().toString())); - } - - public static CollaborationElement[] convertFeatureGroupToElement(FeatureGroupEntity featureGroupEntity) { -// printMessage(logger, "source FeatureGroupEntity -> " + featureGroupEntity.toString()); - CollaborationElement[] elements; - List featureGroupNamespace = getFeatureGroupNamespace(featureGroupEntity); - - int index = 0; - String featureGroupsEntityId = StructureElement.FeatureGroups.name(); - String uniqueId = featureGroupEntity.getVendorLicenseModelId() + "_" + featureGroupEntity.getVersion().toString(); - - if (FeatureGroupsLoaded.contains(uniqueId)) { - elements = new CollaborationElement[1]; - } else { - FeatureGroupsLoaded.add(uniqueId); - elements = new CollaborationElement[2]; - elements[index] = ElementHandler.getElementEntity( - featureGroupEntity.getVendorLicenseModelId(), featureGroupEntity.getVersion().toString(), - featureGroupsEntityId, featureGroupNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.FeatureGroups.name()), - null, null, null); - index++; - } - - featureGroupNamespace.add(featureGroupsEntityId); - - elements[index] = ElementHandler.getElementEntity( - featureGroupEntity.getVendorLicenseModelId(), featureGroupEntity.getVersion().toString(), - featureGroupEntity.getId(), featureGroupNamespace, getFeatureGroupInfo(featureGroupEntity), - getAllFeatureGroupRelations(featureGroupEntity), null, null); - - return elements; - } - - private static Collection getAllFeatureGroupRelations(FeatureGroupEntity featureGroup) { - Collection relations = new ArrayList<>(); - - relations.addAll(featureGroup.getEntitlementPoolIds().stream().map(rel -> - VlmZusammenUtil.createRelation( RelationType.FeatureGroupToEntitlmentPool, rel)) - .collect(Collectors.toList())); - - relations.addAll(featureGroup.getLicenseKeyGroupIds().stream().map(rel -> - VlmZusammenUtil.createRelation( RelationType.FeatureGroupToLicenseKeyGroup, rel)) - .collect(Collectors.toList())); - - relations.addAll(featureGroup.getReferencingLicenseAgreements().stream().map(rel -> - VlmZusammenUtil.createRelation( RelationType.FeatureGroupToReferencingLicenseAgreement, - rel)).collect(Collectors.toList())); - - return relations; - } - - private static Info getFeatureGroupInfo(FeatureGroupEntity featureGroup) { - - Info info = new Info(); - info.setName(featureGroup.getName()); - info.setDescription(featureGroup.getDescription()); - info.addProperty("partNumber", featureGroup.getPartNumber()); - info.addProperty("manufacturerReferenceNumber", featureGroup.getManufacturerReferenceNumber()); - - return info; - } - - - private static List getFeatureGroupNamespace(FeatureGroupEntity featureGroupEntity) { - return ElementHandler.getElementPath(""); - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/LKGConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/LKGConvertor.java deleted file mode 100644 index 7fd640b12d..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/LKGConvertor.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.RelationType; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.StructureElement; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.VlmZusammenUtil; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * Created by ayalaben on 4/24/2017 - */ -public class LKGConvertor { - - private static Logger logger = LoggerFactory.getLogger(LKGConvertor.class); - private static Set compLKGLoaded = new HashSet<>(); - - public static CollaborationElement[] convertLKGToElement(LicenseKeyGroupEntity licenseKeyGroupEntity) { - CollaborationElement[] elements; - List lkgNamespace = getLKGNamespace(licenseKeyGroupEntity); - - int index = 0; - String lkgsEntityId = StructureElement.LicenseKeyGroups.name(); - String uniqueId = licenseKeyGroupEntity.getVendorLicenseModelId() + "_" + licenseKeyGroupEntity.getVersion().toString(); - - if (compLKGLoaded.contains(uniqueId)) { - elements = new CollaborationElement[1]; - } else { - compLKGLoaded.add(uniqueId); - elements = new CollaborationElement[2]; - elements[index] = ElementHandler.getElementEntity( - licenseKeyGroupEntity.getVendorLicenseModelId(), licenseKeyGroupEntity.getVersion().toString(), lkgsEntityId, lkgNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.LicenseKeyGroups.name()), null, null, null); - index++; - } - - lkgNamespace.add(lkgsEntityId); - - elements[index] = ElementHandler.getElementEntity( - licenseKeyGroupEntity.getVendorLicenseModelId(), licenseKeyGroupEntity.getVersion().toString(), licenseKeyGroupEntity.getId(), lkgNamespace, - getLKGInfo(licenseKeyGroupEntity), licenseKeyGroupEntity.getReferencingFeatureGroups().stream().map(rel -> - VlmZusammenUtil.createRelation( RelationType.LicenseKeyGroupToReferencingFeatureGroup, rel)) - .collect(Collectors.toList()), null, null); - - return elements; - } - - private static Info getLKGInfo(LicenseKeyGroupEntity licenseKeyGroupEntity) { - - Info info = new Info(); - info.setName(licenseKeyGroupEntity.getName()); - info.setDescription(licenseKeyGroupEntity.getDescription()); - info.addProperty("LicenseKeyType", licenseKeyGroupEntity.getType()); - info.addProperty("operational_scope", licenseKeyGroupEntity.getOperationalScope()); - - return info; - } - - private static List getLKGNamespace(LicenseKeyGroupEntity LKGEntity) { - return ElementHandler.getElementPath(""); - } - - public static ElementEntityContext convertLKGToElementContext(LicenseKeyGroupEntity licenseKeyGroupEntity) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(licenseKeyGroupEntity.getVendorLicenseModelId(), licenseKeyGroupEntity.getVersion().toString())); - } - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/LicenseAgreementConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/LicenseAgreementConvertor.java deleted file mode 100644 index 25564c3138..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/LicenseAgreementConvertor.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.RelationType; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.StructureElement; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.VlmZusammenUtil; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * Created by ayalaben on 4/25/2017 - */ -public class LicenseAgreementConvertor { - - private static Logger logger = LoggerFactory.getLogger(LicenseAgreementConvertor.class); - private static Set LicenseAgreementsLoaded = new HashSet<>(); - - public static ElementEntityContext convertLicenseAgreementToElementContext(LicenseAgreementEntity licenseAgreementEntity) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(licenseAgreementEntity.getVendorLicenseModelId(), licenseAgreementEntity.getVersion().toString())); - } - - - public static CollaborationElement[] convertLicenseAgreementToElement(LicenseAgreementEntity licenseAgreementEntity) { -// printMessage(logger, "source LicenseAgreementEntity -> " + licenseAgreementEntity.toString()); - CollaborationElement[] elements; - List featureGroupNamespace = getLicenseAgreementNamespace(licenseAgreementEntity); - - int index = 0; - String featureGroupsEntityId = StructureElement.LicenseAgreements.name(); - String uniqueId = licenseAgreementEntity.getVendorLicenseModelId() + "_" + licenseAgreementEntity.getVersion().toString(); - - if (LicenseAgreementsLoaded.contains(uniqueId)) { - elements = new CollaborationElement[1]; - } else { - LicenseAgreementsLoaded.add(uniqueId); - elements = new CollaborationElement[2]; - elements[index] = ElementHandler.getElementEntity( - licenseAgreementEntity.getVendorLicenseModelId(), licenseAgreementEntity.getVersion().toString(), - featureGroupsEntityId, featureGroupNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.LicenseAgreements.name()), - null, null, null); - index++; - } - - featureGroupNamespace.add(featureGroupsEntityId); - - elements[index] = ElementHandler.getElementEntity( - licenseAgreementEntity.getVendorLicenseModelId(), licenseAgreementEntity.getVersion().toString(), - licenseAgreementEntity.getId(), featureGroupNamespace, getLicenseAgreementInfo(licenseAgreementEntity), - licenseAgreementEntity.getFeatureGroupIds().stream().map(rel -> - VlmZusammenUtil.createRelation( RelationType.LicenseAgreementToFeatureGroup, rel)) - .collect(Collectors.toList()), null, null); - - return elements; - } - - private static Info getLicenseAgreementInfo(LicenseAgreementEntity licenseAgreement) { - - Info info = new Info(); - info.setName(licenseAgreement.getName()); - info.setDescription(licenseAgreement.getDescription()); - info.addProperty("licenseTerm", licenseAgreement.getLicenseTerm()); - info.addProperty("requirementsAndConstrains", licenseAgreement.getRequirementsAndConstrains()); - - return info; - } - - private static List getLicenseAgreementNamespace(LicenseAgreementEntity licenseAgreement) { - return ElementHandler.getElementPath(""); - } - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/MibConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/MibConvertor.java deleted file mode 100644 index f145e51f02..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/MibConvertor.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.MigrationMain; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.StructureElement; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class MibConvertor { - private static Logger logger = LoggerFactory.getLogger(MigrationMain.class); - - private static Set compMibLoaded = new HashSet<>(); - - - public static CollaborationElement[] convertMibToElement( - ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - CollaborationElement[] elements; - List mibNamespace = getMibNamespace(componentMonitoringUploadEntity); - - int index = 0; - String mibsEntityId = - StructureElement.Mibs.name() + "_" + componentMonitoringUploadEntity.getComponentId(); - if (compMibLoaded.contains(mibsEntityId)) { - elements = new CollaborationElement[1]; - } else { - compMibLoaded.add(mibsEntityId); - elements = new CollaborationElement[2]; - elements[index++] = ElementHandler.getElementEntity( - componentMonitoringUploadEntity.getVspId(), - componentMonitoringUploadEntity.getVersion().toString(), mibsEntityId, mibNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.Mibs.name()), null, null, null); - } - - mibNamespace.add(mibsEntityId); - elements[index] = ElementHandler.getElementEntity( - componentMonitoringUploadEntity.getVspId(), - componentMonitoringUploadEntity.getVersion().toString(), componentMonitoringUploadEntity - .getId(), mibNamespace, - getMibInfo(componentMonitoringUploadEntity), null, null, componentMonitoringUploadEntity - .getArtifact().array()); - - return elements; - } - - private static Info getMibInfo( - ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - Info info = new Info(); - info.setName(componentMonitoringUploadEntity.getType().toString()); - info.getProperties().put("name", componentMonitoringUploadEntity.getArtifactName()); - return info; - } - - private static List getMibNamespace( - ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - return ElementHandler - .getElementPath(StructureElement.Components.name(), componentMonitoringUploadEntity - .getComponentId()); - } - - public static ElementEntityContext convertMibToElementContext( - ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(componentMonitoringUploadEntity.getVspId(), - componentMonitoringUploadEntity - .getVersion().toString())); - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/NetworkConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/NetworkConvertor.java deleted file mode 100644 index 3d4f1575fc..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/NetworkConvertor.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.MigrationMain; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ElementPropertyName; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ElementType; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.StructureElement; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * @author katyr - * @since April 23, 2017 - */ - -public class NetworkConvertor { - - private static Set networksLoaded = new HashSet<>(); - private static Logger logger = LoggerFactory.getLogger(MigrationMain.class); - - - - public static CollaborationElement[] convertNetworkToElement(NetworkEntity networkEntity) { - - CollaborationElement[] networkElements; - List networkNamespace = getNetworkNamespace(); - - int index = 0; - String networksEntityId = StructureElement.Networks.name(); - String uniqueId = networkEntity.getVspId()+"_"+networkEntity.getVersion().toString(); - if (networksLoaded.contains(uniqueId)) { -// printMessage(logger, "Networks structural elements exist for network " + -// networkEntity.getId()); - networkElements = new CollaborationElement[1]; - } else { -// printMessage(logger, "Creating Networks structural element for network " + -// networkEntity.getId()); - networksLoaded.add(uniqueId); - networkElements = new CollaborationElement[2]; - networkElements[index] = ElementHandler.getElementEntity( - networkEntity.getVspId(), networkEntity.getVersion().toString(), networksEntityId, - networkNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.Networks.name()), - null, - null, - null); - index++; - } - - networkNamespace.add(networksEntityId); - - networkElements[index] = ElementHandler.getElementEntity( - networkEntity.getVspId(), networkEntity.getVersion().toString(), networkEntity.getId(), - networkNamespace, - getNetworkInfo(networkEntity), - null, - null, - networkEntity.getCompositionData().getBytes()); - - - return networkElements; - } - - private static Info getNetworkInfo(NetworkEntity networkEntity) { - Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.Network); - info.addProperty(ElementPropertyName.compositionData.name(), networkEntity.getCompositionData()); - - return info; - } - - private static List getNetworkNamespace() { - return ElementHandler.getElementPath(); - } - - public static ElementEntityContext convertNetworkToElementContext(NetworkEntity networkEntity) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(networkEntity.getVspId(), networkEntity.getVersion().toString())); - } - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/NicConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/NicConvertor.java deleted file mode 100644 index b17e68c0e5..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/NicConvertor.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.MigrationMain; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ElementPropertyName; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ElementType; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.StructureElement; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class NicConvertor { - - - private static Set compNicLoaded = new HashSet<>(); - private static Logger logger = LoggerFactory.getLogger(MigrationMain.class); - - - - public static CollaborationElement[] convertNicToElement(NicEntity nicEntity) { - - CollaborationElement[] nicElements; - List nicNamespace = getNicNamespace(nicEntity); - - int index = 0; - String nicsEntityId = StructureElement.Nics.name() + "_" + nicEntity.getComponentId(); - if (compNicLoaded.contains(nicsEntityId)) { -// printMessage(logger, "Nics structural element exists for nic " + -// nicEntity.getId()); - nicElements = new CollaborationElement[2]; - } else { -// printMessage(logger, "Creating Nics structural element for nic " + -// nicEntity.getId()); - compNicLoaded.add(nicsEntityId); - nicElements = new CollaborationElement[3]; - nicElements[index] = ElementHandler.getElementEntity( - nicEntity.getVspId(), nicEntity.getVersion().toString(), nicsEntityId, - nicNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.Nics.name()), - null, - null, - null); - index++; - } - - nicNamespace.add(nicsEntityId); - nicElements[index] = ElementHandler.getElementEntity( - nicEntity.getVspId(), nicEntity.getVersion().toString(), nicEntity.getId(), - nicNamespace, - getNicInfo(nicEntity), - null, - null, - nicEntity.getCompositionData().getBytes()); - index++; - - nicNamespace.add(nicEntity.getId()); - nicElements[index] = ElementHandler.getElementEntity( - nicEntity.getVspId(), nicEntity.getVersion().toString(),StructureElement.Questionnaire.name() + "_" + nicEntity.getId(), - nicNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.Questionnaire.name()), - null, - null, - (nicEntity.getQuestionnaireData() != null) ? nicEntity.getQuestionnaireData().getBytes() - : null); - return nicElements; - } - - private static Info getNicInfo(NicEntity nicEntity) { - Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.Nic); - info.addProperty(ElementPropertyName.compositionData.name(), nicEntity.getCompositionData()); - return info; - } - - private static List getNicNamespace(NicEntity nicEntity) { - return ElementHandler.getElementPath(StructureElement.Components.name(), nicEntity - .getComponentId()); - } - - public static ElementEntityContext convertNicToElementContext(NicEntity nicEntity) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(nicEntity.getVspId(), nicEntity.getVersion().toString())); - } - - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/OrchestrationTemplateCandidateConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/OrchestrationTemplateCandidateConvertor.java deleted file mode 100644 index e6ceb360bd..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/OrchestrationTemplateCandidateConvertor.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.MigrationMain; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.StructureElement; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateDataEntity; - -import java.util.List; - -public class OrchestrationTemplateCandidateConvertor { - - - - - private static Logger logger = LoggerFactory.getLogger(MigrationMain.class); - - public static CollaborationElement[] convertOrchestrationTemplateCandidateToElement( - OrchestrationTemplateCandidateDataEntity entity) { - - - CollaborationElement[] orchestrationTemplateCandidateElements = new CollaborationElement[2]; - List orchestrationTemplateCandidateNamespace = - getOrchestrationTemplateCandidateNamespace(); - - - - orchestrationTemplateCandidateElements[0] = ElementHandler.getElementEntity( - entity.getId(), entity.getVersion().toString(), StructureElement.OrchestrationTemplateCandidate.name(), - orchestrationTemplateCandidateNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.OrchestrationTemplateCandidate.name()), - null, - null, - entity.getFilesDataStructure().getBytes()); - - orchestrationTemplateCandidateNamespace.add(StructureElement.OrchestrationTemplateCandidate.name()); - orchestrationTemplateCandidateElements[1] = ElementHandler.getElementEntity( - entity.getId(), entity.getVersion().toString(), StructureElement.OrchestrationTemplateCandidateContent.name(), - orchestrationTemplateCandidateNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.OrchestrationTemplateCandidateContent.name()), - null, - null, - entity.getContentData().array()); - - - - return orchestrationTemplateCandidateElements; - } - - - private static List getOrchestrationTemplateCandidateNamespace() { - return ElementHandler.getElementPath(); - } - - public static ElementEntityContext convertComponentToElementContext( - ComponentEntity componentEntity) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(componentEntity.getVspId(), componentEntity.getVersion().toString())); - } - - - - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/ProcessConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/ProcessConvertor.java deleted file mode 100644 index 0a145c49f7..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/ProcessConvertor.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.MigrationMain; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ElementType; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.StructureElement; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class ProcessConvertor { - private static final String NAME = "name"; - private static final String ELEMENT_TYPE = "type"; - private static final String ARTIFACT_NAME = "artifactName"; - private static final String DESCRIPTION = "description"; - private static final String PROCESS_TYPE = "processType"; - private static Set compProcessesLoaded = new HashSet<>(); - - private static Logger logger = LoggerFactory.getLogger(MigrationMain.class); - - - public static CollaborationElement[] convertProcessToElement(ProcessEntity processEntity) { - CollaborationElement[] elements; - boolean isGeneralComponentId = isGeneralComponentId(processEntity); - List processNamespace = getProcessNamespace(processEntity); - int index = 0; - String uniqueId = getUniqueId(processEntity, isGeneralComponentId); - String processesEntityId = isGeneralComponentId ? StructureElement.Processes.name() : - (StructureElement.Processes.name() + "_" +processEntity.getComponentId()); - if (compProcessesLoaded.contains(uniqueId)) { - elements = new CollaborationElement[1]; - } else { - compProcessesLoaded.add(uniqueId); - elements = new CollaborationElement[2]; - elements[index++] = ElementHandler.getElementEntity( - processEntity.getVspId(), processEntity.getVersion().toString(), processesEntityId, - processNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.Processes.name()), null, null, null); - } - - processNamespace.add(processesEntityId); - elements[index] = ElementHandler.getElementEntity( - processEntity.getVspId(), processEntity.getVersion().toString(), processEntity.getId(), - processNamespace, - getProcessInfo(processEntity), null, null, processEntity.getArtifact() == - null ? null : processEntity.getArtifact().array()); - - return elements; - } - - private static String getUniqueId(ProcessEntity processEntity, boolean isGeneralComponentId) { - if (isGeneralComponentId) { - return processEntity.getVspId() + "_" + processEntity.getVersion().toString(); - } else { - return StructureElement.Processes.name() + "_" + processEntity - .getComponentId(); - } - } - - private static Info getProcessInfo(ProcessEntity processEntity) { - Info info = new Info(); - info.setName(processEntity.getName()); - info.addProperty(NAME, processEntity.getName()); - info.addProperty(ELEMENT_TYPE, ElementType.Process); - info.addProperty(ARTIFACT_NAME, processEntity.getArtifactName()); - info.addProperty(DESCRIPTION, processEntity.getDescription()); - info.addProperty(PROCESS_TYPE, - processEntity.getType() != null ? processEntity.getType().name() : null); - return info; - } - - private static List getProcessNamespace(ProcessEntity processEntity) { - if (isGeneralComponentId(processEntity)) { - return ElementHandler.getElementPath(); - } else { - return ElementHandler - .getElementPath(StructureElement.Components.name(), processEntity.getComponentId()); - } - } - - private static boolean isGeneralComponentId(ProcessEntity processEntity) { - return processEntity.getComponentId().equals("General"); - } - - public static ElementEntityContext convertProcessToElementContext(ProcessEntity processEntity) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(processEntity.getVspId(), processEntity.getVersion().toString())); - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VlmConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VlmConvertor.java deleted file mode 100644 index 2e483747ed..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VlmConvertor.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.ItemVersionData; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.StructureElement; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class VlmConvertor { - - private static Set compNicLoaded = new HashSet<>(); - - public static CollaborationElement[] convertVlmToElement(VendorLicenseModelEntity vendorLicenseModel) { - - CollaborationElement[] vspElements = new CollaborationElement[1]; - List vspNamespace = getVlmNamespace(vendorLicenseModel); - - - String vspEntityId = StructureElement.General.name(); - - vspElements[0] = ElementHandler.getElementEntity( - vendorLicenseModel.getId(), vendorLicenseModel.getVersion().toString(), - vspEntityId, - vspNamespace, - getVlmGeneralInfo(vendorLicenseModel), - null, - null, - null); - return vspElements; - } - - - public static ItemVersionData getItemVersionData( - VendorLicenseModelEntity vendorLicenseModel) { - ItemVersionData itemVersionData = new ItemVersionData(); - Info info = new Info(); - info.setName("main version"); - itemVersionData.setInfo(info); - return itemVersionData; - } - - public static Info getVlmInfo(VendorLicenseModelEntity vendorLicenseModel) { - - Info info = new Info(); - info.setName(vendorLicenseModel.getVendorName()); - info.setDescription(vendorLicenseModel.getDescription()); - info.addProperty("type", "vlm"); - info.addProperty("version", vendorLicenseModel.getVersion()); - info.addProperty("iconRef", vendorLicenseModel.getIconRef()); - return info; - } - - private static List getVlmNamespace(VendorLicenseModelEntity vlmEntity) { - return ElementHandler.getElementPath(""); - } - - private static Info getVlmGeneralInfo(VendorLicenseModelEntity vendorLicenseModel) { - - - Info info = new Info(); - info.setName(StructureElement.General.name()); - info.addProperty(InfoPropertyName.type.name(), InfoPropertyName.vlm.name()); - info.addProperty(InfoPropertyName.iconRef.name(), vendorLicenseModel.getIconRef()); - info.addProperty(InfoPropertyName.name.name(), vendorLicenseModel.getVendorName()); - info.addProperty(InfoPropertyName.description.name(), vendorLicenseModel.getDescription()); - return info; - } - - public static ElementEntityContext convertVlmToElementContext(VendorLicenseModelEntity - vendorLicenseModel) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(vendorLicenseModel.getId(), vendorLicenseModel.getVersion().toString())); - } - - - private enum InfoPropertyName { - name, - description, - iconRef, - type, - vlm - } - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VspInformationConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VspInformationConvertor.java deleted file mode 100644 index 59fba5f066..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VspInformationConvertor.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.ItemVersionData; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.loaders.VspInformation; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.StructureElement; - -import java.util.List; - -public class VspInformationConvertor { - - public static ItemVersionData getItemVersionData( - VspInformation vspInformation) { - Info info = new Info(); - info.setName("main version"); - ItemVersionData itemVersionData = new ItemVersionData(); - itemVersionData.setInfo(info); - return itemVersionData; - } - - public static Info getVspInfo(VspInformation vspInformation) { - - Info info = new Info(); - info.setName(vspInformation.getName()); - info.setDescription(vspInformation.getDescription()); - info.addProperty("type", "vsp"); - addVspDetailsToInfo(info, vspInformation); - return info; - } - - private static List getVspNamespace(VendorLicenseModelEntity vlmEntity) { - return ElementHandler.getElementPath(""); - } - - private static void addVspDetailsToInfo(Info info, VspInformation vspInformation) { - info.addProperty("name", vspInformation.getName()); - info.addProperty("description", vspInformation.getDescription()); - info.addProperty("category", vspInformation.getCategory()); - info.addProperty("subCategory", vspInformation.getSubCategory()); - info.addProperty("vendorId", vspInformation.getVendorId()); - info.addProperty("vendorName", vspInformation.getVendorName()); - if (vspInformation.getVlmVersion() != null) { - info.addProperty("vendorVersion", vspInformation.getVlmVersion().toString()); - } - info.addProperty("featureGroups", vspInformation.getFeatureGroups()); - info.addProperty("licenseAgreement", vspInformation.getLicenseAgreement()); - String oldVersion = vspInformation.getIsOldVersion() == null? "1702":"1610"; - info.addProperty("oldVersion", oldVersion); - } - - public static CollaborationElement[] convertVspToElement(VspInformation vspInformation) { - - CollaborationElement[] vspElements; - if(vspInformation.getQuestionnaireData() == null){ - vspElements = new CollaborationElement[4]; - }else{ - vspElements = new CollaborationElement[5]; - } - - int index=0; - - List vspNamespace = getVspNamespace(vspInformation); - - - String vspEntityId = StructureElement.General.name(); - - vspElements[index] = ElementHandler.getElementEntity( - vspInformation.getId(), vspInformation.getVersion().toString(), - vspEntityId, - vspNamespace, - getVspGeneralInfo(vspInformation), - null, - null, - null); - - index++; - String vspOrchestrationTemplateEntityId = StructureElement.OrchestrationTemplate.name(); - vspElements[index] = ElementHandler.getElementEntity( - vspInformation.getId(), vspInformation.getVersion().toString(), - vspOrchestrationTemplateEntityId, - vspNamespace, - ElementHandler.getStructuralElementInfo(vspOrchestrationTemplateEntityId), - null, - null, - null); - - if(vspInformation.getQuestionnaireData()!= null) { - index++; - String vspQuestionnaireEntityId = StructureElement.Questionnaire.name(); - vspElements[index] = ElementHandler.getElementEntity( - vspInformation.getId(), vspInformation.getVersion().toString(), - vspQuestionnaireEntityId, - vspNamespace, - ElementHandler.getStructuralElementInfo(vspQuestionnaireEntityId), - null, - null, - vspInformation.getQuestionnaireData().getBytes() != null ? vspInformation - .getQuestionnaireData().getBytes() : null); - } - vspNamespace.add(vspOrchestrationTemplateEntityId); - index++; - String vspOrchestrationTemplateValidationDataEntityId = StructureElement.OrchestrationTemplateValidationData.name(); - vspElements[index] = ElementHandler.getElementEntity( - vspInformation.getId(), vspInformation.getVersion().toString(), - vspOrchestrationTemplateValidationDataEntityId, - vspNamespace, - ElementHandler.getStructuralElementInfo(vspOrchestrationTemplateValidationDataEntityId), - null, - null, - vspInformation.getValidationData()!= null?vspInformation.getValidationData().getBytes() - :null); - index++; - String vspOrchestrationTemplateContentEntityId = StructureElement.OrchestrationTemplateContent.name(); - vspElements[index] = ElementHandler.getElementEntity( - vspInformation.getId(), vspInformation.getVersion().toString(), - vspOrchestrationTemplateContentEntityId, - vspNamespace, - ElementHandler.getStructuralElementInfo(vspOrchestrationTemplateContentEntityId), - null, - null, - vspInformation.getContentData()!= null?vspInformation.getContentData().array() - :null); - - return vspElements; - } - - private static Info getVspGeneralInfo(VspInformation vspInformation) { - - - Info info = new Info(); - info.setName(StructureElement.General.name()); - info.addProperty("name", vspInformation.getName()); - info.addProperty("description", vspInformation.getDescription()); - info.addProperty("category", vspInformation.getCategory()); - info.addProperty("subCategory", vspInformation.getSubCategory()); - info.addProperty("vendorId", vspInformation.getVendorId()); - info.addProperty("vendorName", vspInformation.getVendorName()); - if (vspInformation.getVlmVersion() != null) { - info.addProperty("vendorVersion", vspInformation.getVlmVersion().toString()); - } - info.addProperty("featureGroups", vspInformation.getFeatureGroups()); - info.addProperty("licenseAgreement", vspInformation.getLicenseAgreement()); - String oldVersion = vspInformation.getIsOldVersion() == null? "1702":"1610"; - info.addProperty("oldVersion", oldVersion); - return info; - } - - private static List getVspNamespace(VspInformation vspEntity) { - return ElementHandler.getElementPath(""); - } - - public static ElementEntityContext convertVspToElementContext(VspInformation vspEntity) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(vspEntity.getId(), vspEntity.getVersion().toString())); - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VspServiceArtifactConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VspServiceArtifactConvertor.java deleted file mode 100644 index 15b8ad729a..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VspServiceArtifactConvertor.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.core.model.types.ServiceArtifact; -import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.sdc.model.impl.zusammen.StructureElement; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * @author katyr - * @since April 23, 2017 - */ - -public class VspServiceArtifactConvertor -{ - private static Set serviceArtifactsLoaded = new HashSet<>(); - - - - public static CollaborationElement[] convertServiceArtifactToElement(ServiceArtifact serviceArtifact) { - - CollaborationElement[] serviceArtifactElements; - List serviceArtifactNamespace = getServiceArtifactNamespace(); - - int index = 0; - String serviceArtifactsEntityId = StructureElement.Artifacts.name(); - String uniqueId = serviceArtifact.getVspId()+"_"+serviceArtifact.getVersion().toString(); - if (serviceArtifactsLoaded.contains(uniqueId)) { - serviceArtifactElements = new CollaborationElement[1]; - } else { - serviceArtifactsLoaded.add(uniqueId); - serviceArtifactElements = new CollaborationElement[2]; - serviceArtifactElements[index] = ElementHandler.getElementEntity( - serviceArtifact.getVspId(), serviceArtifact.getVersion().toString(), serviceArtifactsEntityId, - serviceArtifactNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.Artifacts.name()), - null, - null, - null); - index++; - } - - serviceArtifactNamespace.add(serviceArtifactsEntityId); - String elementId = serviceArtifact.getVspId()+"_"+serviceArtifact.getVersion().toString() - +"_"+serviceArtifact.getName(); - serviceArtifactElements[index] = ElementHandler.getElementEntity( - serviceArtifact.getVspId(), serviceArtifact.getVersion().toString(), elementId, - serviceArtifactNamespace, - getServiceArtifactInfo(serviceArtifact), - null, - null, - FileUtils.toByteArray(serviceArtifact.getContent())); - - return serviceArtifactElements; - } - - private static Info getServiceArtifactInfo(ServiceArtifact serviceArtifactEntity) { - Info info = new Info(); - info.setName(serviceArtifactEntity.getName()); - info.addProperty("type", org.openecomp.sdc.model.impl.zusammen.ElementType.Artifact.name()); - - return info; - } - - private static List getServiceArtifactNamespace() { - return ElementHandler.getElementPath(StructureElement.ServiceModel.name()); - } - - public static ElementEntityContext convertServiceArtifactToElementContext(ServiceArtifact - serviceArtifactEntity) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(serviceArtifactEntity.getVspId(), serviceArtifactEntity.getVersion().toString())); - } - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VspServiceTemplateConvertor.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VspServiceTemplateConvertor.java deleted file mode 100644 index a767246f12..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/convertors/VspServiceTemplateConvertor.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.openecomp.core.migration.convertors; - -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.store.ElementHandler; -import org.openecomp.core.model.types.ServiceTemplate; -import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.sdc.model.impl.zusammen.ElementType; -import org.openecomp.sdc.model.impl.zusammen.StructureElement; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * @author katyr - * @since April 23, 2017 - */ - -public class VspServiceTemplateConvertor -{ - private static Set serviceTemplatesLoaded = new HashSet<>(); - - - - public static CollaborationElement[] convertServiceTemplateToElement(ServiceTemplate serviceTemplate) { - - CollaborationElement[] serviceTemplateElements; - List serviceTemplateNamespace = getServiceTemplateNamespace(); - - int index = 0; - String serviceTemplatesEntityId = StructureElement.Templates.name(); - String uniqueId = serviceTemplate.getVspId()+"_"+serviceTemplate.getVersion().toString(); - if (serviceTemplatesLoaded.contains(uniqueId)) { - serviceTemplateElements = new CollaborationElement[1]; - } else { - serviceTemplatesLoaded.add(uniqueId); - String vspServiceModelEntityId = StructureElement.ServiceModel.name(); - - serviceTemplateElements = new CollaborationElement[3]; - serviceTemplateElements[index] = ElementHandler.getElementEntity( - serviceTemplate.getVspId(), - serviceTemplate.getVersion().toString(), - vspServiceModelEntityId, - serviceTemplateNamespace, - ElementHandler.getServiceModelElementInfo(vspServiceModelEntityId,serviceTemplate), - null, - null, - null); - index++; - serviceTemplateNamespace.add(vspServiceModelEntityId); - serviceTemplateElements[index] = ElementHandler.getElementEntity( - serviceTemplate.getVspId(), serviceTemplate.getVersion().toString(), serviceTemplatesEntityId, - serviceTemplateNamespace, - ElementHandler.getStructuralElementInfo(StructureElement.Templates.name()), - null, - null, - null); - index++; - } - - serviceTemplateNamespace.add(serviceTemplatesEntityId); - String elementId = serviceTemplate.getVspId()+"_"+serviceTemplate.getVersion().toString() - +"_"+serviceTemplate.getName(); - serviceTemplateElements[index] = ElementHandler.getElementEntity( - serviceTemplate.getVspId(), serviceTemplate.getVersion().toString(), elementId, - serviceTemplateNamespace, - getServiceTemplateInfo(serviceTemplate), - null, - null, - FileUtils.toByteArray(serviceTemplate.getContent())); - - return serviceTemplateElements; - } - - private static Info getServiceTemplateInfo(ServiceTemplate serviceTemplateEntity) { - Info info = new Info(); - info.setName(serviceTemplateEntity.getName()); - info.addProperty("type", ElementType.Servicetemplate.name()); - info.addProperty("base", serviceTemplateEntity.getBaseName()); - - - - return info; - } - - private static List getServiceTemplateNamespace() { - return ElementHandler.getElementPath(); - } - - public static ElementEntityContext convertServiceTemplateToElementContext(ServiceTemplate - serviceTemplateEntity) { - - return new ElementEntityContext("GLOBAL_USER", new - ElementContext(serviceTemplateEntity.getVspId(), serviceTemplateEntity.getVersion().toString())); - } - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ComponentCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ComponentCassandraLoader.java deleted file mode 100644 index 3e00f9d2bc..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ComponentCassandraLoader.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.core.migration.loaders; - -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.vendorsoftwareproduct.dao.type.ComponentEntity; - -import java.util.Collection; - -public class ComponentCassandraLoader { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final ComponentAccessor accessor = - noSqlDb.getMappingManager().createAccessor(ComponentAccessor.class); - - - public Collection list() { - return accessor.list().all(); - } - - @Accessor - interface ComponentAccessor { - - @Query( - "select * from vsp_component ") - Result list(); - - - } - - - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/EntitlementPoolCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/EntitlementPoolCassandraLoader.java deleted file mode 100644 index c307bfcdf6..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/EntitlementPoolCassandraLoader.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.openecomp.core.migration.loaders; - -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.vendorlicense.dao.types.EntitlementPoolEntity; - -import java.util.Collection; - -/** - * Created by ayalaben on 4/24/2017 - */ -public class EntitlementPoolCassandraLoader { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - - private static final EntitlementPoolCassandraLoader.EntitlementPoolAccessor accessor = - noSqlDb.getMappingManager().createAccessor(EntitlementPoolCassandraLoader.EntitlementPoolAccessor.class); - - public Collection list() { - return accessor.list().all(); - } - - @Accessor - interface EntitlementPoolAccessor { - @Query("select * from entitlement_pool ") - Result list(); - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/FeatureGroupCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/FeatureGroupCassandraLoader.java deleted file mode 100644 index 0c7627f177..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/FeatureGroupCassandraLoader.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.openecomp.core.migration.loaders; - -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.vendorlicense.dao.types.FeatureGroupEntity; - -import java.util.Collection; - -/** - * Created by ayalaben on 4/25/2017. - */ -public class FeatureGroupCassandraLoader { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final FeatureGroupCassandraLoader.FGAccessor accessor = - noSqlDb.getMappingManager().createAccessor(FeatureGroupCassandraLoader.FGAccessor.class); - - public Collection list() { - return accessor.getAll().all(); - } - - @Accessor - interface FGAccessor { - @Query("SELECT * FROM feature_group") - Result getAll(); - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/LKGCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/LKGCassandraLoader.java deleted file mode 100644 index 891a69eb14..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/LKGCassandraLoader.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.openecomp.core.migration.loaders; - -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.vendorlicense.dao.types.LicenseKeyGroupEntity; - -import java.util.Collection; - -/** - * Created by ayalaben on 4/24/2017 - */ -public class LKGCassandraLoader { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final LKGCassandraLoader.LKGAccessor accessor = - noSqlDb.getMappingManager().createAccessor(LKGCassandraLoader.LKGAccessor.class); - - public Collection list() { - return accessor.getAll().all(); - } - - @Accessor - interface LKGAccessor { - @Query("SELECT * FROM license_key_group") - Result getAll(); - - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/LicenseAgreementCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/LicenseAgreementCassandraLoader.java deleted file mode 100644 index ca44209bdb..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/LicenseAgreementCassandraLoader.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.openecomp.core.migration.loaders; - -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.vendorlicense.dao.types.LicenseAgreementEntity; - -import java.util.Collection; - -/** - * Created by ayalaben on 4/25/2017. - */ -public class LicenseAgreementCassandraLoader { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final LicenseAgreementCassandraLoader.LicenseAgreementAccessor accessor = - noSqlDb.getMappingManager().createAccessor(LicenseAgreementCassandraLoader.LicenseAgreementAccessor.class); - - public Collection list() { - return accessor.getAll().all(); - } - - @Accessor - interface LicenseAgreementAccessor { - @Query("SELECT * FROM license_agreement") - Result getAll(); - - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/MibCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/MibCassandraLoader.java deleted file mode 100644 index b93033cc72..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/MibCassandraLoader.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.core.migration.loaders; - -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.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; - -import java.util.Collection; - -public class MibCassandraLoader { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final MibAccessor accessor = - noSqlDb.getMappingManager().createAccessor(MibAccessor.class); - - - public Collection list() { - return accessor.list().all(); - } - - @Accessor - interface MibAccessor { - - @Query( - "select * from vsp_component_artifact") - Result list(); - - - } - - - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/NetworkCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/NetworkCassandraLoader.java deleted file mode 100644 index 7ce93bccf2..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/NetworkCassandraLoader.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.openecomp.core.migration.loaders; - -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.vendorsoftwareproduct.dao.type.NetworkEntity; - -import java.util.Collection; - -/** - * @author katyr - * @since April 23, 2017 - */ - -public class NetworkCassandraLoader { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final NetworkCassandraLoader.NetworkAccessor accessor = - noSqlDb.getMappingManager().createAccessor(NetworkCassandraLoader.NetworkAccessor.class); - - - public Collection list() { - return accessor.list().all(); - } - - @Accessor - interface NetworkAccessor { - - @Query( - "select * from vsp_network ") - Result list(); - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/NicCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/NicCassandraLoader.java deleted file mode 100644 index fea9c089b5..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/NicCassandraLoader.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.core.migration.loaders; - -import com.datastax.driver.mapping.Mapper; -import com.datastax.driver.mapping.Result; -import com.datastax.driver.mapping.UDTMapper; -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.vendorsoftwareproduct.dao.type.NicEntity; -import org.openecomp.sdc.versioning.dao.types.Version; - -import java.util.Collection; - -public class NicCassandraLoader { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final Mapper mapper = - noSqlDb.getMappingManager().mapper(NicEntity.class); - private static final NicAccessor accessor = - noSqlDb.getMappingManager().createAccessor(NicAccessor.class); - private static final UDTMapper versionMapper = - noSqlDb.getMappingManager().udtMapper(Version.class); - - - public Collection list() { - return accessor.list().all(); - } - - @Accessor - interface NicAccessor { - - @Query( - "select vsp_id, version, component_id, nic_id, composition_data,questionnaire_data " - + " from vsp_component_nic ") - Result list(); - - - } - - - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/OrchestrationTemplateCandidateCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/OrchestrationTemplateCandidateCassandraLoader.java deleted file mode 100644 index 09da455847..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/OrchestrationTemplateCandidateCassandraLoader.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.core.migration.loaders; - -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.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateDataEntity; - -import java.util.Collection; - -public class OrchestrationTemplateCandidateCassandraLoader { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final OrchestrationTemplateCandidateAccessor accessor = - noSqlDb.getMappingManager().createAccessor(OrchestrationTemplateCandidateAccessor.class); - - - public Collection list() { - return accessor.list().all(); - } - - @Accessor - interface OrchestrationTemplateCandidateAccessor { - - @Query( - "select * from vsp_orchestration_template_candidate ") - Result list(); - - - } - - - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ProcessCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ProcessCassandraLoader.java deleted file mode 100644 index 6672af5fb4..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ProcessCassandraLoader.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.core.migration.loaders; - -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.vendorsoftwareproduct.dao.type.ProcessEntity; - -import java.util.Collection; - -public class ProcessCassandraLoader { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final ProcessAccessor accessor = - noSqlDb.getMappingManager().createAccessor(ProcessAccessor.class); - - - public Collection list() { - return accessor.list().all(); - } - - @Accessor - interface ProcessAccessor { - - @Query( - "select * from vsp_process") - Result list(); - - - } - - - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ServiceArtifactCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ServiceArtifactCassandraLoader.java deleted file mode 100644 index 523166205a..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ServiceArtifactCassandraLoader.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.core.migration.loaders; - -import com.datastax.driver.mapping.Result; -import com.datastax.driver.mapping.annotations.Accessor; -import com.datastax.driver.mapping.annotations.Query; -import org.openecomp.core.model.types.ServiceArtifact; -import org.openecomp.core.model.types.ServiceArtifactEntity; -import org.openecomp.core.nosqldb.api.NoSqlDb; -import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; - -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - -public class ServiceArtifactCassandraLoader { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final VspServiceArtifactAccessor accessor = - noSqlDb.getMappingManager().createAccessor( - VspServiceArtifactAccessor.class); - - - public Collection list() { - - - List entityList = accessor.listAll().all(); - - return entityList.stream().map(entity -> entity.getServiceArtifact()) - .collect(Collectors.toList()); - } - - @Accessor - interface VspServiceArtifactAccessor { - - @Query("SELECT * FROM vsp_service_artifact") - Result listAll(); - - - } - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ServiceTemplateCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ServiceTemplateCassandraLoader.java deleted file mode 100644 index f7e5853ffb..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/ServiceTemplateCassandraLoader.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.core.migration.loaders; - -import com.datastax.driver.mapping.Result; -import com.datastax.driver.mapping.annotations.Accessor; -import com.datastax.driver.mapping.annotations.Query; -import org.openecomp.core.model.types.ServiceTemplate; -import org.openecomp.core.model.types.ServiceTemplateEntity; -import org.openecomp.core.nosqldb.api.NoSqlDb; -import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; - -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - -public class ServiceTemplateCassandraLoader { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final VspServiceTemplateAccessor accessor = - noSqlDb.getMappingManager().createAccessor( - VspServiceTemplateAccessor.class); - - - public Collection list() { - - - List entityList = accessor.listAll().all(); - - return entityList.stream().map(entity -> entity.getServiceTemplate()) - .collect(Collectors.toList()); - } - - @Accessor - interface VspServiceTemplateAccessor { - - @Query("SELECT * FROM vsp_service_template") - Result listAll(); - - - } - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VendorLicenseModelCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VendorLicenseModelCassandraLoader.java deleted file mode 100644 index c02cc1e4ef..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VendorLicenseModelCassandraLoader.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.core.migration.loaders; - -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.vendorlicense.dao.types.VendorLicenseModelEntity; - -import java.util.Collection; - -public class VendorLicenseModelCassandraLoader { - - private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static VendorLicenseModelAccessor accessor = - noSqlDb.getMappingManager().createAccessor(VendorLicenseModelAccessor.class); - - - public Collection list() { - return accessor.getAll().all(); - } - - @Accessor - interface VendorLicenseModelAccessor { - - @Query("SELECT * FROM vendor_license_model") - Result getAll(); - - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VendorSoftwareProductInfoLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VendorSoftwareProductInfoLoader.java deleted file mode 100644 index 26fc23cf5d..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VendorSoftwareProductInfoLoader.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.core.migration.loaders; - -import com.datastax.driver.mapping.Mapper; -import com.datastax.driver.mapping.Result; -import com.datastax.driver.mapping.UDTMapper; -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.versioning.dao.types.Version; - -import java.util.Collection; - -public class VendorSoftwareProductInfoLoader { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final Mapper mapper = - noSqlDb.getMappingManager().mapper(VspInformation.class); - private static final VendorSoftwareProductInfoAccessor accessor = - noSqlDb.getMappingManager().createAccessor(VendorSoftwareProductInfoAccessor.class); - private static final UDTMapper versionMapper = - noSqlDb.getMappingManager().udtMapper(Version.class); - - - public Collection list() { - return accessor.listAll().all(); - } - - - @Accessor - interface VendorSoftwareProductInfoAccessor { - - @Query( - "SELECT * " + - "FROM " + - "vsp_information") - Result listAll(); - - - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VersionInfoCassandraLoader.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VersionInfoCassandraLoader.java deleted file mode 100644 index 725298b195..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VersionInfoCassandraLoader.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.core.migration.loaders; - -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 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 Mapper mapper = - noSqlDb.getMappingManager().mapper(VersionInfoEntity.class); - private static VersionInfoAccessor accessor = - noSqlDb.getMappingManager().createAccessor(VersionInfoAccessor.class); - - - - - public Collection list() { - return accessor.getAll().all(); - } - - @Accessor - interface VersionInfoAccessor { - @Query("select * from version_info ") - Result getAll(); - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VspInformation.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VspInformation.java deleted file mode 100644 index 2db1b09db3..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/loaders/VspInformation.java +++ /dev/null @@ -1,276 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.core.migration.loaders; - -import com.datastax.driver.mapping.annotations.Column; -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 org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList; -import org.openecomp.sdc.versioning.dao.types.Version; - -import java.nio.ByteBuffer; -import java.util.List; - -@Table(keyspace = "dox", name = "vsp_information") -public class VspInformation { - public static final String ENTITY_TYPE = "Vendor Software Product"; - - @PartitionKey - @Column(name = "vsp_id") - private String id; - - @PartitionKey(value = 1) - @Frozen - private Version version; - - private String name; - private String description; - - private String category; - - @Column(name = "sub_category") - private String subCategory; - - private String icon; - - @Column(name = "vendor_name") - private String vendorName; - - @Column(name = "vendor_id") - private String vendorId; - - @Column(name = "vlm_version") - @Frozen - private Version vlmVersion; - - @Column(name = "license_agreement") - private String licenseAgreement; - - @Column(name = "feature_groups") - private List featureGroups; - - @Column(name = "package_name") - private String packageName; - - @Column(name = "package_version") - private String packageVersion; - - @Column(name = "validation_data") - private String validationData; - - @Column(name = "is_old_version") - private String isOldVersion; - - @Column(name = "questionnaire_data") - private String questionnaireData; - - @Column(name = "content_data") - private ByteBuffer contentData; - - - @Computed("writetime(name)") - private Long writetimeMicroSeconds; - - - public VspInformation() { - } - - public VspInformation(String id, Version version) { - this.id = id; - this.version = version; - } - - - 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 getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getSubCategory() { - return subCategory; - } - - public void setSubCategory(String subCategory) { - this.subCategory = subCategory; - } - - public String getIcon() { - return icon; - } - - public void setIcon(String icon) { - this.icon = icon; - } - - public String getVendorName() { - return vendorName; - } - - public void setVendorName(String vendorName) { - this.vendorName = vendorName; - } - - public String getVendorId() { - return vendorId; - } - - public void setVendorId(String vendorId) { - this.vendorId = vendorId; - } - - public Version getVlmVersion() { - return vlmVersion; - } - - public void setVlmVersion(Version vlmVersion) { - this.vlmVersion = vlmVersion; - } - - public String getLicenseAgreement() { - return licenseAgreement; - } - - public void setLicenseAgreement(String licenseAgreement) { - this.licenseAgreement = licenseAgreement; - } - - public List getFeatureGroups() { - return featureGroups; - } - - public void setFeatureGroups(List featureGroups) { - this.featureGroups = featureGroups; - } - - 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 Long getWritetimeMicroSeconds() { - return this.writetimeMicroSeconds; - } - - public void setWritetimeMicroSeconds(Long writetimeMicroSeconds) { - this.writetimeMicroSeconds = writetimeMicroSeconds; - } - - public String getIsOldVersion() { - return this.isOldVersion; - } - - public void setIsOldVersion(String oldVersion) { - this.isOldVersion = oldVersion; - } - - public void setVersion(Version version) { - this.version = version; - } - - public Version getVersion() { - return version; - } - - public String getQuestionnaireData() { - return questionnaireData; - } - - public void setQuestionnaireData(String questionnaireData) { - this.questionnaireData = questionnaireData; - } - - public ByteBuffer getContentData() { - return contentData; - } - - public void setContentData(ByteBuffer contentData) { - this.contentData = contentData; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("Vsp id = ").append(this.id); - sb.append("Version = ").append(this.version); - - return sb.toString(); - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/store/ElementHandler.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/store/ElementHandler.java deleted file mode 100644 index 548a8d989b..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/store/ElementHandler.java +++ /dev/null @@ -1,136 +0,0 @@ -package org.openecomp.core.migration.store; - -import com.amdocs.zusammen.datatypes.Id; -import com.amdocs.zusammen.datatypes.Namespace; -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.Relation; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.migration.MigrationMain; -import org.openecomp.core.model.types.ServiceTemplate; -import org.openecomp.core.zusammen.plugin.ZusammenPluginUtil; -import org.openecomp.core.zusammen.plugin.dao.impl.CassandraElementRepository; -import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionInfoEntity; - -import java.io.ByteArrayInputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class ElementHandler { - - private static final String GLOBAL_USER = "GLOBAL_USER"; - - public static void save(SessionContext context, - CassandraElementRepository cassandraElementRepository, - String itemId, Version versionId, - CollaborationElement[] elements) { - - ElementEntityContext elementContext; - for (CollaborationElement element : elements) { - - elementContext = new ElementEntityContext(GLOBAL_USER, new Id(itemId), getVersionId(itemId, - versionId)); - ElementEntity elementEntity = ZusammenPluginUtil.getElementEntity(element); - - cassandraElementRepository.createNamespace(context, elementContext, elementEntity); - - cassandraElementRepository.create(context, elementContext, elementEntity); - - if (isActiveVersion(itemId, versionId)) { - elementContext = - new ElementEntityContext(GLOBAL_USER, new Id(itemId), new Id(versionId.toString())); - cassandraElementRepository.create(context, elementContext, elementEntity); - - } - } - } - - public static CollaborationElement getElementEntity(String itemId, - String versionId, - String elementId, - List elementPath, - Info info, - Collection relations, - List subElements, - byte[] data) { - Namespace namespace = new Namespace(); - for (String pathElementId : elementPath) { - namespace = new Namespace(namespace, new Id(pathElementId)); - } - if (namespace.getValue() == null || namespace.getValue().equals("")) { - namespace = Namespace.ROOT_NAMESPACE; - } - CollaborationElement elementEntity = new CollaborationElement(new Id(itemId), new Id(versionId), - namespace, new Id(elementId)); - - Id parentId = namespace.getParentElementId() != null ? namespace.getParentElementId() : Id.ZERO; - elementEntity.setParentId(parentId); - elementEntity.setInfo(info); - elementEntity.setRelations(relations); - if (subElements != null) { - Set subElementSet = new HashSet<>(); - - subElements.forEach(subElement -> subElementSet.add(new Id(subElement))); - - } - if (data != null) { - elementEntity.setData(new ByteArrayInputStream(data)); - } - - return elementEntity; - } - - public static List getElementPath(String... paths) { - List pathList = new ArrayList<>(); - if (paths != null) { - Collections.addAll(pathList, paths); - } - return pathList; - } - - public static Info getStructuralElementInfo(String elementName) { - Info info = new Info(); - info.setName(elementName); - return info; - } - - - private static Id getVersionId(String itemId, Version versionId) { - VersionInfoEntity versionInfo = - MigrationMain.getVersionInfoMap().get(itemId); - if (versionInfo == null) { - return new Id(versionId.toString()); - } - Version lastVersion = versionInfo.getCandidate() != null ? versionInfo.getCandidate() - .getVersion() - : versionInfo.getActiveVersion(); - - if (lastVersion.equals(versionId)) { - return new Id(itemId); - } else { - return new Id(versionId.toString()); - } - } - - private static boolean isActiveVersion(String itemId, Version versionId) { - VersionInfoEntity versionInfo = - MigrationMain.getVersionInfoMap().get(itemId); - return versionInfo != null && versionInfo.getActiveVersion().equals(versionId); - } - - - public static Info getServiceModelElementInfo(String vspServiceModelEntityId, - ServiceTemplate serviceTemplate) { - Info info = ElementHandler.getStructuralElementInfo(vspServiceModelEntityId); - info.addProperty("base", serviceTemplate.getBaseName()); - return info; - - } -} \ No newline at end of file diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/store/ItemHandler.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/store/ItemHandler.java deleted file mode 100644 index 801984ab24..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/store/ItemHandler.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.openecomp.core.migration.store; - -import com.amdocs.zusammen.datatypes.Id; -import com.amdocs.zusammen.datatypes.Namespace; -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.ItemVersionData; -import com.amdocs.zusammen.datatypes.item.Relation; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.impl.ItemCassandraDao; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.impl.VersionCassandraDao; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntity; - -import org.openecomp.core.migration.MigrationMain; -import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionInfoEntity; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class ItemHandler { - - public static ElementEntity getElementEntity(String id, List - elementPath, Info info, Collection relations, List subElements, - byte[] data) { - ElementEntity elementEntity = new ElementEntity(new Id(id)); - - Namespace namespace = new Namespace(); - for (String elementId : elementPath) { - namespace = new Namespace(namespace, new Id(elementId)); - } - elementEntity.setNamespace(namespace); - elementEntity.setParentId(namespace.getParentElementId()); - elementEntity.setInfo(info); - elementEntity.setRelations(relations); - if(subElements!=null) { - Set subElementSet = new HashSet<>(); - - subElements.forEach(subElement -> subElementSet.add(new Id(subElement))); - - elementEntity.setSubElementIds(subElementSet); - } - - //elementEntity.setData(new ByteArrayInputStream(data)); - return elementEntity; - } - - public static List getElementPath(String... paths) { - List pathList = new ArrayList<>(); - for (String path : paths) { - pathList.add(path); - } - return pathList; - } - - public static Info getStractualElementInfo(String elementName) { - Info info = new Info(); - info.setName(elementName); - return info; - } - - public static void save(SessionContext context, ItemCassandraDao itemCassandraDao, - VersionCassandraDao versionCassandraDao, - String itemId, Version versionId, Info info, - ItemVersionData itemVersionData, Long writetimeMicroSeconds) { - - Date date = writetimeMicroSeconds==null?new Date():new Date(writetimeMicroSeconds); - itemCassandraDao.create(context,new Id(itemId),info,date); - - versionCassandraDao.create(context, context.getUser().getUserName(),new Id(itemId), - null,getVersionId(itemId,versionId),itemVersionData,date); - - if(isActiveVersion(itemId,versionId)){ - versionCassandraDao.create(context, context.getUser().getUserName(),new Id(itemId), - null,new Id(versionId.toString()),itemVersionData,date); - } - } - - - - private static Info getInfo(VendorLicenseModelEntity vlmEntity) { - Info info = new Info(); - - info.setName(vlmEntity.getVendorName()); - info.setDescription(vlmEntity.getDescription()); - info.addProperty("iconRef",vlmEntity.getIconRef()); - info.addProperty("type",vlmEntity.getIconRef()); - return info; - } - - private static Id getVersionId(String itemId, Version versionId) { - VersionInfoEntity versionInfo = - MigrationMain.getVersionInfoMap().get(itemId); - if (versionInfo == null) { - return new Id(versionId.toString()); - } - Version lastVersion = versionInfo.getCandidate() != null ? versionInfo.getCandidate() - .getVersion() - : versionInfo.getActiveVersion(); - - if (lastVersion.equals(versionId)) { - return new Id(itemId); - } else { - return new Id(versionId.toString()); - } - } - private static boolean isActiveVersion(String itemId, Version versionId) { - VersionInfoEntity versionInfo = - MigrationMain.getVersionInfoMap().get(itemId); - if (versionInfo == null) { - return false; - } - - return versionInfo.getActiveVersion().equals(versionId); - } - - -} \ No newline at end of file diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/util/Utils.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/util/Utils.java deleted file mode 100644 index ea026e5d4f..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/util/Utils.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.openecomp.core.migration.util; - -import org.openecomp.sdc.logging.api.Logger; - -/** - * @author Avrahamg - * @since April 24, 2017 - */ -public class Utils { - public static void printMessage(Logger logger, String message) { - System.out.println(message); - logger.debug(message); - } -} - diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/util/marker/MigrationMarker.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/util/marker/MigrationMarker.java deleted file mode 100644 index 4481b431ec..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/util/marker/MigrationMarker.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.openecomp.core.migration.util.marker; - -import com.datastax.driver.mapping.annotations.Accessor; -import com.datastax.driver.mapping.annotations.Query; -import org.openecomp.core.migration.MigrationMain; -import org.openecomp.core.nosqldb.api.NoSqlDb; -import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - -/** - * @author katyr - * @since May 01, 2017 - */ - -public class MigrationMarker { - - private static Logger logger = LoggerFactory.getLogger(MigrationMain.class); - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final MigrationTableAccessor accessor = - noSqlDb.getMappingManager().createAccessor(MigrationMarker.MigrationTableAccessor.class); - - public static Boolean isMigrated() { - - MigrationMarkerEntity result = accessor.isMigrated(); - if (result == null) { - return false; - } else { - return result.getMigrated(); - } - } - - public static void markMigrated() { - accessor.markMigrated(); - } - - @Accessor - interface MigrationTableAccessor { - @Query("SELECT * FROM migration where id='1'") - MigrationMarkerEntity isMigrated(); - - - @Query("insert into migration (id,isMigrated) values('1',true)") - void markMigrated(); - - } - -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/util/marker/MigrationMarkerEntity.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/util/marker/MigrationMarkerEntity.java deleted file mode 100644 index 47bb91dc49..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/util/marker/MigrationMarkerEntity.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.openecomp.core.migration.util.marker; - -import com.datastax.driver.mapping.annotations.ClusteringColumn; -import com.datastax.driver.mapping.annotations.Column; -import com.datastax.driver.mapping.annotations.Table; - -/** - * @author katyr - * @since May 03, 2017 - */ - -@Table(keyspace = "dox", name = "migration") -public class MigrationMarkerEntity { - - @ClusteringColumn - private String id; - - @Column(name = "ismigrated") - private Boolean migrated; - - public Boolean getMigrated() { - return migrated; - } - - public void setMigrated(Boolean migrated) { - this.migrated = migrated; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("MigrationMarkerEntity{"); - sb.append("id='").append(id).append('\''); - sb.append(", migrated=").append(migrated); - sb.append('}'); - return sb.toString(); - } -} diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/resources/logback.xml b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/resources/logback.xml deleted file mode 100644 index 9c9c06c216..0000000000 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/resources/logback.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/ExportDataCommand.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/ExportDataCommand.java deleted file mode 100644 index 487b4131e6..0000000000 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/ExportDataCommand.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.openecomp.core.tools.Commands; - -import static java.nio.file.Files.createDirectories; - -import com.amdocs.zusammen.datatypes.SessionContext; -import org.apache.commons.io.FileUtils; -import org.openecomp.core.tools.Commands.exportdata.ElementHandler; -import org.openecomp.core.tools.Commands.exportdata.ImportProperties; -import org.openecomp.core.tools.Commands.exportdata.ItemHandler; -import org.openecomp.core.tools.Commands.exportdata.VersionHandler; -import org.openecomp.core.tools.util.ZipUtils; -import org.openecomp.core.zusammen.impl.CassandraConnectionInitializer; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.HashSet; -import java.util.Set; -public class ExportDataCommand { - private static final Logger logger = LoggerFactory.getLogger(ExportDataCommand.class); - - public static void exportData(SessionContext context, String filterItem) { - try { - Set filteredItem = new HashSet<>(); - filteredItem.add(filterItem); - ImportProperties.initParams(); - CassandraConnectionInitializer.setCassandraConnectionPropertiesToSystem(); - Path rootDir = Paths.get(ImportProperties.ROOT_DIRECTORY); - initDir(rootDir); - if (filterItem != null) { - filterItem = filterItem.replaceAll("\\r", ""); - } - new ItemHandler().createItemsData(context, filteredItem); - new VersionHandler().loadVersions(filteredItem); - new ElementHandler().loadElements(filteredItem); - zipPath(rootDir,filteredItem); - FileUtils.forceDelete(rootDir.toFile()); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - - } - private static void zipPath(Path rootDir,Set filterItem ) throws Exception{ - LocalDateTime date = LocalDateTime.now(); - DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; - String dateStr = date.format(formatter); - String zipFile = System.getProperty("user.home")+ File.separatorChar+"onboarding_import"+ dateStr + ".zip"; - ZipUtils.createZip(zipFile, rootDir,filterItem); - logger.info("Exported file :" + zipFile); - System.out.println("Exported file :" + zipFile); - } - - - public static void initDir(Path rootDir ) throws IOException{ - if (Files.exists(rootDir)) { - FileUtils.forceDelete(rootDir.toFile()); - } - createDirectories(rootDir); - } - -} \ No newline at end of file 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 2bc48bd0e8..40a56eda83 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 @@ -3,6 +3,8 @@ package org.openecomp.core.tools.Commands; import org.apache.commons.collections.CollectionUtils; import org.openecomp.core.tools.concurrent.ItemHealingTask; import org.openecomp.core.tools.loaders.VersionInfoCassandraLoader; +import org.openecomp.sdc.healing.api.HealingManager; +import org.openecomp.sdc.healing.factory.HealingManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants; import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager; import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory; @@ -31,18 +33,20 @@ import java.util.stream.Stream; public class HealAll { private static final String HEALING_USER = "healing_user"; - private static final int defaulThreadNumber =100; + private static final int defaulThreadNumber = 100; private static BufferedWriter log; private static List tasks = new ArrayList<>(); private static VendorSoftwareProductManager vspManager = VspManagerFactory .getInstance().createInterface(); + private static HealingManager healingManager = HealingManagerFactory.getInstance() + .createInterface(); private static VersioningManager versioningManager = VersioningManagerFactory.getInstance() .createInterface(); static { try { log = - new BufferedWriter(new FileWriter("healing.log",true)); + new BufferedWriter(new FileWriter("healing.log", true)); } catch (IOException e) { if (log != null) { try { @@ -64,13 +68,13 @@ public class HealAll { defaulThreadNumber; ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads); - filterByEntityType(VersionInfoCassandraLoader.list(), + filterByEntityType(VersionInfoCassandraLoader.list(), VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE).forEach - (HealAll::addTaskToTasks); + (HealAll::addTaskToTasks); executeAllTasks(executor); - writeToLog("----finished healing------" ); + writeToLog("----finished healing------"); Instant endTime = Instant.now(); writeToLog("Total runtime was: " + Duration.between(startTime, endTime)); @@ -112,7 +116,7 @@ public class HealAll { if (Objects.nonNull(versionInfoEntity.getCandidate())) { return versionInfoEntity.getCandidate().getVersion(); } else if (!CollectionUtils.isEmpty(versionInfoEntity.getViewableVersions())) { - return versionInfoEntity.getViewableVersions().stream().max(Version::compateTo).get(); + return versionInfoEntity.getViewableVersions().stream().max(Version::compateTo).get(); } return versionInfoEntity.getActiveVersion(); } @@ -126,17 +130,16 @@ public class HealAll { } } - private static Stream filterByEntityType(Collection - versionInfoEntities, - String entityType){ + private static Stream filterByEntityType( + Collection versionInfoEntities, String entityType) { return versionInfoEntities.stream().filter(versionInfoEntity -> versionInfoEntity .getEntityType().equals(entityType)); } - private static void addTaskToTasks(VersionInfoEntity versionInfoEntity){ + + private static void addTaskToTasks(VersionInfoEntity versionInfoEntity) { tasks.add(new ItemHealingTask(versionInfoEntity.getEntityId(), resolveVersion - (versionInfoEntity).toString(), versionInfoEntity.getCandidate() == null ? - HEALING_USER : versionInfoEntity.getCandidate().getUser(), - vspManager, versioningManager)); + (versionInfoEntity).toString(), + vspManager, healingManager)); } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/ImportCommand.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/ImportCommand.java deleted file mode 100644 index cebff91160..0000000000 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/ImportCommand.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.openecomp.core.tools.Commands; - -import com.amdocs.zusammen.datatypes.SessionContext; -import org.apache.commons.io.FileUtils; -import org.openecomp.core.tools.Commands.importdata.TreeWalker; -import org.openecomp.core.tools.Commands.exportdata.ImportProperties; -import org.openecomp.core.tools.util.ZipUtils; -import org.openecomp.core.zusammen.impl.CassandraConnectionInitializer; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - -import java.nio.file.Path; -import java.nio.file.Paths; - -public class ImportCommand { - - private static final Logger logger = LoggerFactory.getLogger(ImportCommand.class); - - - public static void importData(SessionContext context, String zippedFile, String filterItem) { - try { - ImportProperties.initParams(); - CassandraConnectionInitializer.setCassandraConnectionPropertiesToSystem(); - if (zippedFile == null){ - logger.error("Import must have a valid file as an input."); - } - if (zippedFile != null) { - zippedFile = zippedFile.replaceAll("\\r", ""); - if (filterItem != null) { - filterItem = filterItem.replaceAll("\\r", ""); - } - Path rootDir = Paths.get(ImportProperties.ROOT_DIRECTORY); - ExportDataCommand.initDir(rootDir); - ZipUtils.unzip(Paths.get(zippedFile), rootDir); - TreeWalker.walkFiles(context, rootDir, filterItem); - FileUtils.forceDelete(rootDir.toFile()); // clear all unzip data at the end. - } - - - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - } - -} 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 new file mode 100644 index 0000000000..b885ac5d05 --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/SetHealingFlag.java @@ -0,0 +1,31 @@ +package org.openecomp.core.tools.Commands; + +import com.datastax.driver.core.ResultSet; +import org.openecomp.core.tools.store.HealingHandler; +import org.openecomp.core.tools.store.VersionCassandraLoader; +import org.openecomp.core.tools.store.zusammen.datatypes.HealingEntity; + +import java.util.ArrayList; + + +/** + * Created by ayalaben on 10/15/2017 + */ +public class SetHealingFlag { + + + public static void populateHealingTable(String oldVersion) { + + 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))); + + HealingHandler healingHandler = new HealingHandler(); + healingHandler.populateHealingTable(healingEntities); + + } +} diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/ElementHandler.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/ElementHandler.java deleted file mode 100644 index e03b7ffa82..0000000000 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/ElementHandler.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.openecomp.core.tools.Commands.exportdata; - - -import org.openecomp.core.tools.store.ElementCassandraLoader; -import org.openecomp.core.tools.store.zusammen.datatypes.ElementEntity; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - -import java.nio.ByteBuffer; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Objects; -import java.util.Set; - -import static java.io.File.separator; -import static java.nio.file.Files.*; -import static org.openecomp.core.tools.Commands.exportdata.ImportProperties.*; - -public class ElementHandler { - - private static final Logger logger = LoggerFactory.getLogger(ElementHandler.class); - - public ElementHandler() { - } - - public void loadElements(Set filteredItem) { - ElementCassandraLoader elementCassandraLoader = new ElementCassandraLoader(); - elementCassandraLoader.list().forEach(elementEntity -> handleElementEntity(elementEntity,filteredItem)); - } - - private void handleElementEntity(ElementEntity elementEntity, Set filteredItem) { - try { - String itemId = elementEntity.getItemId(); - - if (!filteredItem.isEmpty() && !filteredItem.contains(itemId)){ - return; - } - String versionId = elementEntity.getVersionId(); - String space = elementEntity.getSpace(); - String namespace = elementEntity.getNamespace(); - String elementId = elementEntity.getElement_id(); - - String namespacePath = separator; - if (!isNull(namespace)){ - namespacePath = namespace.replace(ELEMENT_NAMESPACE_SPLITTER,separator)+separator; - } - Path elementDirectoryPath; - if (!isNull(namespace)){ - elementDirectoryPath = Paths.get( ROOT_DIRECTORY + separator + itemId - + separator + versionId + separator + space + separator + namespacePath+ separator + elementId); - } else { - elementDirectoryPath = Paths.get( ROOT_DIRECTORY + separator + itemId - + separator + versionId + separator + space + separator + elementId); - } - - if (notExists(elementDirectoryPath)) { - Path created = createDirectories(elementDirectoryPath); - } - - String info = elementEntity.getInfo(); - if (!isNull(info)) { - Path infoFilePath = Paths.get(elementDirectoryPath.toString() + separator + ELEMENT_INFO_PREFIX - + elementId + JSON_POSTFIX); - write(infoFilePath, info.getBytes()); - } - - String relations = elementEntity.getRelations(); - if (!isNull(relations)) { - Path realtionsFilePath = Paths.get(elementDirectoryPath.toString() + separator - + ELEMENT_RELATION_PREFIX + elementId + JSON_POSTFIX); - write(realtionsFilePath, relations.getBytes()); - } - - ByteBuffer data = elementEntity.getData(); - if (!Objects.isNull(data)) { - Path dataFilePath = Paths.get(elementDirectoryPath.toString() + separator - + ELEMENT_DATA_PREFIX + elementId + JSON_POSTFIX); - write(dataFilePath, data.array()); - } - - ByteBuffer visualization = elementEntity.getVisualization(); - if (!Objects.isNull(visualization)) { - Path visualFilePath = Paths.get(elementDirectoryPath.toString() + separator - + ELEMENT_VISUALIZATION_PREFIX + elementId ); - write(visualFilePath, visualization.array()); - } - - ByteBuffer searchableData = elementEntity.getSearchableData(); - if (!Objects.isNull(searchableData)) { - Path searchableFilePath = Paths.get(elementDirectoryPath.toString() + separator - + ELEMENT_SEARCHABLE_PREFIX + elementId); - write(searchableFilePath, searchableData.array()); - } - - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - - } - - private boolean isNull(String inStr){ - if (Objects.isNull(inStr)){ - return true; - } - return inStr.trim().equalsIgnoreCase("null"); - } - -} diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/ImportProperties.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/ImportProperties.java deleted file mode 100644 index 3b7566fd1b..0000000000 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/ImportProperties.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.openecomp.core.tools.Commands.exportdata; - -import java.io.File; - -public class ImportProperties { - public static final String VERSION_FILE_PREFIX = "version_"; - public static final String VERSION_INFO_FILE_PREFIX = "version_info_"; - public static final String JSON_POSTFIX = ".json"; - - public static final String ELEMENT_INFO_PREFIX = "elem_info"; - public static final String ELEMENT_RELATION_PREFIX = "elem_relations"; - public static final String ELEMENT_DATA_PREFIX = "elem_data"; - public static final String ELEMENT_VISUALIZATION_PREFIX = "elem_visualization"; - public static final String ELEMENT_SEARCHABLE_PREFIX = "elem_searchableData"; - public static final String ELEMENT_NAMESPACE_SPLITTER = "/"; - public static String ROOT_DIRECTORY; - public static final void initParams(){ - 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/Commands/exportdata/ItemHandler.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/ItemHandler.java deleted file mode 100644 index ebbfb56ed0..0000000000 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/ItemHandler.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.openecomp.core.tools.Commands.exportdata; - -import com.amdocs.zusammen.datatypes.Id; -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.item.Item; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.ItemDao; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.ItemDaoFactory; -import com.google.common.base.Strings; -import org.openecomp.core.tools.Commands.ExportDataCommand; -import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import static java.io.File.separator; -import static java.nio.file.Files.*; -import static org.openecomp.core.tools.Commands.exportdata.ImportProperties.JSON_POSTFIX; - -public class ItemHandler { - private static final Logger logger = LoggerFactory.getLogger(ExportDataCommand.class); - - - public ItemHandler() { - ImportProperties.initParams(); - } - - public void createItemsData(SessionContext context, Set filteredItem) throws URISyntaxException, IOException { - final List items = new ArrayList<>(); - if (filteredItem.isEmpty()) { - items.addAll(getItemDao(context).list(context)); - } else { - Optional item = addItem(context, filteredItem.iterator().next(), items); - item.ifPresent(foundedItem -> { - Object vendorId = foundedItem.getInfo().getProperty("vendorId"); - if (vendorId != null) { - String vendorIdStr = vendorId.toString(); - addItem(context, vendorIdStr, items); - filteredItem.add(vendorIdStr); - } - }); - } - - items.parallelStream().forEach(item -> createItemDirectoryAndFiles(item, filteredItem)); - - } - - - - private Optional addItem(SessionContext context, String filteredItem, List items) { - Optional item = getItemDao(context).get(context, new Id(filteredItem)); - item.ifPresent(itemData -> items.add(itemData)); - return item; - } - - private final void createItemDirectoryAndFiles(Item item, Set filteredItem) { - try { - String itemId = item.getId().getValue(); - if (!filteredItem.isEmpty() && !filteredItem.contains(itemId)) { - return; - } - Path itemPath = Paths.get(ImportProperties.ROOT_DIRECTORY + separator + itemId); - Path itemFilePath = Paths.get(ImportProperties.ROOT_DIRECTORY + separator + - itemId + separator + itemId + JSON_POSTFIX); - if (notExists(itemPath)) { - createDirectories(itemPath); - } - String itemJson = JsonUtil.object2Json(item); - write(itemFilePath, itemJson.getBytes()); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - - } - - - private ItemDao getItemDao(SessionContext context) { - return ItemDaoFactory.getInstance().createInterface(context); - } -} diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/VersionHandler.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/VersionHandler.java deleted file mode 100644 index 4ff562484c..0000000000 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/exportdata/VersionHandler.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.openecomp.core.tools.Commands.exportdata; - -import org.openecomp.core.tools.Commands.ExportDataCommand; -import org.openecomp.core.tools.store.VersionInfoCassandraLoader; -import org.openecomp.core.tools.store.VersionCassandraLoader; - -import org.openecomp.core.tools.store.zusammen.datatypes.VersionEntity; -import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.versioning.dao.types.VersionInfoEntity; - -import static java.io.File.separator; -import static java.nio.file.Files.*; -import static org.openecomp.core.tools.Commands.exportdata.ImportProperties.*; -import static org.openecomp.core.tools.Commands.exportdata.ImportProperties.ROOT_DIRECTORY; - -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Set; - -public class VersionHandler { - private static final Logger logger = LoggerFactory.getLogger(ExportDataCommand.class); - - public VersionHandler() { - } - - public void loadVersions(Set filteredItem) { - VersionCassandraLoader versionCassandraLoader = new VersionCassandraLoader(); - versionCassandraLoader.list().forEach(versionEntity -> handleVersionEntity(versionEntity,filteredItem)); - VersionInfoCassandraLoader versionInfoCassandraLoader = new VersionInfoCassandraLoader(); - versionInfoCassandraLoader.list().forEach(versionInfoEntity -> handleVersionInfo(versionInfoEntity,filteredItem)); - } - - private void handleVersionEntity(VersionEntity versionEntity, Set filteredItem) { - try { - String itemId = versionEntity.getItemId(); - if (!filteredItem.isEmpty() && !filteredItem.contains(itemId)){ - return; - } - String versionId = versionEntity.getVersionId(); - String space = versionEntity.getSpace(); - Path versionDirectoryPath = Paths.get( ROOT_DIRECTORY + separator + itemId - + separator + versionId + separator + space); - Path versionFilePath = Paths.get(versionDirectoryPath.toString() + separator + VERSION_FILE_PREFIX - + versionId + JSON_POSTFIX); - if (notExists(versionDirectoryPath)) { - createDirectories(versionDirectoryPath); - } - String versionJson = JsonUtil.object2Json(versionEntity); - write(versionFilePath, versionJson.getBytes()); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - - } - - private void handleVersionInfo(VersionInfoEntity versionInfoEntity, Set filteredItem) { - try { - String itemId = versionInfoEntity.getEntityId(); - Path itemDirectory = Paths.get( ROOT_DIRECTORY + separator + itemId); - Path versionInfoFilePath = Paths.get(itemDirectory.toString() + separator + VERSION_INFO_FILE_PREFIX - + itemId + JSON_POSTFIX); - if (exists(itemDirectory)) { - String versionJson = JsonUtil.object2Json(versionInfoEntity); - write(versionInfoFilePath, versionJson.getBytes()); - } - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - - } -} diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/ElementImport.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/ElementImport.java deleted file mode 100644 index d439468e97..0000000000 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/ElementImport.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.openecomp.core.tools.Commands.importdata; - -import com.amdocs.zusammen.datatypes.Id; -import com.amdocs.zusammen.datatypes.SessionContext; -import org.openecomp.core.tools.store.ElementCassandraLoader; -import org.openecomp.core.tools.store.ElementNamespaceHandler; -import org.openecomp.core.tools.store.VersionCassandraLoader; -import org.openecomp.core.tools.store.zusammen.datatypes.ElementEntity; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import static java.io.File.separator; -import static org.openecomp.core.tools.Commands.exportdata.ImportProperties.*; - -public class ElementImport { - private static final Logger logger = LoggerFactory.getLogger(ElementImport.class); - public static final String ROOT_ITEM = Id.ZERO.getValue(); - - private ElementCassandraLoader elementCassandraLoader = new ElementCassandraLoader(); - private ElementNamespaceHandler cassandraElementRepository = new ElementNamespaceHandler(); - private VersionCassandraLoader versionCassandraLoader = new VersionCassandraLoader(); - - public void loadPath(SessionContext sessionContext, Path elementDir, String elementId, String[] - pathObjects) { - try { - if (!Files.isDirectory(elementDir)){ - return; - } - // load info file - ElementEntity elementEntity = new ElementEntity(); - Path infoFilePath = Paths.get(elementDir.toString() + separator + ELEMENT_INFO_PREFIX - + elementId + JSON_POSTFIX); - if (Files.exists(infoFilePath)) { - String info = new String(Files.readAllBytes(infoFilePath)); - elementEntity.setInfo(info); - } - // load relation file - Path realtionsFilePath = Paths.get(elementDir.toString() + separator - + ELEMENT_RELATION_PREFIX + elementId + JSON_POSTFIX); - if (Files.exists(realtionsFilePath)) { - String relations = new String(Files.readAllBytes(realtionsFilePath)); - elementEntity.setRelations(relations); - } - - //load entity data - Path dataFilePath = Paths.get(elementDir.toString() + separator - + ELEMENT_DATA_PREFIX + elementId + JSON_POSTFIX); - if (Files.exists(dataFilePath)) { - byte[] bytes = Files.readAllBytes(dataFilePath); - ByteBuffer data = ByteBuffer.wrap(bytes); - elementEntity.setData(data); - } - - //load visualization - Path visualFilePath = Paths.get(elementDir.toString() + separator - + ELEMENT_VISUALIZATION_PREFIX + elementId); - if (Files.exists(visualFilePath)) { - byte[] bytes = Files.readAllBytes(visualFilePath); - ByteBuffer visualization = ByteBuffer.wrap(bytes); - elementEntity.setVisualization(visualization); - } - - //load searchable - Path searchableFilePath = Paths.get(elementDir.toString() + separator - + ELEMENT_SEARCHABLE_PREFIX + elementId); - if (Files.exists(searchableFilePath)) { - byte[] bytes = Files.readAllBytes(searchableFilePath); - ByteBuffer searchable = ByteBuffer.wrap(bytes); - elementEntity.setSearchableData(searchable); - } - String element_Id = pathObjects[pathObjects.length - 1]; - elementEntity.setSpace(pathObjects[2]); - elementEntity.setItemId(pathObjects[0]); - elementEntity.setVersionId(pathObjects[1]); - elementEntity.setElement_id(element_Id); - elementEntity.setNamespace(getNameSpace(pathObjects)); - elementEntity.setParentId(getParentId(pathObjects)); - elementEntity.setSubElementIds(getAllSubElementsIds(elementDir, element_Id)); - elementCassandraLoader.createEntity(elementEntity); - cassandraElementRepository.createElementNamespace(elementEntity); - versionCassandraLoader.insertElementToVersion(elementEntity); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - } - - private String getParentId(String[] pathObjects) { - - if (pathObjects[pathObjects.length - 1].equals(ROOT_ITEM)) { - return null; - } - if (pathObjects.length == 4) { - return ROOT_ITEM; - } - return pathObjects[pathObjects.length - 2]; - } - - private Set getAllSubElementsIds(Path root, String elementId) throws IOException { - if (elementId.equals(ROOT_ITEM)) { - root = root.getParent(); - } - File file = root.toFile(); - Set retVal = new HashSet<>(); - File[] files = file.listFiles(); - for (File f : files){ - if (f.isDirectory()){ - retVal.add(f.getName()); - } - } - retVal.remove(ROOT_ITEM); - return retVal; - - } - - private String getNameSpace(String[] pathObjects) { - if (pathObjects.length <= 4) { - return ""; - } - if (pathObjects.length == 5) { - return pathObjects[3]; - } - return Arrays.stream(pathObjects, 3, pathObjects.length - 1) - .reduce("", (s1, s2) -> s1 + File.separator + s2); - } -} diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/ItemImport.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/ItemImport.java deleted file mode 100644 index 4dd4a1f2c8..0000000000 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/ItemImport.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.openecomp.core.tools.Commands.importdata; - -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.item.Item; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.ItemDao; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.ItemDaoFactory; -import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - -import java.io.File; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import static org.openecomp.core.tools.Commands.exportdata.ImportProperties.JSON_POSTFIX; - -public class ItemImport { - private static final Logger logger = LoggerFactory.getLogger(ItemImport.class); - - public void loadPath(SessionContext sessionContext, Path itemDir, String itemName) { - try { - Path itemPath = Paths.get(itemDir.toString() + File.separator + itemName + JSON_POSTFIX); - if (!Files.exists(itemPath)) { - return; - } - String itemJson = new String(Files.readAllBytes(itemPath)); - if (itemJson.trim().isEmpty()) { - return; - } - Item item = JsonUtil.json2Object(itemJson, Item.class); - ItemDao itemDao = getItemDao(sessionContext); - itemDao.create(sessionContext, item.getId(), item.getInfo(), item.getCreationTime()); - logger.info("Item Created :"+item.getInfo().getName()+" , "+item.getId()); - System.out.println("Item Created :"+item.getInfo().getName()+" , "+item.getId()); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - } - - private ItemDao getItemDao(SessionContext context) { - return ItemDaoFactory.getInstance().createInterface(context); - } -} diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/TreeWalker.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/TreeWalker.java deleted file mode 100644 index 30c4152491..0000000000 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/TreeWalker.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.openecomp.core.tools.Commands.importdata; - -import com.amdocs.zusammen.datatypes.SessionContext; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.stream.Stream; - -public class TreeWalker { - private static final Logger logger = LoggerFactory.getLogger(TreeWalker.class); - - public static final void walkFiles(SessionContext sessionContext,Path rootDir, String filterItem) throws IOException { - try (Stream walk = Files.walk(rootDir)) { - walk.parallel().filter(path -> Files.isDirectory(path)). - forEach(path -> handlePath(sessionContext,path, rootDir, filterItem)); - } - } - - private static final void handlePath(SessionContext sessionContext, Path path, Path root,String filterItem) { - String logicalPath = path.toString().replace(root.toString(), ""); - if (logicalPath.startsWith(File.separator)){ - logicalPath = logicalPath.substring(1); - } - String[] splitted = logicalPath.split(File.separator); - if(filterItem != null && splitted.length > 0 && !splitted[0].contains(filterItem)){ - return; - } - switch (splitted.length) { - case 0: - //root - ignore - break; - case 1: // handle Item - new ItemImport().loadPath(sessionContext,path,splitted[splitted.length -1]); - new VersionInfoImport().loadPath(sessionContext,path,splitted[splitted.length -1]); - break; - case 2: - //ignore this level - break; - case 3: // handle version - new VersionImport().loadPath(sessionContext,path,splitted[splitted.length -2]); - break; - default: - //handle elements - new ElementImport().loadPath(sessionContext,path,splitted[splitted.length -1],splitted); - break; - } - - } - -} diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/VersionImport.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/VersionImport.java deleted file mode 100644 index 48433d8a90..0000000000 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/VersionImport.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.openecomp.core.tools.Commands.importdata; - -import com.amdocs.zusammen.datatypes.SessionContext; -import org.openecomp.core.tools.store.VersionCassandraLoader; -import org.openecomp.core.tools.store.zusammen.datatypes.VersionEntity; -import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import static java.io.File.separator; -import static org.openecomp.core.tools.Commands.exportdata.ImportProperties.JSON_POSTFIX; -import static org.openecomp.core.tools.Commands.exportdata.ImportProperties.VERSION_FILE_PREFIX; - -public class VersionImport { - private static final Logger logger = LoggerFactory.getLogger(VersionImport.class); - - public void loadPath(SessionContext sessionContext, Path versionDir , String versionId){ - try { - Path versionPath = Paths.get(versionDir.toString() + separator + VERSION_FILE_PREFIX - + versionId + JSON_POSTFIX); - if (!Files.exists(versionPath)) { - return; - } - String versionJson = new String(Files.readAllBytes(versionPath)); - if (versionJson.trim().isEmpty()) { - return; - } - VersionEntity versionEntity = JsonUtil.json2Object(versionJson, VersionEntity.class); - VersionCassandraLoader versionCassandraLoader = new VersionCassandraLoader(); - versionCassandraLoader.insertVersion(versionEntity); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - } - - -} diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/VersionInfoImport.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/VersionInfoImport.java deleted file mode 100644 index e9d4174d6c..0000000000 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/Commands/importdata/VersionInfoImport.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.openecomp.core.tools.Commands.importdata; - -import com.amdocs.zusammen.datatypes.SessionContext; -import org.openecomp.core.tools.store.VersionInfoCassandraLoader; -import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.versioning.dao.types.VersionInfoEntity; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import static java.io.File.separator; -import static org.openecomp.core.tools.Commands.exportdata.ImportProperties.JSON_POSTFIX; -import static org.openecomp.core.tools.Commands.exportdata.ImportProperties.VERSION_INFO_FILE_PREFIX; - -public class VersionInfoImport { - private static final Logger logger = LoggerFactory.getLogger(VersionInfoImport.class); - - public void loadPath(SessionContext sessionContext, Path itemPath, String itemId) { - try { - Path versionInfoFilePath = Paths.get(itemPath.toString() + separator + VERSION_INFO_FILE_PREFIX - + itemId + JSON_POSTFIX); - if (!Files.exists(versionInfoFilePath)) { - return; - } - String versionInfoJson = new String(Files.readAllBytes(versionInfoFilePath)); - if (versionInfoJson.trim().isEmpty()) { - return; - } - VersionInfoEntity versionInfoEntity = JsonUtil.json2Object(versionInfoJson, VersionInfoEntity.class); - VersionInfoCassandraLoader versionInfoCassandraLoader = new VersionInfoCassandraLoader(); - versionInfoCassandraLoader.insertVersionInfo(versionInfoEntity); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - } - - -} diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/concurrent/ItemHealingTask.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/concurrent/ItemHealingTask.java index 39b62d4e99..878390fdc2 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/concurrent/ItemHealingTask.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/concurrent/ItemHealingTask.java @@ -1,13 +1,8 @@ package org.openecomp.core.tools.concurrent; -import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants; +import org.openecomp.sdc.healing.api.HealingManager; import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; -import org.openecomp.sdc.versioning.VersioningManager; -import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; import java.util.concurrent.Callable; @@ -17,55 +12,44 @@ import java.util.concurrent.Callable; public class ItemHealingTask implements Callable { private String itemId; - private String versionId; - private String user; + private Version version; private VendorSoftwareProductManager vspManager; - private VersioningManager versioningManager; + private HealingManager healingManager; public String getItemId() { return itemId; } public String getVersionId() { - return versionId; +// return version.getId(); + return null; } - public ItemHealingTask(String itemId, String versionId, String user, + public ItemHealingTask(String itemId, String versionId, VendorSoftwareProductManager vspManager, - VersioningManager versioningManager) { - this.itemId = itemId; - this.versionId = versionId; - this.user = user; - this.versioningManager = versioningManager; + HealingManager healingManager) { +// this.itemId = itemId; +// this.version = new Version(versionId); this.vspManager = vspManager; + this.healingManager = healingManager; + } @Override public String call() throws Exception { - - VersionInfo versionInfo = getVersionInfo(itemId, VersionableEntityAction.Read, user); - Version resolvedVersion = VersioningUtil.resolveVersion(Version.valueOf(versionId), - versionInfo, user); - VspDetails vspDetails = vspManager.getVsp(itemId, resolvedVersion, user); - - try { - vspManager.callAutoHeal(itemId, versionInfo, vspDetails, user); - - } catch (Exception e) { - return (String.format("healing failed on vsp: %s with id: %s, versionId: %s, resolved " + - "Version: %s, with message: %s",vspDetails.getName(),itemId, - versionId,resolvedVersion,e.getMessage())); - } - - return String.format("healed vsp: %s, with id: %s, versionId:%s, resolved version: %s", - vspDetails.getName(), itemId, versionId,resolvedVersion ); - } - - private VersionInfo getVersionInfo(String vendorSoftwareProductId, VersionableEntityAction action, - String user) { - return versioningManager.getEntityVersionInfo( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, - vendorSoftwareProductId, user, action); +// VspDetails vspDetails = vspManager.getVsp(itemId, version); +// +// try { +// healingManager.healItemVersion(itemId, version, ItemType.vsp, true); +// } catch (Exception e) { +// return (String +// .format("healing failed on vsp: %s with id: %s, versionId: %s, with message: %s", +// vspDetails.getName(), itemId, version.getId(), e.getMessage())); +// } +// +// return String.format("healed vsp: %s, with id: %s, versionId: %s", +// vspDetails.getName(), itemId, version.getId()); + return null; } } 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 new file mode 100644 index 0000000000..5dcc72de59 --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exportinfo/ExportDataCommand.java @@ -0,0 +1,125 @@ +/** + * Copyright © 2016-2017 European Support Limited. + */ +package org.openecomp.core.tools.exportinfo; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.ResultSetFuture; +import com.datastax.driver.core.Session; +import com.google.common.collect.Sets; +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import org.apache.commons.io.FileUtils; +import org.openecomp.core.nosqldb.impl.cassandra.CassandraSessionFactory; +import org.openecomp.core.tools.importinfo.ImportProperties; +import org.openecomp.core.tools.util.Utils; +import org.openecomp.core.tools.util.ZipUtils; +import org.openecomp.core.zusammen.impl.CassandraConnectionInitializer; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.yaml.snakeyaml.Yaml; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.stream.Collectors; + +import static java.nio.file.Files.createDirectories; + + +public class ExportDataCommand { + private static final Logger logger = LoggerFactory.getLogger(ExportDataCommand.class); + public static final String JOIN_DELIMITER = "$#"; + public static final String JOIN_DELIMITER_SPILTTER = "\\$\\#"; + public static final String MAP_DELIMITER = "!@"; + public static final String MAP_DELIMITER_SPLITTER = "\\!\\@"; + public static final String EXPORT_FILE_NAME = "ITEM_EXPORT"; + + public static void exportData(SessionContext sessionContext, String filterItem) { + try { + CassandraConnectionInitializer.setCassandraConnectionPropertiesToSystem(); + final Set filteredItems = Sets.newHashSet(filterItem); + Path rootDir = Paths.get(ImportProperties.ROOT_DIRECTORY); + initDir(rootDir); + 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")) { + queries = (Map>) yaml.load(is); + } + List queriesList = queries.get("queries"); + List itempsColumns = queries.get("item_columns"); + Set vlms = new HashSet<>(); + CountDownLatch doneQueries = new CountDownLatch(queriesList.size()); + for (int i = 0; i < queriesList.size(); i++) { + executeQuery(queriesList.get(i), fis, itempsColumns.get(i), vlms, doneQueries); + } + doneQueries.await(); + if (!vlms.isEmpty()) { + CountDownLatch doneVmls = new CountDownLatch(queriesList.size()); + + for (int i = 0; i < queriesList.size(); i++) { + executeQuery(queriesList.get(i), vlms, itempsColumns.get(i), null, doneVmls); + } + + doneVmls.await(); + } + zipPath(rootDir); + FileUtils.forceDelete(rootDir.toFile()); + } catch (Exception ex) { + Utils.logError(logger, ex); + } + + } + + + private static boolean executeQuery(final String query, final Set filteredItems, final String filteredColumn, + final Set vlms, final CountDownLatch donequerying) { + Session session = CassandraSessionFactory.getSession(); + ResultSetFuture resultSetFuture = session.executeAsync(query); + Futures.addCallback(resultSetFuture, new FutureCallback() { + @Override + public void onSuccess(ResultSet resultSet) { + new ExportSerializer().serializeResult(resultSet, filteredItems, filteredColumn, vlms); + donequerying.countDown(); + } + + @Override + public void onFailure(Throwable t) { + Utils.logError(logger, "Query failed :" + query, t); + donequerying.countDown(); + } + }); + return true; + } + + private static void zipPath(Path rootDir) throws Exception { + LocalDateTime date = LocalDateTime.now(); + DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; + String dateStr = date.format(formatter); + dateStr = dateStr.replaceAll(":", "_"); + String zipFile = System.getProperty("user.home") + File.separatorChar + "onboarding_import" + dateStr + ".zip"; + ZipUtils.createZip(zipFile, rootDir); + Utils.printMessage(logger, "Exported file :" + zipFile); + } + + + public static void initDir(Path rootDir) throws IOException { + if (rootDir.toFile().exists()) { + FileUtils.forceDelete(rootDir.toFile()); + } + createDirectories(rootDir); + } + +} \ No newline at end of file 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 new file mode 100644 index 0000000000..3c917b1c7e --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exportinfo/ExportSerializer.java @@ -0,0 +1,152 @@ +/** + * Copyright © 2016-2017 European Support Limited. + */ +package org.openecomp.core.tools.exportinfo; + +import com.datastax.driver.core.DataType.Name; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import org.codehaus.jackson.map.ObjectMapper; +import org.openecomp.core.tools.importinfo.ImportProperties; +import org.openecomp.core.tools.model.ColumnDefinition; +import org.openecomp.core.tools.model.TableData; +import org.openecomp.core.tools.util.Utils; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.openecomp.core.tools.importinfo.ImportSingleTable.dataTypesMap; + +public class ExportSerializer { + + private static final Logger logger = LoggerFactory.getLogger(ExportDataCommand.class); + 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.definitions = resultSet.getColumnDefinitions().asList().stream().map(column -> new ColumnDefinition(column)).collect(Collectors.toList()); + String table = tableData.definitions.iterator().next().getTable(); + boolean isElementTable = table.equals(ELEMENT_TABLE_NAME); + Iterator iterator = resultSet.iterator(); + iterator.forEachRemaining(row -> { + if (!filteredItems.contains(row.getString(filteredColumn))) { + return; + } + List rowData = new ArrayList<>(); + for (int i = 0; i < tableData.definitions.size(); i++) { + ColumnDefinition columnDefinition = tableData.definitions.get(i); + Name name = dataTypesMap.get(columnDefinition.getType()); + boolean checkForVLM = isElementTable && columnDefinition.getName().equals(ELEMENT_INFO_COLUMN_NAME); + Object data; + data = convertByType(vlms, row, i, name, checkForVLM); + rowData.add(data.toString()); + } + tableData.rows.add(rowData); + }); + ObjectMapper objectMapper = new ObjectMapper(); + 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); + } + } + + private Object convertByType(Set vlms, Row row, int i, Name name, boolean checkForVLM) { + Object data; + switch (name) { + case VARCHAR: + case TEXT: + case ASCII: + String string = row.getString(i); + if (string == null) { + string = ""; + } + if (checkForVLM && vlms != null){ + String vlm = extractVlm(string); + if (vlm!= null) { + vlms.add(vlm); + } + } + data = Base64.getEncoder().encodeToString(string.getBytes()); + break; + case BLOB: + ByteBuffer bytes = row.getBytes(i); + if (bytes == null) { + bytes = ByteBuffer.wrap("".getBytes()); + } + data = Base64.getEncoder().encodeToString(bytes.array()); + break; + case TIMESTAMP: + data = row.getDate(i).getTime(); + break; + case BOOLEAN: + data = row.getBool(i); + break; + case COUNTER: + data = row.getLong(i); + break; + case INT: + data = row.getInt(i); + break; + case FLOAT: + data = row.getFloat(i); + break; + case SET: + Set set = row.getSet(i, Object.class); + Object joined = set.stream().map(o -> o.toString()).collect(Collectors.joining(ExportDataCommand.JOIN_DELIMITER)); + data = Base64.getEncoder().encodeToString(joined.toString().getBytes()); + break; + case MAP: + Map map = row.getMap(i, Object.class, Object.class); + Set> entrySet = map.entrySet(); + Object mapAsString = entrySet.parallelStream().map(entry -> entry.getKey().toString() + ExportDataCommand.MAP_DELIMITER +entry.getValue().toString()) + .collect(Collectors.joining(ExportDataCommand.MAP_DELIMITER)); + data = Base64.getEncoder().encodeToString(mapAsString.toString().getBytes()); + break; + default: + throw new UnsupportedOperationException("Name is not supported :" + name); + } + return data; + } + + protected String extractVlm(String injson) { + try { + if (injson == null){ + return null; + } + JsonElement root = new JsonParser().parse(injson); + if (root == null){ + return null; + } + JsonElement properties = root.getAsJsonObject().get("properties"); + if (properties == null){ + return null; + } + JsonElement vendorId = properties.getAsJsonObject().get("vendorId"); + if (vendorId == null){ + return null; + } + return vendorId.getAsString(); + } catch (Exception ex){ + return null; + } + } +} 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 new file mode 100644 index 0000000000..bae6cfa4dd --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportDataCommand.java @@ -0,0 +1,37 @@ +package org.openecomp.core.tools.importinfo; + + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.apache.commons.io.FileUtils; +import org.openecomp.core.tools.exportinfo.ExportDataCommand; +import org.openecomp.core.tools.util.Utils; +import org.openecomp.core.tools.util.ZipUtils; +import org.openecomp.core.zusammen.impl.CassandraConnectionInitializer; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Stream; + +public class ImportDataCommand { + + private static final Logger logger = LoggerFactory.getLogger(ImportDataCommand.class); + + public static final void execute(SessionContext sessionContext, String uploadFile) { + try { + CassandraConnectionInitializer.setCassandraConnectionPropertiesToSystem(); + Path outputFolder = Paths.get(ImportProperties.ROOT_DIRECTORY); + ExportDataCommand.initDir(outputFolder); //clear old imports. + ZipUtils.unzip(Paths.get(uploadFile), outputFolder); + try( Stream files = Files.list(outputFolder)) { + files.forEach(file -> new ImportSingleTable().importFile(file)); + } + FileUtils.forceDelete(outputFolder.toFile()); // leaves directory clean + } catch (IOException e) { + Utils.logError(logger, e); + } + } +} 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 new file mode 100644 index 0000000000..b9a27faeef --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportProperties.java @@ -0,0 +1,7 @@ +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"; +} 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 new file mode 100644 index 0000000000..7504ad1194 --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportSingleTable.java @@ -0,0 +1,166 @@ +package org.openecomp.core.tools.importinfo; + +import com.datastax.driver.core.BoundStatement; +import com.datastax.driver.core.DataType.Name; +import com.datastax.driver.core.PreparedStatement; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.ResultSetFuture; +import com.datastax.driver.core.Session; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; +import com.google.common.collect.Sets; +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import org.apache.commons.lang3.StringUtils; +import org.codehaus.jackson.map.ObjectMapper; +import org.openecomp.core.nosqldb.impl.cassandra.CassandraSessionFactory; +import org.openecomp.core.tools.exportinfo.ExportDataCommand; +import org.openecomp.core.tools.model.ColumnDefinition; +import org.openecomp.core.tools.model.TableData; +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.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; + +public class ImportSingleTable { + + private static final Logger logger = LoggerFactory.getLogger(ImportSingleTable.class); + + public static final String INSERT_INTO = "INSERT INTO "; + public static final String VALUES = " VALUES "; + private static final Map statementsCache = new HashMap<>(); + + public void importFile(Path file) { + try { + ObjectMapper objectMapper = new ObjectMapper(); + TableData tableData = objectMapper.readValue(file.toFile(), TableData.class); + Session session = CassandraSessionFactory.getSession(); + PreparedStatement ps = getPrepareStatement(tableData, session); + tableData.rows.parallelStream().forEach(row -> executeQuery(session, ps, tableData.definitions, row)); + } catch (IOException e) { + Utils.logError(logger, e); + } + + } + + private PreparedStatement getPrepareStatement(TableData tableData, Session session) { + String query = createQuery(tableData); + if (statementsCache.containsKey(query)) { + return statementsCache.get(query); + } + PreparedStatement preparedStatement = session.prepare(query); + statementsCache.put(query, preparedStatement); + return preparedStatement; + } + + private void executeQuery(Session session, PreparedStatement ps, List definitions, List rows) { + BoundStatement bind = ps.bind(); + for (int i = 0; i < definitions.size(); i++) { + ColumnDefinition columnDefinition = definitions.get(i); + String rowData = rows.get(i); + Name name = dataTypesMap.get(columnDefinition.getType()); + handleByType(bind, i, rowData, name); + } + ResultSetFuture resultSetFuture = session.executeAsync(bind); + Futures.addCallback(resultSetFuture, new FutureCallback() { + @Override + public void onSuccess(ResultSet resultSet) { + Utils.printMessage(logger, "successful write "); + } + + @Override + public void onFailure(Throwable t) { + Utils.logError(logger, t); + } + }); + } + + private void handleByType(BoundStatement bind, int i, String rowData, Name name) { + switch (name) { + case VARCHAR: + case TEXT: + case ASCII: + bind.setString(i, new String(Base64.getDecoder().decode(rowData))); + break; + case BLOB: + bind.setBytes(i, ByteBuffer.wrap(Base64.getDecoder().decode(rowData.getBytes()))); + break; + case TIMESTAMP: + bind.setDate(i, new Date(Long.parseLong(rowData))); + break; + case BOOLEAN: + bind.setBool(i, Boolean.parseBoolean(rowData)); + break; + case COUNTER: + bind.setLong(i, Long.parseLong(rowData)); + break; + case INT: + bind.setInt(i, Integer.parseInt(rowData)); + break; + case FLOAT: + bind.setFloat(i, Float.parseFloat(rowData)); + break; + case SET: + byte[] decoded = Base64.getDecoder().decode(rowData); + String decodedStr = new String(decoded); + if (!StringUtils.isEmpty(decodedStr)) { + String[] splitted = decodedStr.split(ExportDataCommand.JOIN_DELIMITER_SPILTTER); + Set set = Sets.newHashSet(splitted); + set.remove(""); + bind.setSet(i, set); + } else { + bind.setSet(i, null); + } + break; + case MAP: + byte[] decodedMap = Base64.getDecoder().decode(rowData); + String mapStr = new String(decodedMap); + if (!StringUtils.isEmpty(mapStr)) { + String[] splittedMap = mapStr.split(ExportDataCommand.JOIN_DELIMITER_SPILTTER); + Map map = new HashMap<>(); + for (String keyValue : splittedMap) { + String[] split = keyValue.split(ExportDataCommand.MAP_DELIMITER_SPLITTER); + map.put(split[0], split[1]); + } + bind.setMap(i, map); + } else { + bind.setMap(i, null); + } + break; + default: + throw new UnsupportedOperationException("Name is not supported :" + name); + + } + } + + private String createQuery(TableData tableData) { + ColumnDefinition def = tableData.definitions.iterator().next(); + StringBuilder sb = new StringBuilder(); + sb.append(INSERT_INTO).append(def.getKeyspace()).append(".").append(def.getTable()); + sb.append(tableData.definitions.stream().map(definition -> definition.getName()).collect(Collectors.joining(" , ", " ( ", " ) "))); + sb.append(VALUES).append(tableData.definitions.stream().map(definition -> "?").collect(Collectors.joining(" , ", " ( ", " ) "))).append(";"); + return sb.toString(); + } + + 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(); + } + +} diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/loaders/zusammen/VspGeneralLoader.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/loaders/zusammen/VspGeneralLoader.java deleted file mode 100644 index d92866bb47..0000000000 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/loaders/zusammen/VspGeneralLoader.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.openecomp.core.tools.loaders.zusammen; - -import com.amdocs.zusammen.datatypes.Id; -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import org.openecomp.core.zusammen.plugin.dao.impl.CassandraElementRepository; -import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.StructureElement; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public class VspGeneralLoader { - public static Map load(SessionContext context, - Map> vspItemVersionsMap) { - Map elementEntityMap = new HashMap<>(); - System.setProperty("cassandra.dox.keystore", "zusammen_dox"); - CassandraElementRepository cassandraElementRepository = new CassandraElementRepository(); - for (Map.Entry> entry : vspItemVersionsMap.entrySet()) { - - for (String version : entry.getValue()) { - - Optional result = - cassandraElementRepository.get(context, new ElementEntityContext( - context.getUser().getUserName(), - new Id(entry.getKey()), - new Id(version)), - new ElementEntity(new Id(StructureElement.General.name()))); - if (result.isPresent()) { - elementEntityMap.put(context.getUser().getUserName() + "_" + entry.getKey() - + "_" + version, result.get()); - } - } - } - - return elementEntityMap; - } -} diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/loaders/zusammen/VspItemLoader.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/loaders/zusammen/VspItemLoader.java deleted file mode 100644 index 78b915c525..0000000000 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/loaders/zusammen/VspItemLoader.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.openecomp.core.tools.loaders.zusammen; - -public class VspItemLoader { -} 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 b55d51709d..182988717e 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 @@ -3,9 +3,9 @@ package org.openecomp.core.tools.main; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.UserInfo; import org.openecomp.core.tools.Commands.HealAll; -import org.openecomp.core.tools.Commands.ImportCommand; -import org.openecomp.core.tools.Commands.ExportDataCommand; -import org.openecomp.core.tools.Commands.ResetOldVersion; +import org.openecomp.core.tools.Commands.SetHealingFlag; +import org.openecomp.core.tools.exportinfo.ExportDataCommand; +import org.openecomp.core.tools.importinfo.ImportDataCommand; import org.openecomp.core.tools.util.ToolsUtil; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; @@ -39,13 +39,13 @@ public class ZusammenMainTool { switch (COMMANDS.valueOf(command)){ case RESET_OLD_VERSION: - ResetOldVersion.reset(context,ToolsUtil.getParam("v",args),ToolsUtil.getParam("n",args)); + SetHealingFlag.populateHealingTable(ToolsUtil.getParam("v",args)); break; case EXPORT: ExportDataCommand.exportData(context,ToolsUtil.getParam("i",args)); break; case IMPORT: - ImportCommand.importData(context, ToolsUtil.getParam("f",args),ToolsUtil.getParam("i",args)); + ImportDataCommand.execute(context, ToolsUtil.getParam("f",args)); break; case HEAL_ALL: HealAll.healAll(ToolsUtil.getParam("t",args)); 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 new file mode 100644 index 0000000000..846392c1ab --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/model/ColumnDefinition.java @@ -0,0 +1,84 @@ +/** + * Copyright © 2016-2017 European Support Limited. + */ +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 { + + private String keyspace; + private String table; + private String name; + private String type; + + public ColumnDefinition() { + } + + public ColumnDefinition(String keyspace, String table, String name, DataType type) { + this.keyspace = keyspace; + this.table = table; + this.name = name; + this.type = type.getName().toString(); + } + + public ColumnDefinition(Definition definition) { + this(definition.getKeyspace(), definition.getTable(), definition.getName(), definition.getType()); + } + + /** + * The name of the keyspace this column is part of. + * + * @return the name of the keyspace this column is part of. + */ + public String getKeyspace() { + return keyspace; + } + + /** + * Returns the name of the table this column is part of. + * + * @return the name of the table this column is part of. + */ + public String getTable() { + return table; + } + + /** + * Returns the name of the column. + * + * @return the name of the column. + */ + public String getName() { + return name; + } + + /** + * Returns the type of the column. + * + * @return the type of the column. + */ + public String getType() { + return type; + } + + @Override + public final int hashCode() { + return Arrays.hashCode(new Object[]{keyspace, table, name, type}); + } + + @Override + public final boolean equals(Object o) { + 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); + } +} 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 new file mode 100644 index 0000000000..155f35c006 --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/model/TableData.java @@ -0,0 +1,12 @@ +/** + * Copyright © 2016-2017 European Support Limited. + */ +package org.openecomp.core.tools.model; + +import java.util.ArrayList; +import java.util.List; + +public class TableData { + public List definitions = new ArrayList<>(); + public List> rows = new ArrayList<>(); +} diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/CassandraElementRepository.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/CassandraElementRepository.java index c41b46ea14..fcc67e11d0 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/CassandraElementRepository.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/CassandraElementRepository.java @@ -34,7 +34,12 @@ import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; import java.lang.reflect.Type; import java.nio.ByteBuffer; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; public class CassandraElementRepository { @@ -61,18 +66,18 @@ public class CassandraElementRepository { ElementEntity element) { Row row = getElementAccessor(context).get( elementContext.getSpace(), - elementContext.getItemId().toString(), + elementContext.getItemId().getValue(), getVersionId(elementContext), - element.getId().toString()).one(); + element.getId().getValue()).one(); return row == null ? Optional.empty() : Optional.of(getElementEntity(element, row)); } private String getVersionId(ElementEntityContext elementContext) { - return elementContext.getChangeRef() == null - ? elementContext.getVersionId().toString() - : elementContext.getChangeRef(); + return elementContext.getRevisionId() == null + ? elementContext.getVersionId().getValue() + : elementContext.getRevisionId().getValue(); } @@ -92,7 +97,7 @@ public class CassandraElementRepository { private void updateElement(SessionContext context, ElementEntityContext elementContext, ElementEntity element) { - if (elementContext.getChangeRef() == null) { + if (elementContext.getRevisionId() == null) { getElementAccessor(context).update( JsonUtil.object2Json(element.getInfo()), @@ -113,7 +118,7 @@ public class CassandraElementRepository { element.getVisualization(), elementContext.getSpace(), elementContext.getItemId().toString(), - elementContext.getChangeRef(), + elementContext.getRevisionId().getValue(), element.getId().toString()); } } @@ -154,7 +159,7 @@ public class CassandraElementRepository { getVersionId(elementContext)).one(); return row == null ? new HashSet<>() - : row.getSet(CassandraElementRepository.VersionElementsField.ELEMENT_IDS, String.class); + : row.getSet(VersionElementsField.ELEMENT_IDS, String.class); } /* diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ElementHandler.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ElementHandler.java index 5c72c95f49..d8929ea720 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ElementHandler.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ElementHandler.java @@ -2,7 +2,6 @@ package org.openecomp.core.tools.store; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; @@ -11,23 +10,17 @@ public class ElementHandler { private static final String GLOBAL_USER = "GLOBAL_USER"; public static void update(SessionContext context, - String itemId, String versionId, String changeRef, + String itemId, String versionId, String revisionId, ElementEntity elementEntity) { ElementEntityContext elementContext; CassandraElementRepository cassandraElementRepository = new CassandraElementRepository(); - if (changeRef == null) { + if (revisionId == null) { elementContext = new ElementEntityContext(GLOBAL_USER, new Id(itemId), - new Id(versionId)); + new Id(versionId)); - } else { - elementContext = new ElementEntityContext(GLOBAL_USER, new ElementContext(new Id(itemId), - new Id(versionId), - changeRef)); } - cassandraElementRepository.update(context, elementContext, elementEntity); - } } 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 new file mode 100644 index 0000000000..78bbdf069e --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/HealingHandler.java @@ -0,0 +1,54 @@ +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 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.ArrayList; + +/** + * 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(ArrayList healingEntities) { + healingEntities.forEach(healingEntity -> { + if (isHealingRecordExist(healingEntity)) { + accessor.updateFlag(healingEntity.getHealingFlag(), healingEntity.getSpace(), + healingEntity.getItemId(), healingEntity.getVersionId()); + } else { + accessor.create(healingEntity.getSpace(), healingEntity.getItemId(), + healingEntity.getVersionId(), healingEntity.getHealingFlag(), + healingEntity.getOldVersion()); + } + }); + } + + private boolean isHealingRecordExist(HealingEntity healingEntity) { + return accessor.getFlag(healingEntity.getSpace(), healingEntity.getItemId(), + healingEntity.getVersionId()).getAvailableWithoutFetching() == 1; + } + + @Accessor + interface HealingAccessor { + + @Query("SELECT healing_needed FROM healing WHERE space=? AND item_id=? AND version_id=?") + ResultSet getFlag(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); + } + +} \ No newline at end of file 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 851e92dcca..fd9dc25daa 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 @@ -20,6 +20,7 @@ package org.openecomp.core.tools.store; +import com.datastax.driver.core.ResultSet; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; @@ -60,6 +61,8 @@ public class VersionCassandraLoader { return accessor.getAll(); } + public ResultSet listItemVersion() { return accessor.getAllItemVersion();} + @Accessor interface VersionAccessor { @@ -74,5 +77,8 @@ public class VersionCassandraLoader { @Query("select * from zusammen_dox.version ") @QueryParameters(fetchSize = 400) Result getAll(); + + @Query("select space,item_id,version_id from zusammen_dox.version ") + ResultSet getAllItemVersion(); } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VspGeneralLoader.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VspGeneralLoader.java index 1d9d2d9774..b8620b8283 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VspGeneralLoader.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VspGeneralLoader.java @@ -4,14 +4,13 @@ import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import org.openecomp.core.zusammen.plugin.dao.impl.CassandraElementRepository; import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Objects; +import java.util.Optional; public class VspGeneralLoader { @@ -56,24 +55,24 @@ public class VspGeneralLoader { for (Map.Entry> entry : vspItemChangeRefssMap.entrySet()) { - for (String changeRef : entry.getValue()) { + for (String revisionId : entry.getValue()) { itemId = new Id(entry.getKey()); - entityId = getEntityIdByInfoNameValue(context, itemId, null, changeRef,null, NAME, + entityId = getEntityIdByInfoNameValue(context, itemId, null, revisionId,null, NAME, GENERAL); if (entityId != null) { ElementEntityContext elementContext = new ElementEntityContext( context.getUser().getUserName(), itemId, null); - elementContext.setChangeRef(changeRef); + elementContext.setRevisionId(new Id(revisionId)); Optional result = cassandraElementRepository.get(context, elementContext, new ElementEntity(entityId)); if (result.isPresent()) { - elementEntityMap.put(buildKey(context, entry, changeRef), result.get()); + elementEntityMap.put(buildKey(context, entry, revisionId), result.get()); } } } @@ -90,7 +89,7 @@ public class VspGeneralLoader { private static Id getEntityIdByInfoNameValue(SessionContext context, Id itemId, Id versionId, - String changeRef, + String revisionId, Id elementId, String name, String value) { @@ -100,8 +99,8 @@ public class VspGeneralLoader { context.getUser().getUserName(), itemId, versionId); - if (changeRef != null) { - elementContext.setChangeRef(changeRef); + if (revisionId != null) { + elementContext.setRevisionId(new Id(revisionId)); } Optional result = cassandraElementRepository.get(context, elementContext, @@ -113,8 +112,8 @@ public class VspGeneralLoader { context.getUser().getUserName(), itemId, versionId); - if(changeRef!= null){ - subElementContext.setChangeRef(changeRef); + if(revisionId!= null){ + subElementContext.setRevisionId(new Id(revisionId)); } Optional subElementEntityOptional = cassandraElementRepository.get(context, subElementContext, 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 new file mode 100644 index 0000000000..8c95f795a6 --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/HealingEntity.java @@ -0,0 +1,78 @@ +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; + +/** + * Created by ayalaben on 10/15/2017 + */ +@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 old_version; + + public String getSpace() { + return space; + } + + public void setSpace(String space) { + this.space = space; + } + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getVersionId() { + return versionId; + } + + public void setVersionId(String versionId) { + this.versionId = versionId; + } + + public boolean getHealingFlag() { + return healingFlag; + } + + public void setHealingFlag(boolean healingFlag) { + this.healingFlag = healingFlag; + } + + public HealingEntity(String space, String itemId, String versionId, boolean healingFlag,String + oldVersion) { + this.space = space; + this.itemId = itemId; + this.versionId = versionId; + this.healingFlag = healingFlag; + this.old_version = oldVersion; + } + + public String getOldVersion() { + return old_version; + } + + public void setOldVersion(String old_version) { + this.old_version = old_version; + } +} \ No newline at end of file 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 c7280c8a9d..946c05ef84 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 @@ -1,6 +1,8 @@ package org.openecomp.core.tools.store.zusammen.datatypes; -import com.datastax.driver.mapping.annotations.*; +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; 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 d1621ad672..f48b212327 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 @@ -3,13 +3,36 @@ 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 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); + } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/util/ZipUtils.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/util/ZipUtils.java index 2f6693d133..e0fd1a7535 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/util/ZipUtils.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/util/ZipUtils.java @@ -1,13 +1,17 @@ package org.openecomp.core.tools.util; import com.google.common.io.ByteStreams; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Objects; import java.util.Scanner; import java.util.Set; @@ -17,12 +21,23 @@ import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class ZipUtils { - public static void createZip(String zipFileName, Path dir, Set filterItem) throws Exception { + + private static final Logger logger = LoggerFactory.getLogger(ZipUtils.class); + + public static void createZip(String zipFileName, Path dir) throws IOException { File dirObj = dir.toFile(); + Path zippedFile = Files.createFile(Paths.get(zipFileName)); try ( - FileOutputStream fileOutputStream = new FileOutputStream(zipFileName); - ZipOutputStream out = new ZipOutputStream(fileOutputStream)) { - addDir(dirObj, out, dir.toString(), filterItem); + FileOutputStream fileOutputStream = new FileOutputStream(File.separator + zippedFile.toFile()); + BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream); + ZipOutputStream out = new ZipOutputStream(bos)) { + File[] files = dirObj.listFiles(); + for (File file : files) { + out.putNextEntry(new ZipEntry(file.getName())); + Files.copy(Paths.get(file.getPath()), out); + out.closeEntry(); + } + Utils.printMessage(logger, "Zip file was created " + zipFileName); } } @@ -47,7 +62,7 @@ public class ZipUtils { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { addDir(files[i], out, root, filterItem); - String filePath = files[i].getAbsolutePath().replace(root + File.separator, "") + "/"; + String filePath = files[i].getAbsolutePath().replace(root + File.separator, "") + File.separator; out.putNextEntry(new ZipEntry(filePath)); continue; } @@ -57,7 +72,6 @@ public class ZipUtils { out.putNextEntry(new ZipEntry(filePath)); try { ByteStreams.copy(in, out); - } finally { out.closeEntry(); } @@ -71,7 +85,7 @@ public class ZipUtils { if (zipFile == null || outputFolder == null) { return; } - if (!Files.exists(outputFolder)) { + if (!outputFolder.toFile().exists()) { Files.createDirectories(outputFolder); } @@ -83,7 +97,7 @@ public class ZipUtils { File newFile = new File(outputFolder.toString() + File.separator + fileName); if (ze.isDirectory()) { Path path = newFile.toPath(); - if (!Files.exists(path)) { + if (!path.toFile().exists()) { Files.createDirectories(path); } } else { diff --git a/openecomp-be/tools/zusammen-tools/src/main/resources/logback.xml b/openecomp-be/tools/zusammen-tools/src/main/resources/logback.xml index a13dc82e22..2461aed504 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/resources/logback.xml +++ b/openecomp-be/tools/zusammen-tools/src/main/resources/logback.xml @@ -1,5 +1,6 @@ + diff --git a/openecomp-be/tools/zusammen-tools/src/main/resources/queries.yaml b/openecomp-be/tools/zusammen-tools/src/main/resources/queries.yaml new file mode 100644 index 0000000000..a93a5a46e8 --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/main/resources/queries.yaml @@ -0,0 +1,16 @@ +queries: + - select * from zusammen_dox.element; + - select * from zusammen_dox.element_namespace; + - select * from zusammen_dox.item; + - select * from zusammen_dox.version; + - select * from zusammen_dox.version_elements; + - select * from dox.item_permissions; + - select * from dox.vsp_merge_hint ; +item_columns: + - item_id + - item_id + - item_id + - item_id + - item_id + - item_id + - item_id \ No newline at end of file diff --git a/openecomp-be/tools/zusammen-tools/src/test/java/org/openecomp/core/tools/Commands/exportinfo/serialize/VLMExtractTest.java b/openecomp-be/tools/zusammen-tools/src/test/java/org/openecomp/core/tools/Commands/exportinfo/serialize/VLMExtractTest.java new file mode 100644 index 0000000000..7b43c4624f --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/test/java/org/openecomp/core/tools/Commands/exportinfo/serialize/VLMExtractTest.java @@ -0,0 +1,48 @@ +package org.openecomp.core.tools.Commands.exportinfo.serialize; + +import org.openecomp.core.tools.exportinfo.ExportSerializer; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +public class VLMExtractTest { + + + + @Test + public void extractVLM(){ + String vlmId = "979a56c7b2fa41e6a5742137f53a5c1b"; + String elemenet_info_string = "{\n" + + " \"name\": \"VendorSoftwareProduct\",\n" + + " \"properties\": {\n" + + " \"subCategory\": \"resourceNewCategory.dcae component.collector\",\n" + + " \"name\": \"vsp1\",\n" + + " \"icon\": \"icon\",\n" + + " \"onboardingMethod\": \"NetworkPackage\",\n" + + " \"description\": \"d\",\n" + + " \"vendorId\": \""+vlmId+"\",\n" + + " \"category\": \"resourceNewCategory.dcae component\",\n" + + " \"vendorName\": \"vlm1\",\n" + + " \"elementType\": \"VendorSoftwareProduct\"\n" + + " }\n" + + "}\n" ; + String extractedVlmId = new CustomExportSerializer().extractVlm(elemenet_info_string); + assertNotNull(extractedVlmId); + assertEquals(extractedVlmId,vlmId); + + } + + @Test + public void failToExtractVLMBecauseJsonIsCorrupted(){ + String elemenet_info_string = "gfhhhghgh"; + String extractedVlmId = new CustomExportSerializer().extractVlm(elemenet_info_string); + assertNull(extractedVlmId); + } + + private static final class CustomExportSerializer extends ExportSerializer{ + public String extractVlm(String injson) { + return super.extractVlm(injson); + } + } +} diff --git a/openecomp-be/tools/zusammen-tools/src/test/resources/configuration.yaml b/openecomp-be/tools/zusammen-tools/src/test/resources/configuration.yaml new file mode 100644 index 0000000000..6636e20726 --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/test/resources/configuration.yaml @@ -0,0 +1,251 @@ +identificationHeaderFields: + - HTTP_IV_USER + - HTTP_CSP_FIRSTNAME + - HTTP_CSP_LASTNAME + - HTTP_IV_REMOTE_ADDRESS + - HTTP_CSP_WSTYPE + + + +# catalog backend http port +beHttpPort: 8080 + +# catalog backend http context +beContext: /sdc/rest/config/get + +# catalog backend protocol +beProtocol: http + +# catalog backend ssl port +beSslPort: 8443 + +version: 1.0 +released: 2012-11-30 + +titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties +titanInMemoryGraph: false +titanLockTimeout: 30 +titanReconnectIntervalInSeconds: 3 +titanHealthCheckReadTimeout: 1 +esReconnectIntervalInSeconds: 3 +uebHealthCheckReconnectIntervalInSeconds: 15 +uebHealthCheckReadTimeout: 4 + +# Protocols +protocols: + - http + - https + +# Users +users: + tom: passwd + bob: passwd + +neo4j: + host: neo4jhost + port: 7474 + user: neo4j + password: "12345" + +cassandraConfig: + cassandraHosts: ['localhost'] + reconnectTimeout : 30000 + authenticate: true + username: asdc_user + password: password + ssl: false + truststorePath : /path/path + truststorePassword : password + keySpaces: + - { name: dox, replicationStrategy: SimpleStrategy, replicationInfo: ['1']} + - { name: zusammen_dox, replicationStrategy: SimpleStrategy, replicationInfo: ['1']} + - { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']} + +#Application-specific settings of ES +elasticSearch: + # Mapping of index prefix to time-based frame. For example, if below is configured: + # + # - indexPrefix: auditingevents + # creationPeriod: minute + # + # then ES object of type which is mapped to "auditingevents-*" template, and created on 2015-12-23 13:24:54, will enter "auditingevents-2015-12-23-13-24" index. + # Another object created on 2015-12-23 13:25:54, will enter "auditingevents-2015-12-23-13-25" index. + # If creationPeriod: month, both of the above will enter "auditingevents-2015-12" index. + # + # PLEASE NOTE: the timestamps are created in UTC/GMT timezone! This is needed so that timestamps will be correctly presented in Kibana. + # + # Legal values for creationPeriod - year, month, day, hour, minute, none (meaning no time-based behaviour). + # + # If no creationPeriod is configured for indexPrefix, default behavour is creationPeriod: month. + + indicesTimeFrequency: + - indexPrefix: auditingevents + creationPeriod: month + - indexPrefix: monitoring_events + creationPeriod: month + +artifactTypes: + - CHEF + - PUPPET + - SHELL + - YANG + - YANG_XML + - HEAT + - BPEL + - DG_XML + - MURANO_PKG + - OTHER + +licenseTypes: + - User + - Installation + - CPU + +#Deployment artifacts placeHolder +deploymentResourceArtifacts: + heat: + displayName: "HEAT Template" + type: HEAT + +deploymentResourceInstanceArtifacts: + heatEnv: + displayName: "HEAT ENV" + type: HEAT_ENV + description: "Auto-generated HEAT Environment deployment artifact" + fileExtension: "env" + +#Informational artifacts placeHolder +excludeResourceCategory: + - Generic +informationalResourceArtifacts: + features: + displayName: Features + type: OTHER + capacity: + displayName: Capacity + type: OTHER + vendorTestResult: + displayName: Vendor Test Result + type: OTHER + testScripts: + displayName: Test Scripts + type: OTHER + cloudQuestionnaire: + displayName: Cloud Questionnaire (completed) + type: OTHER + HEATTemplateFromVendor: + displayName: HEAT Template from Vendor + type: HEAT + +excludeServiceCategory: + +informationalServiceArtifacts: + messageFlows: + displayName: Message Flows + type: OTHER + instantiationFlows: + displayName: Management Flows + type: OTHER + serviceArtifactPlan: + displayName: Service Artifact Plan + type: OTHER + summaryOfImpactsToECOMPElements: + displayName: Summary of impacts to OPENECOMP elements,OSSs, BSSs + type: OTHER + controlLoopFunctions: + displayName: Control Loop Functions + type: OTHER + dimensioningInfo: + displayName: Dimensioning Info + type: OTHER + affinityRules: + displayName: Affinity Rules + type: OTHER + operationalPolicies: + displayName: Operational Policies + type: OTHER + serviceSpecificPolicies: + displayName: Service-specific Policies + type: OTHER + engineeringRules: + displayName: Engineering Rules (ERD) + type: OTHER + distributionInstructions: + displayName: Distribution Instructions + type: OTHER + certificationTestResults: + displayName: TD Certification Test Results + type: OTHER + deploymentVotingRecord: + displayName: Deployment Voting Record + type: OTHER + serviceQuestionnaire: + displayName: Service Questionnaire + type: OTHER + +serviceApiArtifacts: + configuration: + displayName: Configuration + type: OTHER + instantiation: + displayName: Instantiation + type: OTHER + monitoring: + displayName: Monitoring + type: OTHER + reporting: + displayName: Reporting + type: OTHER + logging: + displayName: Logging + type: OTHER + testing: + displayName: Testing + type: OTHER + + +additionalInformationMaxNumberOfKeys: 50 + +systemMonitoring: + enabled: false + isProxy: false + probeIntervalInSeconds: 15 + +defaultHeatArtifactTimeoutMinutes: 60 + +serviceDeploymentArtifacts: + +resourceDeploymentArtifacts: + HEAT: + acceptedTypes: + - yaml + - yml + +resourceInformationalDeployedArtifacts: + YANG_XML: + acceptedTypes: + - xml + + +unLoggedUrls: + - /sdc2/rest/healthCheck + +cleanComponentsConfiguration: + cleanIntervalInMinutes: 1440 + componentsToClean: + - Resource + +artifactsIndex: resources + +heatEnvArtifactHeader: + " # _______________________________________________________________________________________________________________________________________\n + #| AT&T Proprietary (Restricted) |\n + #| Only for use by authorized individuals or any above-designated team(s) |\n + #| within the AT&T companies and not for general distribution |\n + #|_______________________________________________________________________________________________________________________________________|\n" +heatEnvArtifactFooter: + " # _______________________________________________________________________________________________________________________________________\n + #| AT&T Proprietary (Restricted) |\n + #| Only for use by authorized individuals or any above-designated team(s) |\n + #| within the AT&T companies and not for general distribution |\n + #|_______________________________________________________________________________________________________________________________________|\n" diff --git a/openecomp-be/tools/zusammen-tools/src/test/resources/queries.yaml b/openecomp-be/tools/zusammen-tools/src/test/resources/queries.yaml new file mode 100644 index 0000000000..6ca8cd6efe --- /dev/null +++ b/openecomp-be/tools/zusammen-tools/src/test/resources/queries.yaml @@ -0,0 +1,16 @@ +queries: + - select * from zusammen_dox.element; + - select * from zusammen_dox.element_namespace; + - select * from zusammen_dox.item; + - select * from zusammen_dox.version; + - select * from zusammen_dox.version_elements; + - select * from dox.item_permissions; + - select * from dox.vsp_merge_hint; +item_columns: + - item_id + - item_id + - item_id + - item_id + - item_id + - item_id + - item_id \ No newline at end of file diff --git a/openecomp-ui/.eslintrc b/openecomp-ui/.eslintrc index 63da329372..baa1391245 100644 --- a/openecomp-ui/.eslintrc +++ b/openecomp-ui/.eslintrc @@ -32,6 +32,7 @@ "DEV": true, "Blob": true, "XMLHttpRequest": true, + "WebSocket": true, "URL": true, "PunchOutRegistry": true, "it": true, diff --git a/openecomp-ui/devConfig.defaults.json b/openecomp-ui/devConfig.defaults.json index 99380b1e50..059d380618 100644 --- a/openecomp-ui/devConfig.defaults.json +++ b/openecomp-ui/devConfig.defaults.json @@ -1,6 +1,7 @@ { "port": 9000, "proxyCatalogTarget": null, + "proxyWebsocketTarget": null, "proxyTarget": null, "bundles": { "bundle": ["sdc-app/sdc.app.jsx"], diff --git a/openecomp-ui/gulpfile.js b/openecomp-ui/gulpfile.js index 6d45a0b374..8ca9a233aa 100644 --- a/openecomp-ui/gulpfile.js +++ b/openecomp-ui/gulpfile.js @@ -38,7 +38,7 @@ const path = { // output output: dist, css: dist + '/css', - svg: dist + '/resources/images/svg', +// svg: dist + '/resources/images/svg', appinf_output: dist + '/webapp-onboarding', healthCheckOutput: dist + '/v1.0', // war @@ -48,8 +48,8 @@ const path = { // storybook storybookFonts: './.storybook/fonts/*', storybookDist: './.storybook-dist', - storybookResources: './.storybook/resources/onboarding/resources/images/svg', - storybookDistResources: './.storybook-dist/onboarding/resources/images/svg' + //storybookResources: './.storybook/resources/onboarding/resources/images/svg', + //storybookDistResources: './.storybook-dist/onboarding/resources/images/svg' }; // cleans up the output directory taskMaker.defineTask('clean', {taskName: 'clean', src: path.output}); @@ -57,10 +57,10 @@ taskMaker.defineTask('clean', {taskName: 'clean', src: path.output}); taskMaker.defineTask('copy', {taskName: 'copy-json', src: path.json, dest: path.output, changed: {extension: '.json'}}); taskMaker.defineTask('copy', {taskName: 'copy-index.html', src: path.index, dest: path.output, rename: 'index.html'}); taskMaker.defineTask('copy', {taskName: 'copy-heat.html', src: path.heat, dest: path.output, rename: 'heat.html'}); -taskMaker.defineTask('copy', {taskName: 'copy-svg', src: path.svgSrc, dest: path.svg}); +//taskMaker.defineTask('copy', {taskName: 'copy-svg', src: path.svgSrc, dest: path.svg}); taskMaker.defineTask('copy', {taskName: 'copy-storybook-fonts', src: path.storybookFonts, dest: path.storybookDist}); -taskMaker.defineTask('copy', {taskName: 'copy-storybook-resources', src: path.svgSrc, dest: path.storybookResources}); -taskMaker.defineTask('copy', {taskName: 'copy-storybook-resources-prod', src: path.svgSrc, dest: path.storybookDistResources}); +//taskMaker.defineTask('copy', {taskName: 'copy-storybook-resources', src: path.svgSrc, dest: path.storybookResources}); +//taskMaker.defineTask('copy', {taskName: 'copy-storybook-resources-prod', src: path.svgSrc, dest: path.storybookDistResources}); // used for compressing war files taskMaker.defineTask('compress', {taskName: 'compress-war', src: path.war, filename: appName + '.war', dest: path.wardest}); taskMaker.defineTask('compress', {taskName: 'compress-heat-war', src: path.heatWar, filename: 'heat-validation.war', dest: path.wardest}); @@ -94,7 +94,7 @@ gulp.task('app-context', function(){ }) }); // aggregates all copy tasks -gulp.task('copy-stuff', callback => runSequence(['copy-json', 'copy-index.html', 'copy-heat.html', 'copy-svg', 'app-context'], callback)); +gulp.task('copy-stuff', callback => runSequence(['copy-json', 'copy-index.html', 'copy-heat.html', 'app-context'], callback)); // minimum build for dev gulp.task('dev', callback => runSequence('clean', 'copy-stuff', callback)); diff --git a/openecomp-ui/package.json b/openecomp-ui/package.json index 6e13e269d2..c3875ab5d0 100644 --- a/openecomp-ui/package.json +++ b/openecomp-ui/package.json @@ -14,14 +14,16 @@ "test-failedTestReport": "jest --json | node test-utils/failedTestReport.js", "test-dev": "jest --watch", "test-coverage": "jest --coverage && start ./coverage/lcov-report/index.html", - "storybook": "gulp copy-storybook-resources && start-storybook -p 9090 -c .storybook -s .storybook/resources,.storybook/fonts", + "test-build": "jest --coverage", + "storybook": "start-storybook -p 9090 -c .storybook -s .storybook/fonts", "storyshots": "jest storyshots.test.js", - "build-storybook": "build-storybook -c .storybook -o .storybook-dist && gulp copy-storybook-fonts && gulp copy-storybook-resources-prod" + "build-storybook": "build-storybook -c .storybook -o .storybook-dist && gulp copy-storybook-fonts" }, "dependencies": { + "attr-accept": "^1.1.0", "classnames": "^2.2.5", "core-js": "^2.4.0", - "d3": "^3.5.16", + "d3": "^4.9.1", "dox-sequence-diagram-ui": "file:../dox-sequence-diagram-ui", "intl": "^1.0.1", "intl-format-cache": "^2.0.5", @@ -29,17 +31,20 @@ "intl-relativeformat": "^1.2.0", "lodash": "^4.13.1", "md5": "^2.1.0", + "prop-types": "^15.6.0", "randomstring": "^1.1.5", "react": "~15.3.2", "react-bootstrap": "^0.30.1", + "react-click-outside": "^2.3.1", "react-dom": "~15.3.2", "react-dropzone": "3.7.3", "react-redux": "^4.4.1", "react-select": "1.0.0-rc.5", + "react-show-more": "^1.1.1", "react-sortable": "^1.2.0", "redux": "^3.3.1", "restful-js": "0.7.0", - "sdc-ui": "1.6.8", + "sdc-ui": "1.6.9", "uuid-js": "^0.7.5", "validator": "^4.3.0" }, @@ -76,7 +81,7 @@ "gulp-replace": "^0.5.4", "gulp-tap": "^1.0.1", "html-loader": "^0.4.3", - "http-proxy-middleware": "^0.8.2", + "http-proxy-middleware": "^0.17.4", "ignore-loader": "^0.1.1", "jasmine-core": "^2.5.2", "jest": "^19.0.2", @@ -88,6 +93,7 @@ "node-watch": "^0.3.5", "prompt": "^0.2.14", "react-addons-test-utils": "~15.3.2", + "react-click-outside": "^2.3.1", "react-datepicker": "^0.48.0", "react-hot-loader": "^1.3.1", "rosie": "^1.6.0", @@ -110,6 +116,7 @@ "\\.(css|scss)$": "/test-utils/styleMock.js", "^nfvo-utils/RestAPIUtil.js$": "/test-utils/MockRest.js", "^sdc-ui/lib/react/SVGIcon.js$": "/test-utils/MockSVGIcon.js", + "^react-show-more$": "/test-utils/ShowMore.js", "^nfvo-utils(.*)$": "/src/nfvo-utils$1", "^nfvo-components(.*)$": "/src/nfvo-components$1", "^sdc-app(.*)$": "/src/sdc-app$1", @@ -131,6 +138,10 @@ "collectCoverageFrom": [ "src/**/*.{js,jsx}" ], + "coveragePathIgnorePatterns": [ + "/node_modules/", + "(.)*.stories.js" + ], "coverageReporters": [ "lcov" ] diff --git a/openecomp-ui/pom.xml b/openecomp-ui/pom.xml index a5eaeef39a..df86ce7748 100644 --- a/openecomp-ui/pom.xml +++ b/openecomp-ui/pom.xml @@ -39,6 +39,9 @@ + + ${basedir}/coverage + ${basedir}/../dox-sequence-diagram-ui/dist @@ -141,6 +144,16 @@ run build -- --version=${project.version} + + ui test + + npm + + + run test-build + + test + diff --git a/openecomp-ui/resources/images/angle-left.svg b/openecomp-ui/resources/images/angle-left.svg deleted file mode 100644 index b2d2f81b3d..0000000000 --- a/openecomp-ui/resources/images/angle-left.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - diff --git a/openecomp-ui/resources/images/angle-right.svg b/openecomp-ui/resources/images/angle-right.svg deleted file mode 100644 index f8e6efc3a6..0000000000 --- a/openecomp-ui/resources/images/angle-right.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - diff --git a/openecomp-ui/resources/images/artifacts_icon.png b/openecomp-ui/resources/images/artifacts_icon.png deleted file mode 100644 index 584f78d33a..0000000000 Binary files a/openecomp-ui/resources/images/artifacts_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/base_icon.png b/openecomp-ui/resources/images/base_icon.png deleted file mode 100644 index 439a517e03..0000000000 Binary files a/openecomp-ui/resources/images/base_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/download_icon.png b/openecomp-ui/resources/images/download_icon.png deleted file mode 100644 index 307d0eff9e..0000000000 Binary files a/openecomp-ui/resources/images/download_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/ZIP_blue_icon.png b/openecomp-ui/resources/images/icons/ZIP_blue_icon.png deleted file mode 100644 index a36d2473fc..0000000000 Binary files a/openecomp-ui/resources/images/icons/ZIP_blue_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/ZIP_icon.png b/openecomp-ui/resources/images/icons/ZIP_icon.png deleted file mode 100644 index 82822d5727..0000000000 Binary files a/openecomp-ui/resources/images/icons/ZIP_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/artifacts_blue_icon.png b/openecomp-ui/resources/images/icons/artifacts_blue_icon.png deleted file mode 100644 index 46bc14884b..0000000000 Binary files a/openecomp-ui/resources/images/icons/artifacts_blue_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/artifacts_grey_icon.png b/openecomp-ui/resources/images/icons/artifacts_grey_icon.png deleted file mode 100644 index 6f3e8a2ebf..0000000000 Binary files a/openecomp-ui/resources/images/icons/artifacts_grey_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/back_icon.png b/openecomp-ui/resources/images/icons/back_icon.png deleted file mode 100644 index 305080a807..0000000000 Binary files a/openecomp-ui/resources/images/icons/back_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/checked_in.png b/openecomp-ui/resources/images/icons/checked_in.png deleted file mode 100644 index 44112ced13..0000000000 Binary files a/openecomp-ui/resources/images/icons/checked_in.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/checked_out.png b/openecomp-ui/resources/images/icons/checked_out.png deleted file mode 100644 index ac73c732bb..0000000000 Binary files a/openecomp-ui/resources/images/icons/checked_out.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/down_chevron.png b/openecomp-ui/resources/images/icons/down_chevron.png deleted file mode 100644 index 257f036646..0000000000 Binary files a/openecomp-ui/resources/images/icons/down_chevron.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/env_icon.png b/openecomp-ui/resources/images/icons/env_icon.png deleted file mode 100644 index 83d6852a14..0000000000 Binary files a/openecomp-ui/resources/images/icons/env_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/env_icon_blue.png b/openecomp-ui/resources/images/icons/env_icon_blue.png deleted file mode 100644 index bb30e26382..0000000000 Binary files a/openecomp-ui/resources/images/icons/env_icon_blue.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/error_icon_big.png b/openecomp-ui/resources/images/icons/error_icon_big.png deleted file mode 100644 index 35dfeb318c..0000000000 Binary files a/openecomp-ui/resources/images/icons/error_icon_big.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/error_icon_small.png b/openecomp-ui/resources/images/icons/error_icon_small.png deleted file mode 100644 index 059aa9b201..0000000000 Binary files a/openecomp-ui/resources/images/icons/error_icon_small.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/favicon.ico b/openecomp-ui/resources/images/icons/favicon.ico deleted file mode 100644 index c59a7aa0a3..0000000000 Binary files a/openecomp-ui/resources/images/icons/favicon.ico and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/favicon.png b/openecomp-ui/resources/images/icons/favicon.png deleted file mode 100644 index c59a7aa0a3..0000000000 Binary files a/openecomp-ui/resources/images/icons/favicon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/go_to_overview_disable_icon.png b/openecomp-ui/resources/images/icons/go_to_overview_disable_icon.png deleted file mode 100644 index 98bf1d92d8..0000000000 Binary files a/openecomp-ui/resources/images/icons/go_to_overview_disable_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/go_to_overview_icon.png b/openecomp-ui/resources/images/icons/go_to_overview_icon.png deleted file mode 100644 index e996377fec..0000000000 Binary files a/openecomp-ui/resources/images/icons/go_to_overview_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/nested_HEAT_icon_blue.png b/openecomp-ui/resources/images/icons/nested_HEAT_icon_blue.png deleted file mode 100644 index 21383bf4c1..0000000000 Binary files a/openecomp-ui/resources/images/icons/nested_HEAT_icon_blue.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/nested_heat_icon.png b/openecomp-ui/resources/images/icons/nested_heat_icon.png deleted file mode 100644 index beeaf20264..0000000000 Binary files a/openecomp-ui/resources/images/icons/nested_heat_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/network_blue_icon.png b/openecomp-ui/resources/images/icons/network_blue_icon.png deleted file mode 100644 index 5ed223d214..0000000000 Binary files a/openecomp-ui/resources/images/icons/network_blue_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/network_icon.png b/openecomp-ui/resources/images/icons/network_icon.png deleted file mode 100644 index ec0f9208e4..0000000000 Binary files a/openecomp-ui/resources/images/icons/network_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/orphans_blue_icon-n.png b/openecomp-ui/resources/images/icons/orphans_blue_icon-n.png deleted file mode 100644 index 64a5949a6a..0000000000 Binary files a/openecomp-ui/resources/images/icons/orphans_blue_icon-n.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/orphans_grey_icon.png b/openecomp-ui/resources/images/icons/orphans_grey_icon.png deleted file mode 100644 index f761ae71b8..0000000000 Binary files a/openecomp-ui/resources/images/icons/orphans_grey_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/others_blue_icon.png b/openecomp-ui/resources/images/icons/others_blue_icon.png deleted file mode 100644 index e3953151dd..0000000000 Binary files a/openecomp-ui/resources/images/icons/others_blue_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/others_icon.png b/openecomp-ui/resources/images/icons/others_icon.png deleted file mode 100644 index cc498053d2..0000000000 Binary files a/openecomp-ui/resources/images/icons/others_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/pencil_icon-01.svg b/openecomp-ui/resources/images/icons/pencil_icon-01.svg deleted file mode 100644 index 50e38aa6a2..0000000000 --- a/openecomp-ui/resources/images/icons/pencil_icon-01.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - diff --git a/openecomp-ui/resources/images/icons/plus_vlm_summary_disabled_icon.png b/openecomp-ui/resources/images/icons/plus_vlm_summary_disabled_icon.png deleted file mode 100644 index dcd8081e74..0000000000 Binary files a/openecomp-ui/resources/images/icons/plus_vlm_summary_disabled_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/plus_vlm_summary_icon.png b/openecomp-ui/resources/images/icons/plus_vlm_summary_icon.png deleted file mode 100644 index e50ce02a92..0000000000 Binary files a/openecomp-ui/resources/images/icons/plus_vlm_summary_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/plus_vlm_summary_icon_blue.png b/openecomp-ui/resources/images/icons/plus_vlm_summary_icon_blue.png deleted file mode 100644 index 09ecc4a2ea..0000000000 Binary files a/openecomp-ui/resources/images/icons/plus_vlm_summary_icon_blue.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/revert_icon_disabled.png b/openecomp-ui/resources/images/icons/revert_icon_disabled.png deleted file mode 100644 index e0f55de1fd..0000000000 Binary files a/openecomp-ui/resources/images/icons/revert_icon_disabled.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/reverticon.png b/openecomp-ui/resources/images/icons/reverticon.png deleted file mode 100644 index 813f036788..0000000000 Binary files a/openecomp-ui/resources/images/icons/reverticon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/save_icon_disable.png b/openecomp-ui/resources/images/icons/save_icon_disable.png deleted file mode 100644 index 5eb6513027..0000000000 Binary files a/openecomp-ui/resources/images/icons/save_icon_disable.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/saveicon.png b/openecomp-ui/resources/images/icons/saveicon.png deleted file mode 100644 index 64ada85cdb..0000000000 Binary files a/openecomp-ui/resources/images/icons/saveicon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/submit_icon_disable.png b/openecomp-ui/resources/images/icons/submit_icon_disable.png deleted file mode 100644 index ccb5775e8c..0000000000 Binary files a/openecomp-ui/resources/images/icons/submit_icon_disable.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/submiticonactive.png b/openecomp-ui/resources/images/icons/submiticonactive.png deleted file mode 100644 index d0d36a1870..0000000000 Binary files a/openecomp-ui/resources/images/icons/submiticonactive.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/vlm_list_view_blue_icon.png b/openecomp-ui/resources/images/icons/vlm_list_view_blue_icon.png deleted file mode 100644 index da2b5bb027..0000000000 Binary files a/openecomp-ui/resources/images/icons/vlm_list_view_blue_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/vlm_list_view_grey_icon.png b/openecomp-ui/resources/images/icons/vlm_list_view_grey_icon.png deleted file mode 100644 index 582cf8eab4..0000000000 Binary files a/openecomp-ui/resources/images/icons/vlm_list_view_grey_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/volume_blue_icon.png b/openecomp-ui/resources/images/icons/volume_blue_icon.png deleted file mode 100644 index 34e47ac97e..0000000000 Binary files a/openecomp-ui/resources/images/icons/volume_blue_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/volume_icon.png b/openecomp-ui/resources/images/icons/volume_icon.png deleted file mode 100644 index ca2a2f8fcc..0000000000 Binary files a/openecomp-ui/resources/images/icons/volume_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/warning_icon_big.png b/openecomp-ui/resources/images/icons/warning_icon_big.png deleted file mode 100644 index c44d24021e..0000000000 Binary files a/openecomp-ui/resources/images/icons/warning_icon_big.png and /dev/null differ diff --git a/openecomp-ui/resources/images/icons/warning_icon_small.png b/openecomp-ui/resources/images/icons/warning_icon_small.png deleted file mode 100644 index 1592ec5045..0000000000 Binary files a/openecomp-ui/resources/images/icons/warning_icon_small.png and /dev/null differ diff --git a/openecomp-ui/resources/images/module_icon.png b/openecomp-ui/resources/images/module_icon.png deleted file mode 100644 index fd71a747db..0000000000 Binary files a/openecomp-ui/resources/images/module_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/pencil_icon-01.svg b/openecomp-ui/resources/images/pencil_icon-01.svg deleted file mode 100644 index 50e38aa6a2..0000000000 --- a/openecomp-ui/resources/images/pencil_icon-01.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - diff --git a/openecomp-ui/resources/images/plus-circle-icon.svg b/openecomp-ui/resources/images/plus-circle-icon.svg deleted file mode 100644 index 352dcad5e8..0000000000 --- a/openecomp-ui/resources/images/plus-circle-icon.svg +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/angle-double-left.svg b/openecomp-ui/resources/images/svg/angle-double-left.svg deleted file mode 100644 index 9e1591a11d..0000000000 --- a/openecomp-ui/resources/images/svg/angle-double-left.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/angle-double-right.svg b/openecomp-ui/resources/images/svg/angle-double-right.svg deleted file mode 100644 index e77031aa70..0000000000 --- a/openecomp-ui/resources/images/svg/angle-double-right.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/angle-left.svg b/openecomp-ui/resources/images/svg/angle-left.svg deleted file mode 100644 index b2d2f81b3d..0000000000 --- a/openecomp-ui/resources/images/svg/angle-left.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - diff --git a/openecomp-ui/resources/images/svg/angle-right.svg b/openecomp-ui/resources/images/svg/angle-right.svg deleted file mode 100644 index f8e6efc3a6..0000000000 --- a/openecomp-ui/resources/images/svg/angle-right.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - diff --git a/openecomp-ui/resources/images/svg/back.svg b/openecomp-ui/resources/images/svg/back.svg deleted file mode 100644 index 287355fa95..0000000000 --- a/openecomp-ui/resources/images/svg/back.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - diff --git a/openecomp-ui/resources/images/svg/calendar.svg b/openecomp-ui/resources/images/svg/calendar.svg deleted file mode 100644 index 9c059024d5..0000000000 --- a/openecomp-ui/resources/images/svg/calendar.svg +++ /dev/null @@ -1 +0,0 @@ -Asset 1 \ No newline at end of file diff --git a/openecomp-ui/resources/images/svg/caret-down.svg b/openecomp-ui/resources/images/svg/caret-down.svg deleted file mode 100644 index cfd3c57eb1..0000000000 --- a/openecomp-ui/resources/images/svg/caret-down.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - diff --git a/openecomp-ui/resources/images/svg/check-circle.svg b/openecomp-ui/resources/images/svg/check-circle.svg deleted file mode 100644 index 313657e4a1..0000000000 --- a/openecomp-ui/resources/images/svg/check-circle.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/openecomp-ui/resources/images/svg/check.svg b/openecomp-ui/resources/images/svg/check.svg deleted file mode 100644 index 43d18814b1..0000000000 --- a/openecomp-ui/resources/images/svg/check.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - diff --git a/openecomp-ui/resources/images/svg/chevron-down.svg b/openecomp-ui/resources/images/svg/chevron-down.svg deleted file mode 100644 index 1ebd094459..0000000000 --- a/openecomp-ui/resources/images/svg/chevron-down.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - diff --git a/openecomp-ui/resources/images/svg/chevron-up.svg b/openecomp-ui/resources/images/svg/chevron-up.svg deleted file mode 100644 index 7fce935e14..0000000000 --- a/openecomp-ui/resources/images/svg/chevron-up.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - diff --git a/openecomp-ui/resources/images/svg/close.svg b/openecomp-ui/resources/images/svg/close.svg deleted file mode 100644 index 0decc7c2b6..0000000000 --- a/openecomp-ui/resources/images/svg/close.svg +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - diff --git a/openecomp-ui/resources/images/svg/error-circle.svg b/openecomp-ui/resources/images/svg/error-circle.svg deleted file mode 100644 index 8234753bd4..0000000000 --- a/openecomp-ui/resources/images/svg/error-circle.svg +++ /dev/null @@ -1 +0,0 @@ -Asset 4 \ No newline at end of file diff --git a/openecomp-ui/resources/images/svg/exclamation-triangle-full.svg b/openecomp-ui/resources/images/svg/exclamation-triangle-full.svg deleted file mode 100644 index 7cab121861..0000000000 --- a/openecomp-ui/resources/images/svg/exclamation-triangle-full.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - diff --git a/openecomp-ui/resources/images/svg/exclamation-triangle-line.svg b/openecomp-ui/resources/images/svg/exclamation-triangle-line.svg deleted file mode 100644 index eae682503d..0000000000 --- a/openecomp-ui/resources/images/svg/exclamation-triangle-line.svg +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/exclamation-triangle.svg b/openecomp-ui/resources/images/svg/exclamation-triangle.svg deleted file mode 100644 index 245661242a..0000000000 --- a/openecomp-ui/resources/images/svg/exclamation-triangle.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - diff --git a/openecomp-ui/resources/images/svg/filter.svg b/openecomp-ui/resources/images/svg/filter.svg deleted file mode 100644 index 1c493f4653..0000000000 --- a/openecomp-ui/resources/images/svg/filter.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - diff --git a/openecomp-ui/resources/images/svg/locked.svg b/openecomp-ui/resources/images/svg/locked.svg deleted file mode 100644 index 9785f8df11..0000000000 --- a/openecomp-ui/resources/images/svg/locked.svg +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/pencil.svg b/openecomp-ui/resources/images/svg/pencil.svg deleted file mode 100644 index 6701a3aba0..0000000000 --- a/openecomp-ui/resources/images/svg/pencil.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/plus-circle.svg b/openecomp-ui/resources/images/svg/plus-circle.svg deleted file mode 100644 index 9a0f023be7..0000000000 --- a/openecomp-ui/resources/images/svg/plus-circle.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/plus.svg b/openecomp-ui/resources/images/svg/plus.svg deleted file mode 100644 index 36f3486717..0000000000 --- a/openecomp-ui/resources/images/svg/plus.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/search.svg b/openecomp-ui/resources/images/svg/search.svg deleted file mode 100644 index ce8310429a..0000000000 --- a/openecomp-ui/resources/images/svg/search.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - diff --git a/openecomp-ui/resources/images/svg/sliders.svg b/openecomp-ui/resources/images/svg/sliders.svg deleted file mode 100644 index ade9de2435..0000000000 --- a/openecomp-ui/resources/images/svg/sliders.svg +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/trash-o.svg b/openecomp-ui/resources/images/svg/trash-o.svg deleted file mode 100644 index 26336f172f..0000000000 --- a/openecomp-ui/resources/images/svg/trash-o.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/unlocked.svg b/openecomp-ui/resources/images/svg/unlocked.svg deleted file mode 100644 index 6d94a94247..0000000000 --- a/openecomp-ui/resources/images/svg/unlocked.svg +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/vendor.svg b/openecomp-ui/resources/images/svg/vendor.svg deleted file mode 100644 index a3b8f5f0a3..0000000000 --- a/openecomp-ui/resources/images/svg/vendor.svg +++ /dev/null @@ -1 +0,0 @@ -vendor diff --git a/openecomp-ui/resources/images/svg/version-controller-lock-closed.svg b/openecomp-ui/resources/images/svg/version-controller-lock-closed.svg deleted file mode 100644 index 73aae7dbf2..0000000000 --- a/openecomp-ui/resources/images/svg/version-controller-lock-closed.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/version-controller-lock-open.svg b/openecomp-ui/resources/images/svg/version-controller-lock-open.svg deleted file mode 100644 index 52e0b8bf71..0000000000 --- a/openecomp-ui/resources/images/svg/version-controller-lock-open.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/version-controller-revert.svg b/openecomp-ui/resources/images/svg/version-controller-revert.svg deleted file mode 100644 index f9f02f94be..0000000000 --- a/openecomp-ui/resources/images/svg/version-controller-revert.svg +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - diff --git a/openecomp-ui/resources/images/svg/version-controller-save.svg b/openecomp-ui/resources/images/svg/version-controller-save.svg deleted file mode 100644 index 4a05425ed7..0000000000 --- a/openecomp-ui/resources/images/svg/version-controller-save.svg +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/version-controller-submit.svg b/openecomp-ui/resources/images/svg/version-controller-submit.svg deleted file mode 100644 index 9909ab3c6e..0000000000 --- a/openecomp-ui/resources/images/svg/version-controller-submit.svg +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - diff --git a/openecomp-ui/resources/images/svg/vlm.svg b/openecomp-ui/resources/images/svg/vlm.svg deleted file mode 100644 index 79b4625a09..0000000000 --- a/openecomp-ui/resources/images/svg/vlm.svg +++ /dev/null @@ -1 +0,0 @@ -vlm_new_icon \ No newline at end of file diff --git a/openecomp-ui/resources/images/svg/vsp.svg b/openecomp-ui/resources/images/svg/vsp.svg deleted file mode 100644 index 344755c2ab..0000000000 --- a/openecomp-ui/resources/images/svg/vsp.svg +++ /dev/null @@ -1 +0,0 @@ -vsp_new_icon diff --git a/openecomp-ui/resources/images/trash_icon.png b/openecomp-ui/resources/images/trash_icon.png deleted file mode 100644 index ebc17aef38..0000000000 Binary files a/openecomp-ui/resources/images/trash_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/upload_icon.png b/openecomp-ui/resources/images/upload_icon.png deleted file mode 100644 index 55f60f654e..0000000000 Binary files a/openecomp-ui/resources/images/upload_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/images/v_icon.png b/openecomp-ui/resources/images/v_icon.png deleted file mode 100644 index 387e3037fc..0000000000 Binary files a/openecomp-ui/resources/images/v_icon.png and /dev/null differ diff --git a/openecomp-ui/resources/scss/_components.scss b/openecomp-ui/resources/scss/_components.scss index 7c726aa8dd..7f73047c91 100644 --- a/openecomp-ui/resources/scss/_components.scss +++ b/openecomp-ui/resources/scss/_components.scss @@ -1,5 +1,4 @@ @import "components/punchOut"; -@import "components/buttons"; @import "components/forms"; @import "components/validationForm"; @import "components/dualListBox"; @@ -19,6 +18,10 @@ @import "components/activityLog"; @import "components/selectActionTable"; @import "components/datepicker"; +@import "components/tree"; +@import "components/commitModal"; +@import "components/userNotifications"; +@import "components/overlay"; %noselect { -webkit-touch-callout: none; @@ -70,10 +73,6 @@ } } -.warning-icon { - margin-left: 50%; - color: $yellow; -} .chevron::before { border-style: solid; diff --git a/openecomp-ui/resources/scss/_modules.scss b/openecomp-ui/resources/scss/_modules.scss index 405e91a61b..6fe6e30ab6 100644 --- a/openecomp-ui/resources/scss/_modules.scss +++ b/openecomp-ui/resources/scss/_modules.scss @@ -23,4 +23,8 @@ @import "modules/uploadScreen"; @import "modules/vspHeatSetup"; @import "modules/softwareProductDependencies"; +@import "modules/_permissions.scss"; +@import "modules/_revisions.scss"; @import "modules/softwareProductDeployment"; +@import "modules/versionsPage"; +@import "modules/mergeEditor"; diff --git a/openecomp-ui/resources/scss/bootstrap-cust/_buttons.scss b/openecomp-ui/resources/scss/bootstrap-cust/_buttons.scss deleted file mode 100644 index bf58006d89..0000000000 --- a/openecomp-ui/resources/scss/bootstrap-cust/_buttons.scss +++ /dev/null @@ -1,13 +0,0 @@ - -.btn { - height: 30px; - min-width: 95px; -} - -.btn-default .fa { - color: $brand-primary; -} - -.btn-info { - @include button-variant($text-black, $tlv-gray, $light-gray); -} diff --git a/openecomp-ui/resources/scss/bootstrap-cust/_forms.scss b/openecomp-ui/resources/scss/bootstrap-cust/_forms.scss index 60fd7ab07d..4ec2341011 100644 --- a/openecomp-ui/resources/scss/bootstrap-cust/_forms.scss +++ b/openecomp-ui/resources/scss/bootstrap-cust/_forms.scss @@ -1,6 +1,7 @@ .form-group { .control-label { @extend .body-2-semibold; + font-weight: normal; } &.required { label:before { @@ -28,6 +29,15 @@ label { margin-bottom: 8px; } +.sdc-radio { + label { + font-weight: normal; + margin-bottom: 0; + } + input[type="radio"] { + margin: 0; + } +} select.form-control { display: block; width: 215px; @@ -37,7 +47,7 @@ select[multiple] { background: none; } -input[type="radio"], input[type="checkbox"] { +input[type="checkbox"] { margin: 0; &:before { @@ -77,14 +87,6 @@ input[type="radio"], input[type="checkbox"] { border-radius: 2px; } -input[type=radio]:checked:before { - content: "\2022"; - color: $blue; - font-size: 30px; - text-align: center; - line-height: 11px; - font-family: $radio-font-family; -} input[type=checkbox]:checked:before { font-family: $icon-font-family; diff --git a/openecomp-ui/resources/scss/bootstrap-cust/_modals.scss b/openecomp-ui/resources/scss/bootstrap-cust/_modals.scss index ad6b4f8aca..1f132043ab 100644 --- a/openecomp-ui/resources/scss/bootstrap-cust/_modals.scss +++ b/openecomp-ui/resources/scss/bootstrap-cust/_modals.scss @@ -11,9 +11,13 @@ padding: 0; .validation-form-content { padding: 50px; + padding-bottom: 30px; overflow-y: auto; max-height: 490px; } + .validation-buttons { + padding-right: 50px; + } } .modal-footer { diff --git a/openecomp-ui/resources/scss/bootstrap-cust/_navbar.scss b/openecomp-ui/resources/scss/bootstrap-cust/_navbar.scss deleted file mode 100644 index acf2024b56..0000000000 --- a/openecomp-ui/resources/scss/bootstrap-cust/_navbar.scss +++ /dev/null @@ -1,3 +0,0 @@ -.navbar { - border: none; -} diff --git a/openecomp-ui/resources/scss/bootstrap-cust/_navs.scss b/openecomp-ui/resources/scss/bootstrap-cust/_navs.scss deleted file mode 100644 index 914a7794f1..0000000000 --- a/openecomp-ui/resources/scss/bootstrap-cust/_navs.scss +++ /dev/null @@ -1,30 +0,0 @@ -.nav { - > li { - > a { - padding: 10px 10px 3px; - } - } -} - -.nav-tabs { - @include box-shadow(0px 2px 1px -1px $gray); - padding: 0 28px; - - > li { - @extend .body-1; - - > a { - color: $dark-gray; - text-transform: uppercase; - } - - &.active > a { - &, - &:hover, - &:focus { - @extend .body-1-semibold; - border-bottom: 3px solid $blue; - } - } - } -} diff --git a/openecomp-ui/resources/scss/bootstrap.scss b/openecomp-ui/resources/scss/bootstrap.scss index 777f490a89..32890b35f0 100644 --- a/openecomp-ui/resources/scss/bootstrap.scss +++ b/openecomp-ui/resources/scss/bootstrap.scss @@ -20,18 +20,12 @@ @import "bootstrap-cust/tables"; @import "bootstrap/forms"; @import "bootstrap-cust/forms"; -//@import "bootstrap/buttons"; -//@import "bootstrap-cust/buttons"; // Components @import "bootstrap/component-animations"; @import "bootstrap/dropdowns"; @import "bootstrap-cust/dropdowns"; @import "bootstrap/button-groups"; @import "bootstrap/input-groups"; -@import "bootstrap/navs"; -@import "bootstrap-cust/navs"; -@import "bootstrap/navbar"; -@import "bootstrap-cust/navbar"; @import "bootstrap/breadcrumbs"; @import "bootstrap/pagination"; @import "bootstrap/pager"; diff --git a/openecomp-ui/resources/scss/bootstrap/_button-groups.scss b/openecomp-ui/resources/scss/bootstrap/_button-groups.scss index dc2906e44f..14ee0d348c 100644 --- a/openecomp-ui/resources/scss/bootstrap/_button-groups.scss +++ b/openecomp-ui/resources/scss/bootstrap/_button-groups.scss @@ -92,21 +92,9 @@ outline: 0; } -// Sizing -// -// Remix the default button sizing classes into new ones for easier manipulation. -.btn-group-xs > .btn { - @extend .btn-xs; -} -.btn-group-sm > .btn { - @extend .btn-sm; -} -.btn-group-lg > .btn { - @extend .btn-lg; -} // Split button dropdowns // ---------------------- diff --git a/openecomp-ui/resources/scss/common/_base.scss b/openecomp-ui/resources/scss/common/_base.scss index e901db000e..ff3a830e6b 100644 --- a/openecomp-ui/resources/scss/common/_base.scss +++ b/openecomp-ui/resources/scss/common/_base.scss @@ -11,10 +11,14 @@ body { @extend %noselect; } +$scrollbar-width: 8px; +$scrollbar-height: 8px; +/* firefox */ +$ff-scrollbar-width: 17px; /* scrollbar styling for Google Chrome | Safari | Opera */ ::-webkit-scrollbar { - width: 8px; - height: 8px; + width: $scrollbar-width; + height: $scrollbar-height; } ::-webkit-scrollbar-track { diff --git a/openecomp-ui/resources/scss/common/_layout.scss b/openecomp-ui/resources/scss/common/_layout.scss index dc2a33ccc7..6c6a0cf165 100644 --- a/openecomp-ui/resources/scss/common/_layout.scss +++ b/openecomp-ui/resources/scss/common/_layout.scss @@ -26,4 +26,10 @@ .modal-title { text-transform: uppercase; } -} \ No newline at end of file +} +.page-title { + @extend .heading-1; + @extend .text-uppercase !optional; + margin-bottom: 20px; + color: $blue; +} diff --git a/openecomp-ui/resources/scss/common/_typography.scss b/openecomp-ui/resources/scss/common/_typography.scss index 95d6d88595..c4ae856b5f 100644 --- a/openecomp-ui/resources/scss/common/_typography.scss +++ b/openecomp-ui/resources/scss/common/_typography.scss @@ -31,9 +31,9 @@ $body-font-2: 13px; $body-font-3: 12px; $body-font-4: 10px; -$icon-font-size: 11px; +$icon-font-size: 10px; $icon-font-family: Arial; -$radio-font-family: Arial; + .heading-1 { @include base-font-light; @@ -133,10 +133,6 @@ $radio-font-family: Arial; font-size: $body-font-3; } -.circle-icon-text { - @include base-font-semibold; - font-size: $body-font-1; -} .warning-text { color: $yellow; diff --git a/openecomp-ui/resources/scss/common/_utils.scss b/openecomp-ui/resources/scss/common/_utils.scss index 88a9ece7a8..99b1ff5d9a 100644 --- a/openecomp-ui/resources/scss/common/_utils.scss +++ b/openecomp-ui/resources/scss/common/_utils.scss @@ -118,7 +118,6 @@ $browserPrefixes: webkit moz o ms; max-height: $lineHeight * $lineCount; text-align: justify; word-break: break-all; - white-space: nowrap; // margin-right: -1em; padding-right: 1em; &:before { @@ -215,7 +214,7 @@ $browserPrefixes: webkit moz o ms; } } -@mixin create-circle($size, $bgcolor, $content) { +@mixin create-circle($size, $bgcolor) { border-radius: 50%; width: $size; height: $size; diff --git a/openecomp-ui/resources/scss/common/_variables.scss b/openecomp-ui/resources/scss/common/_variables.scss index 3a3178c6b0..5125b652ea 100644 --- a/openecomp-ui/resources/scss/common/_variables.scss +++ b/openecomp-ui/resources/scss/common/_variables.scss @@ -21,12 +21,10 @@ $white: #ffffff; $red: #cf2a2a; $crimson: #a94442; -$background-alice-blue: #e5f5fb; $background-gray: #f2f2f2; $text-black: #191919; $link-blue: #056bae; $functional-green: #007a3e; -$functional-yellow: #ffb81c; $tlv-gray: #f8f8f8; $tlv-light-gray: #eaeaea; $tlv-hover: #e6f6fb; @@ -34,7 +32,7 @@ $highlight-gray: #eceff3; $content-background-color: $white; -$scroll-bar-color: $text-black;//$light-gray; +$scroll-bar-color: $text-black; $vc-status-text-color: #42b72a; // sizes @@ -45,72 +43,8 @@ $tablet-max-width: 1024px; $laptop-min-width: 1224px; $desktop-min-width: 1824px; -/* Textures */ -$images-folder-name: "../images"; -/* -$plus-circle-icon: $images-folder-name + "/plus-circle-icon.svg"; -$interface-icon: $images-folder-name + "/interface.svg"; -$sdc-logo: $images-folder-name + "/logo.svg"; -$warning-icon: $images-folder-name + "/warning.svg"; -*/ -/* Icons */ -$icons-folder: "../images/icons"; -/* -$plus-circle-icon: $images-folder-name + "/plus-circle-icon.svg"; -$interface-icon: $images-folder-name + "/interface.svg"; -$sdc-logo: $images-folder-name + "/logo.svg"; -$warning-icon: $images-folder-name + "/warning.svg"; -*/ -$pencil-icon: $images-folder-name + "/pencil_icon-01.svg"; -/* -$vc-check-in-icon: $icons-folder + "/checked_in.png"; -$vc-checkout-icon: $icons-folder + "/checked_out.png"; -$vc-revert-icon: $icons-folder + "/reverticon.png"; -$vc-revert-disabled-icon: $icons-folder + "/revert_icon_disabled.png"; -$vc-save-icon: $icons-folder + "/saveicon.png"; -$vc-save-disabled-icon: $icons-folder + "/save_icon_disable.png"; -$vc-submit-icon: $icons-folder + "/submiticonactive.png"; -$vc-submit-disabled-icon: $icons-folder + "/submit_icon_disable.png"; -$trash-icon: $images-folder-name + "/trash_icon.png"; -$download-icon: $images-folder-name + "/download_icon.png"; -$upload-icon: $images-folder-name + "/upload_icon.png"; -*/ -/***** -// catalog icons -$back-icon: $icons-folder + "/back_icon.png"; -// validation icons -$artifacts-selected-icon: $icons-folder + "/artifacts_blue_icon.png"; -$artifacts-regular-icon: $icons-folder + "/artifacts_grey_icon.png"; -$chevron_down: $icons-folder + "/down_chevron.png"; -$error-icon-lg: $icons-folder + "/error_icon_big.png"; -$error-icon-sm: $icons-folder + "/error_icon_small.png"; -$go-to-overview-icon: $icons-folder + "/go_to_overview_icon.png"; -$go-to-overview-disabled-icon: $icons-folder + "/go_to_overview_disable_icon.png"; -$network-selected-icon: $icons-folder + "/network_blue_icon.png"; -$network-icon: $icons-folder + "/network_icon.png"; -$others-selected-icon: $icons-folder + "/others_blue_icon.png"; -$others-icon: $icons-folder + "/others_icon.png"; -$volume-selected-icon: $icons-folder + "/volume_blue_icon.png"; -$volume-icon: $icons-folder + "/volume_icon.png"; -$warning-icon-lg: $icons-folder + "/warning_icon_big.png"; -$warning-icon-sm: $icons-folder + "/warning_icon_small.png"; -$zip-icon: $icons-folder + "/ZIP_icon.png"; -$zip-selected-icon: $icons-folder + "/ZIP_blue_icon.png"; -$heat-icon: $icons-folder + "/nested_heat_icon.png"; -$heat-selected-icon: $icons-folder + "/nested_HEAT_icon_blue.png"; -$env-icon: $icons-folder + "/env_icon.png"; -$env-selected-icon: $icons-folder + "/env_icon_blue.png"; -// vlm summary icons -$vlm-summary-plus-blue: $icons-folder + "/plus_vlm_summary_icon_blue.png"; -$vlm-summary-plus: $icons-folder + "/plus_vlm_summary_icon.png"; -$vlm-summary-plus-disabled: $icons-folder + "/plus_vlm_summary_disabled_icon.png"; -$vlm-summary-orphans: $icons-folder + "/orphans_grey_icon.png"; -$vlm-summary-orphans-blue: $icons-folder + "/orphans_blue_icon-n.png"; -$vlm-summary-used: $icons-folder + "/vlm_list_view_grey_icon.png"; -$vlm-summary-used-blue: $icons-folder + "/vlm_list_view_blue_icon.png"; -*****/ diff --git a/openecomp-ui/resources/scss/components/_activityLog.scss b/openecomp-ui/resources/scss/components/_activityLog.scss index 5e9418ed7d..7a5b77b58c 100644 --- a/openecomp-ui/resources/scss/components/_activityLog.scss +++ b/openecomp-ui/resources/scss/components/_activityLog.scss @@ -23,6 +23,7 @@ $message-info-icon-size: 16px; .list-editor-view-list { border: 1px solid $light-gray; border-bottom: none; + overflow-y: hidden; } .activity-list-item { display: flex; diff --git a/openecomp-ui/resources/scss/components/_buttons.scss b/openecomp-ui/resources/scss/components/_buttons.scss deleted file mode 100644 index 357a799e93..0000000000 --- a/openecomp-ui/resources/scss/components/_buttons.scss +++ /dev/null @@ -1,30 +0,0 @@ -.primary-btn{ - border: 1px solid; - border-color: $blue; - color: $blue; - @extend .body-1-semibold; - text-align: center; - padding: 7px; - border-radius: 5px; - cursor: pointer; - align-self: center; - background-color: $white; - .primary-btn-text { - width: 100%; - } - &:hover { - color: $blue; - border-color: $blue; - background-color: $tlv-hover; - &:active { - color: $blue; - border-color: $blue; - } - } - - &:focus:not(:hover) { - color: $blue; - border-color: $blue; - background-color: $white; - } -} diff --git a/openecomp-ui/resources/scss/components/_commitModal.scss b/openecomp-ui/resources/scss/components/_commitModal.scss new file mode 100644 index 0000000000..e7f5d28933 --- /dev/null +++ b/openecomp-ui/resources/scss/components/_commitModal.scss @@ -0,0 +1,10 @@ + +.comment-commit-form { + .commit-modal-text { + padding-bottom: 30px; + } + .validation-buttons .sdc-button-default{ + min-width: 94px; + width: auto; + } +} \ No newline at end of file diff --git a/openecomp-ui/resources/scss/components/_dropzone.scss b/openecomp-ui/resources/scss/components/_dropzone.scss index cad752d415..2479ae7f0c 100644 --- a/openecomp-ui/resources/scss/components/_dropzone.scss +++ b/openecomp-ui/resources/scss/components/_dropzone.scss @@ -6,3 +6,26 @@ opacity: 0.5; } } +.file-upload-box { + @extend .body-1; + display: flex; + text-align: center; + flex-direction: column; + justify-content: center; + border: 2px dashed $light-gray; + padding-top: 20px; + padding-bottom: 20px; + width: 382px; + align-items: center; + .upload-btn { + padding: 4px 20px; + } + .drag-text { + color: $blue; + @extend .body-1-semibold; + } + .or-text { + margin-top: 10px; + margin-bottom: 10px; + } +} diff --git a/openecomp-ui/resources/scss/components/_dualListBox.scss b/openecomp-ui/resources/scss/components/_dualListBox.scss index 4353ab39e8..0c7d82e31c 100644 --- a/openecomp-ui/resources/scss/components/_dualListBox.scss +++ b/openecomp-ui/resources/scss/components/_dualListBox.scss @@ -8,10 +8,7 @@ .dual-search-multi-select-section { flex: 1; - .dual-text-box-search-title, .dual-list-box-multi-select-text { - @extend .body-1; - color: $dark-gray; - } + .dual-text-box-search { margin: 5px 0 30px 0; } @@ -30,6 +27,9 @@ padding: 4px 0 4px 10px; } } + option:checked { + background: $blue linear-gradient(0deg, $blue 0%, $blue 100%); + } } } .dual-list-options-bar { diff --git a/openecomp-ui/resources/scss/components/_forms.scss b/openecomp-ui/resources/scss/components/_forms.scss index b662ce873c..58e843047f 100644 --- a/openecomp-ui/resources/scss/components/_forms.scss +++ b/openecomp-ui/resources/scss/components/_forms.scss @@ -1,8 +1,8 @@ .section-title { @extend .heading-3-semibold; - padding: 50px 0 30px 0; + padding: 50px 0 20px 0; &:first-child { - padding: 0 0 30px 0; + padding-top: 0; } } diff --git a/openecomp-ui/resources/scss/components/_grid.scss b/openecomp-ui/resources/scss/components/_grid.scss index 9a76f97546..f210b64df6 100644 --- a/openecomp-ui/resources/scss/components/_grid.scss +++ b/openecomp-ui/resources/scss/components/_grid.scss @@ -1,66 +1,71 @@ -$gridItemSpace: 15%; - .grid-section { - &:not(:last-of-type) { - padding-bottom: 30px; - } - .grid-items { - display: flex; - flex-direction: row; - flex-wrap: wrap; - } - - %grid-col-base { - flex-shrink: 0; - display: flex; - } - - .grid-item { - flex: 1; - display: flex; - flex-direction: column; - } - - .grid-item-stretch { - @extend .grid-item; - & *:last-child { - flex: 1; - display: flex; - flex-direction: column; - } - } + $gridItemSpace: 15%; - .grid-col-1 { - @extend %grid-col-base; - flex-basis: 25%; - &:after { - flex-basis: $gridItemSpace; + @mixin gridCol($numOfCols, $flexBasis) { + .#{grid-col- + $numOfCols} { + @extend %grid-col-base; + flex-basis: $flexBasis; + &:not(.last-col-in-row):after { + flex-basis: $gridItemSpace / $numOfCols; content: ' '; } - } + } + } - .grid-col-2 { - @extend %grid-col-base; - flex-basis: 50%; - &:after { - flex-basis: $gridItemSpace / 2; - content: ' '; - } - } - .grid-col-3 { - @extend %grid-col-base; - flex-basis: 75%; - &:after { - flex-basis: $gridItemSpace / 3; - content: ' '; + @mixin gridColWithLastColumn($numOfCols, $flexBasis, $flexBasisLast) { + .#{grid-col- + $numOfCols} { + @extend %grid-col-base; + &:not(.last-col-in-row) { + flex-basis: $flexBasis; + margin-right: 5%; } - } - .grid-col-4 { - @extend %grid-col-base; - flex-basis: 100%; - &:after { - flex-basis: $gridItemSpace / 4; - content: ' '; + &.last-col-in-row { + flex-basis: $flexBasisLast; } - } + } + } + + &:not(:last-of-type) { + padding-bottom: 30px; + } + + .grid-items { + display: flex; + flex-direction: row; + flex-wrap: wrap; + } + + %grid-col-base { + flex-shrink: 0; + display: flex; + } + + .grid-item { + flex: 1; + display: flex; + flex-direction: column; + } + + .grid-item-stretch { + @extend .grid-item; + & *:last-child { + flex: 1; + display: flex; + flex-direction: column; + } + } + + &.has-last-col-set { + @include gridColWithLastColumn(1, 21%, 22%); + @include gridColWithLastColumn(2, 47%, 48%); + @include gridColWithLastColumn(3, 73%, 74%); + @include gridColWithLastColumn(4, 100%, 100%); + } + + &:not(.has-last-col-set) { + @include gridCol(1, 25%); + @include gridCol(2, 50%); + @include gridCol(3, 75%); + @include gridCol(4, 100%); + } } diff --git a/openecomp-ui/resources/scss/components/_icon.scss b/openecomp-ui/resources/scss/components/_icon.scss deleted file mode 100644 index c80055d055..0000000000 --- a/openecomp-ui/resources/scss/components/_icon.scss +++ /dev/null @@ -1,164 +0,0 @@ -$image-icon-normal-size: 20px; - -.icon-component { - display: inline-flex; - align-items: center; - - &.clickable:hover { - cursor: pointer; - } - .icon-label { - color: $blue; - } - &.disabled { - .icon-label { - color: $tlv-light-gray; - opacity: 0.7; - } - } - .icon { - width: $image-icon-normal-size; - height: $image-icon-normal-size; - margin: 0 6px; - background-repeat: no-repeat; - - &.trash { - background-image: url($trash-icon); - } - - &.artifacts { - background-image: url($artifacts-icon); - } - - &.base { - background-image: url($base-module-icon); - } - - &.module { - background-image: url($module-icon); - } - - &.pencil { - background-image: url($pencil-icon); - } - - &.check { - background-image: url($check-icon); - width: 30px; - height: 30px; - } - - &.download { - background-image: url($download-icon); - width: 16px; - height: 14px; - } - - &.upload { - background-image: url($upload-icon); - width: 16px; - height: 14px; - } - &.validation-artifacts { - width: 13px; - height: 17px; - position: relative; - top: 3px; - background-image: url($artifacts-regular-icon); - &.selected { - background-image: url($artifacts-selected-icon); - } - } - &.network { - background-image: url($network-icon); - width: 12px; - height: 12px; - &.selected { - background-image: url($network-selected-icon); - } - } - &.validation-other { - background-image: url($others-icon); - width: 12px; - height: 12px; - &.selected { - background-image: url($others-selected-icon); - } - } - &.volume { - width: 15px; - height: 16px; - background-image: url($volume-icon); - &.selected { - background-image: url($volume-selected-icon); - } - } - &.zip { - background-image: url($zip-icon); - height: 23px; - width: 29px; - &.selected { - background-image: url($zip-selected-icon); - } - } - &.heat { - background-image: url($heat-icon); - height: 14px; - width: 16px; - &.selected { - background-image: url($heat-selected-icon); - } - } - &.env { - background-image: url($env-icon); - height: 15px; - width: 16px; - &.selected { - background-image: url($env-selected-icon); - } - } - &.error { - width: 14px; - min-width: 14px; - height: 14px; - background-image: url($error-icon-sm); - } - &.warning { - height: 13px; - width: 15px; - min-width: 15px; - background-image: url($warning-icon-sm); - } - &.error-lg { - width: 17px; - min-width: 17px; - height: 17px; - background-image: url($error-icon-lg); - } - &.warning-lg { - width: 19px; - min-width: 19px; - height: 17px; - background-image: url($warning-icon-lg); - } - &.chevron-up { - background-image: url($chevron_down); - transform: rotate(180deg); - height: 7px; - width: 11px; - } - &.chevron-down { - background-image: url($chevron_down); - height: 7px; - width: 11px; - } - &.go-to-overview { - background-image: url($go-to-overview-icon); - height: 15px; - width: 18px; - &.disabled { - background-image: url($go-to-overview-disabled-icon); - } - } - } -} diff --git a/openecomp-ui/resources/scss/components/_listEditorView.scss b/openecomp-ui/resources/scss/components/_listEditorView.scss index c3e9fa6081..354a6a1f70 100644 --- a/openecomp-ui/resources/scss/components/_listEditorView.scss +++ b/openecomp-ui/resources/scss/components/_listEditorView.scss @@ -17,27 +17,6 @@ .list-editor-view-title { @extend .heading-3-semibold; } - .list-editor-view-add-controller { - @extend .body-1-semibold; - color: $blue; - display: table; - cursor: pointer; - position: relative; - padding-top: 0; - padding-bottom: 0; - margin-left: auto; - .list-editor-view-add-title { - display: flex; - } - span { - display: table-cell; - vertical-align: middle; - margin-top:4px; - &:nth-child(2) { - padding-left: 10px; - } - } - } } .list-editor-view-list-scroller { @@ -68,9 +47,6 @@ overflow-wrap: break-word; white-space: initial; - .description { - @include multiline-ellipsis(1.3em, 3); - } .number-field { align-content: center; @@ -82,6 +58,9 @@ line-height: 0.9; } } + .description { + @include multiline-ellipsis(1.3em, 3); + } .text { @extend .body-1; } @@ -105,9 +84,8 @@ } } .svg-icon { + margin-top: 5px; transition: fill .3s; - height: 18px; - width: 18px; fill: $white; } } diff --git a/openecomp-ui/resources/scss/components/_navigationSideBar.scss b/openecomp-ui/resources/scss/components/_navigationSideBar.scss index daf5025bee..ab4d15fd90 100644 --- a/openecomp-ui/resources/scss/components/_navigationSideBar.scss +++ b/openecomp-ui/resources/scss/components/_navigationSideBar.scss @@ -18,9 +18,10 @@ .group-name { @extend .heading-4-semibold; @include ellipsis; - min-height: 56px; + min-height: 70px; display: block; - padding: 18px 12px 13px 40px; + height: 70px; + padding: 24px 12px 13px 40px; background-color: $white; border-bottom: 1px solid $tlv-light-gray; } diff --git a/openecomp-ui/resources/scss/components/_overlay.scss b/openecomp-ui/resources/scss/components/_overlay.scss new file mode 100644 index 0000000000..7c310bf1a6 --- /dev/null +++ b/openecomp-ui/resources/scss/components/_overlay.scss @@ -0,0 +1,26 @@ +.onboarding-overlay { + z-index: 1000; + border: 1px solid $light-gray; + position: absolute; + background-color: $white; + border-radius: 2px; + box-shadow: 0 3px 7px 1px rgba(0, 0, 0, 0.2); + display: flex; + flex-direction: column; + justify-content: space-around; + margin-top: 5px; + margin-left: -86px; + .arrow-up { + width: 0; + height: 0; + border-left: 5px solid transparent; + border-right: 5px solid transparent; + background-color: transparent; + border-bottom: 5px solid $blue; + margin-left: 114px; + margin-top: -5px; + } + .arrow-border { + border-top: 5px solid $blue; + } +} \ No newline at end of file diff --git a/openecomp-ui/resources/scss/components/_tree.scss b/openecomp-ui/resources/scss/components/_tree.scss new file mode 100644 index 0000000000..e03594ee64 --- /dev/null +++ b/openecomp-ui/resources/scss/components/_tree.scss @@ -0,0 +1,56 @@ + +.tree-view { + overflow: hidden; + + &.scrollable { + overflow: auto; + } + + .node { + text-shadow: none; + stroke: none; + + .outer-circle { + stroke: $blue; + stroke-width: 2px; + fill: $white; + } + + .inner-circle { + fill: $blue; + } + + text { + text-anchor: end; + @extend .body-2-semibold; + fill: $blue; + } + + &.clickable { + cursor: pointer; + } + + &.selectedNode { + .outer-circle { + fill: $blue; + } + + .inner-circle { + fill: $blue; + } + + text { + fill: $blue; + } + } + } + + + .link { + fill: none; + stroke: $dark-gray; + stroke-opacity: 0.4; + stroke-width: 1.5px; + } + +} diff --git a/openecomp-ui/resources/scss/components/_userNotifications.scss b/openecomp-ui/resources/scss/components/_userNotifications.scss new file mode 100644 index 0000000000..74cafae438 --- /dev/null +++ b/openecomp-ui/resources/scss/components/_userNotifications.scss @@ -0,0 +1,123 @@ + +.onboarding-notifications { + margin-left: 10px; + .notifications-icon { + display: flex; + @extend .clickable; + .notifications-count { + color: $white; + font-size: 11px; + text-align: center; + width: 16px; + height: 16px; + background-color: $orange; + border-radius: 50%; + position: relative; + right: 7px; + top: -2px; + &.hidden-count { + background-color: transparent; + color: transparent; + } + } + } + .onboarding-overlay { + width: 520px; + right: 39px; + margin-top: 18px; + .arrow-up { + margin-left: 487px; + } + + .user-notifications { + .notifications-title { + color: $blue; + @extend .heading-5-semibold; + @extend .text-uppercase !optional; + padding: 13px 20px 10px 20px; + border-bottom: 1px solid $tlv-light-gray; + } + .notifications-list { + max-height: 600px; + overflow-y: auto; + .notification { + border-bottom: 1px solid $tlv-light-gray; + padding: 16px 20px 18px 20px; + display: flex; + &.unread { + background-color: lighten($gray, 38%); + .item-name { + display: flex; + @include base-font-bold; + } + .unread-circle-icon { + width: 8px; + height: 8px; + border-radius: 50%; + background-color: $blue; + align-self: center; + margin-bottom: 3px; + margin-left: 9px; + } + } + .notification-data { + width: 366px; + margin-right: 30px; + color: $dark-gray; + .item-name { + @extend .body-2-semibold; + @extend .text-uppercase !optional; + margin-bottom: 6px; + } + .flex-items { + display: flex; + margin: 6px 0 11px 0; + @extend .body-3; + line-height: 20px; + @extend .text-uppercase !optional; + color: $gray; + .separator { + border-left: 1px solid $dark-gray; + margin: 5px 8px; + } + } + .description { + @extend .body-3; + margin: 11px 0 8px 0; + .more-less { + font-size: $icon-font-size; + color: $blue; + } + } + .date { + font-size: $icon-font-size; + @include base-font-regular; + color: $gray; + margin-top: 8px; + } + } + + .notification-action .action-button { + @extend .clickable; + width: 74px; + height: 28px; + color: $white; + background-color: $blue; + border-radius: 2px; + text-align: center; + line-height: 2; + margin-top: 4px; + &.active { + background-color: #0091c7; + border: solid 1px #006186; + } + &:hover { + background-color: #1ec2ff; + border: solid 1px #0091c8; + } + } + } + } + } + } +} diff --git a/openecomp-ui/resources/scss/components/_versionController.scss b/openecomp-ui/resources/scss/components/_versionController.scss index 57610986c3..11e5b41675 100644 --- a/openecomp-ui/resources/scss/components/_versionController.scss +++ b/openecomp-ui/resources/scss/components/_versionController.scss @@ -1,102 +1,272 @@ .version-controller-bar { - display: flex; - min-height: 57px; - border-bottom: 1px solid $tlv-light-gray; - background-color: transparent; - .vc-container { - display: flex; - flex: 1; - align-self: center; - background-color: transparent; - justify-content: space-between; - padding-left: 16px; - padding-right: 40px; - .version-status-container { - display: flex; - height: 30px; - .version-selector { - border: none; - margin-top: 7px; - padding-right: 10px; - margin-right: 15px; - margin-left: 10px; - @extend .body-1; - } - .version-section { - .form-group { - margin-right: 20px; - .input-options { - border: none; - .input-options-select { - padding-top: 4px; - } - } - } - } - .vc-status { - display: flex; - padding-left: 20px; - border-left: $light-gray thin solid; - .status-text { - align-self: center; - margin-top: 2px; - @extend .heading-5; - color: $dark-gray; - } - } - } - .save-submit-cancel-container { - display: flex; - height: 30px; - .action-buttons { - display: flex; - padding: 0 13px; - .version-control-buttons { - display: flex; - } - .action-buttons-svg { - padding-top: 5px; - margin-right: 20px; - padding-bottom: 5px; - - - .svg-icon { - fill: $dark-gray; - &:hover { - fill: $black; - } - &.__versionControllerLockClosed { - margin-top: -3px; - } - &.__versionControllerLockOpen { - margin-top: -6px; - } - &.__versionControllerSubmit { - fill: $blue; - &:hover { - fill: $dark-blue; - } - &.disabled { - fill: $dark-gray; - } - } - } - } - - - - - } - .vc-nav-item-close { - display: flex; - padding-left: 18px; - padding-top: 3px; - align-self: center; - @extend .body-1; - color: $gray; - cursor: pointer; - border-left: $gray thin solid; - } - } - } + display: flex; + min-height: 70px; + border-bottom: 1px solid $tlv-light-gray; + background-color: transparent; + + .vc-container { + display: flex; + flex: 1; + align-self: center; + background-color: transparent; + justify-content: space-between; + align-items: center; + padding-left: 16px; + padding-right: 40px; + + .vc-separator { + border-left: 1px solid $tlv-light-gray; + height: 37px; + margin-left: 5px; + margin-right: 5px; + } + + .version-status-container { + display: flex; + height: 30px; + + .version-selector-more-versions { + color: $blue; + cursor: pointer; + } + + .version-selector { + margin-top: 0px; + padding-right: 10px; + margin-right: 15px; + margin-left: 10px; + border-color: $light-gray; + border-radius: 2px; + width: 243px; + height: 30px; + @extend .body-1; + } + + .version-section { + .form-group { + margin-right: 20px; + + .input-options { + border: none; + + .input-options-select { + padding-top: 4px; + } + } + } + } + + .vc-status { + display: flex; + padding-left: 20px; + border-left: $light-gray thin solid; + + .status-text { + align-self: center; + margin-top: 2px; + @extend .heading-5; + color: $dark-gray; + } + } + } + + .save-submit-cancel-container { + display: flex; + align-items: center; + height: 100%; + + .action-buttons, .collaborator-action-buttons, .vc-save-section, .vc-submit-section { + display: flex; + align-items: center; + height: 100%; + + .vc-submit-button { + border: 1px solid $dark-gray; + width: 94px; + height: 30px; + border-radius: 2px; + padding-top: 5px; + padding-left: 10px; + margin-left: 10px; + margin-right: 10px; + + &:hover:not(.disabled) { + cursor: pointer; + background-color: $tlv-light-gray; + } + + &.disabled { + border-color: $light-gray; + } + + .vc-v-submit { + width: 11px; + height: 8px; + margin-right: 10px; + position: relative; + top: -1px; + } + } + + .version-control-buttons { + display: flex; + } + + .action-button-wrapper { + display: flex; + align-items: center; + height: 70px; + + &:hover:not(.disabled) { + background-color: $tlv-light-gray; + } + + &:active:not(.disabled) { + background-color: $light-gray; + } + + .action-buttons-svg { + padding-left: 10px; + padding-right: 10px; + + .svg-icon { + fill: $text-black; + height: 20px; + + &, &.__version-controller-save { width: 20px; } + &.__version-controller-permissions { width: 32px; } + &.__version-controller-undo, &.__version-controller-revert { width: 20px; } + &.__version-controller-sync, &.__version-controller-commit { width: 28px; } + } + } + + .version-controller-permissions { + width: 32px; + height: 20px; + fill: $dark-gray; + } + } + + .action-button-label { + display: block; + font-size: $icon-font-size; + font-family: $icon-font-family; + height: 1em; + margin-top: 5px; + margin-bottom: 0; + } + + .onboarding-overlay { + margin-top: -6px; + .permissions-overlay { + width: 237px; + + .permissions-overlay-header { + text-align: left; + color: $blue; + padding-bottom: 15px; + padding-top: 15px; + border-bottom: 1px solid $light-gray; + .permissions-overlay-header-title { + margin-left: 20px; + } + } + .permissions-overlay-content { + max-height: 290px; + overflow-y: auto; + padding-left: 10px; + padding-right: 10px; + .contributor { + &:last-child { + border-bottom: none; + } + border-bottom: 1px solid $tlv-light-gray; + .contributor-content { + padding-top: 12px; + padding-bottom: 10px; + margin-left: 10px; + display: flex; + .contributor-icon-circle { + &.selected { + border: 1px solid $blue; + } + + border-radius: 65px; + padding: 2px; + width: 32px; + height: 32px; + margin-top: 4px; + .contributer-icon { + width: 26px; + border-radius: 50px; + height: 26px; + margin-top: 0px; + .__user { + height: 18px; + width: 16px; + stroke: $blue; + fill: transparent; + margin-left: 5px; + margin-top: 3px; + } + &.selected { + border: 1px solid $blue; + background-color: $blue; + .__user { + stroke: $white; + margin-left: 4px; + } + } + } + } + + .contributer-info { + padding-left: 11px; + .contributer-name { + @extend .body-2-semibold; + text-transform: uppercase; + color: $dark-gray; + } + .contributer-role { + @extend .body-3; + color: $gray; + display: flex; + text-transform: lowercase; + p:first-letter { + text-transform: uppercase; + } + justify-content: space-between; + } + } + } + } + } + .permissions-overlay-footer { + .manage-permissions-btn { + @extend .body-2-semibold; + margin-top: 20px; + padding-top: 10px; + padding-bottom: 10px; + color: $blue; + text-align: center; + cursor: pointer; + background-color: $tlv-gray; + } + } + + } + } + } + } + .vc-nav-item-close { + display: flex; + padding-left: 18px; + padding-top: 3px; + align-self: center; + @extend .body-1; + color: $gray; + cursor: pointer; + border-left: $gray thin solid; + } + } } diff --git a/openecomp-ui/resources/scss/modules/_entitlementPools.scss b/openecomp-ui/resources/scss/modules/_entitlementPools.scss index ad0bb77e8d..d9919c27e3 100644 --- a/openecomp-ui/resources/scss/modules/_entitlementPools.scss +++ b/openecomp-ui/resources/scss/modules/_entitlementPools.scss @@ -1,51 +1,22 @@ .entitlement-pools-list-editor { - .list-editor-view-list { - .list-editor-item-view { - min-height: 110px; - height: 110px; - } .list-editor-item-view-field { - .entitlement-pools-count, .contract-number, .type{ - color: $purple; - } .entitlement-pools-count { @extend .heading-1; - margin-top: -10px; - - } + color: $purple; } } } .entitlement-pools-modal { - .modal-body { - padding: 0; - } - .sdc-tab-content { - margin: 0; - } .entitlement-pools-form { - .threshold-section { + .threshold-section, .date-section { display: flex; justify-content: space-between; .validation-input-wrapper { flex: 0 0 46%; } } - .date-section { - display: flex; - justify-content: space-between; - .validation-input-wrapper { - flex: 0 0 46%; - } - } - .validation-form-content { - padding: 20px 50px; } - } - .validation-buttons { - padding: 20px 50px; - } } diff --git a/openecomp-ui/resources/scss/modules/_featureGroup.scss b/openecomp-ui/resources/scss/modules/_featureGroup.scss index 5f98ed2c05..cf681b8758 100644 --- a/openecomp-ui/resources/scss/modules/_featureGroup.scss +++ b/openecomp-ui/resources/scss/modules/_featureGroup.scss @@ -37,48 +37,5 @@ } } -.feature-group-modal { - .modal-body { - padding: 0; - } - .feature-group-form { - .no-items-msg { - margin-top: 55px; - color: $dark-gray; - } - .validation-form-content { - padding: 0; - } - .nav.nav-tabs { - padding-left: 50px; - } - .tab-content { - padding: 50px; - .field-section { - @extend .body-2-semibold; - margin-bottom: 23px; - width: 400px; - color: $black; - } - .description-field { - height: 170px; - } - .list-editor-item-view-content { - white-space: nowrap; - overflow: hidden; - > div { - overflow: hidden; - text-overflow: ellipsis; - &:not(:last-of-type) { - margin-right: 24px; - } - } - } - } - .validation-buttons { - padding: 20px 50px; - } - } -} diff --git a/openecomp-ui/resources/scss/modules/_licenseAgreement.scss b/openecomp-ui/resources/scss/modules/_licenseAgreement.scss index 7a7b87677e..579e9bab2b 100644 --- a/openecomp-ui/resources/scss/modules/_licenseAgreement.scss +++ b/openecomp-ui/resources/scss/modules/_licenseAgreement.scss @@ -2,10 +2,6 @@ .license-agreement-list-editor { .list-editor-view-list { - .list-editor-item-view { - min-height: 110px; - height: 110px; - } .list-editor-item-view-field { .list-editor-item-view-field-tight { vertical-align: top; @@ -17,46 +13,14 @@ overflow-wrap: break-word; } } - .feature-groups-count, .contract-number, .type { + .feature-groups-count, .type { color: $light-green; } .feature-groups-count { @extend .heading-1; padding-top: 2px; - text-align: center; - } - .contract-number { - margin-bottom: 8px; } - } - } -} -.license-agreement-modal { - .modal-body { - padding: 0; - } - .license-agreement-form { - .no-items-msg { - margin-top: 55px; - color: $dark-gray; - } - .tab-content { - padding: 50px; - .list-editor-item-view-content { - white-space: nowrap; - overflow: hidden; - > div { - overflow: hidden; - text-overflow: ellipsis; - &:not(:last-of-type) { - margin-right: 24px; - } - } - } - } - .validation-buttons { - padding: 20px 50px; } } } diff --git a/openecomp-ui/resources/scss/modules/_licenseKeyGroup.scss b/openecomp-ui/resources/scss/modules/_licenseKeyGroup.scss index d072849c08..bcb6abc83d 100644 --- a/openecomp-ui/resources/scss/modules/_licenseKeyGroup.scss +++ b/openecomp-ui/resources/scss/modules/_licenseKeyGroup.scss @@ -1,16 +1,11 @@ .license-key-groups-list-editor { .list-editor-view-list { - .list-editor-item-view { - min-height: 110px; - height: 110px; - } .list-editor-item-view-field { .operational-scope, .type { color: $orange; } .operational-scope { - margin-bottom: 0px; @include ellipsis; } } diff --git a/openecomp-ui/resources/scss/modules/_licenseModel.scss b/openecomp-ui/resources/scss/modules/_licenseModel.scss index fab091fe67..e93ea989fd 100644 --- a/openecomp-ui/resources/scss/modules/_licenseModel.scss +++ b/openecomp-ui/resources/scss/modules/_licenseModel.scss @@ -6,9 +6,6 @@ border-bottom: none; padding-bottom: 30px; } - .modal-body { - padding: 0; - } .sdc-tabs-list { padding-left: 50px; border-bottom: 1px solid $tlv-light-gray; @@ -25,10 +22,7 @@ text-align: end; } .license-model-form { - .validation-form-content { - padding: 20px 50px; - } - .validation-buttons { + .validation-form-content, .validation-buttons { padding: 20px 50px; } &.license-agreement-form, &.feature-group-form { @@ -51,3 +45,11 @@ } } } +.license-model-list-editor { + .list-editor-view-list { + .list-editor-item-view { + min-height: 110px; + height: 110px; + } + } +} diff --git a/openecomp-ui/resources/scss/modules/_licenseModelOverview.scss b/openecomp-ui/resources/scss/modules/_licenseModelOverview.scss index 9246b5fcbf..21c5bd8007 100644 --- a/openecomp-ui/resources/scss/modules/_licenseModelOverview.scss +++ b/openecomp-ui/resources/scss/modules/_licenseModelOverview.scss @@ -4,17 +4,14 @@ $icon-margin: 30px; $arrow-element-width: 30px; $list-item-padding: 15px; -@mixin overview-tile-shadow() { - @include box-shadow(0.5px 0.8px 4px 0 rgba(24, 24, 25, 0.05)); -} -// @mixin vlm-list-item-inset($color) { -// @include box-shadow(inset 6px 0 0 0 $color); -// } $la-color: $dark-blue; $fg-color: $blue; $lkg-ep-color: $light-blue; +@mixin overview-tile-shadow() { + @include box-shadow(0.5px 0.8px 4px 0 rgba(24, 24, 25, 0.05)); +} .license-model-overview { .overview-top-section { @@ -185,11 +182,8 @@ $lkg-ep-color: $light-blue; width: 100%; } .svg-icon-wrapper { - .svg-icon { &.__plusCircle { - width: 20px; - height: 20px; margin-top: 3px; margin-left: auto; fill: $dark-gray; @@ -197,7 +191,8 @@ $lkg-ep-color: $light-blue; fill: $blue; } } - } + } + } .summary-name-and-count { @@ -406,7 +401,7 @@ $lkg-ep-color: $light-blue; &.vlm-list-item-la { margin-top: 10px; .la-icon { - @include create-circle($circle-icon-size,$la-color,'LA'); + @include create-circle($circle-icon-size, $la-color); color: $white; } .vlm-list-item-title { @@ -439,7 +434,7 @@ $lkg-ep-color: $light-blue; margin-left: 29px; } .fg-icon { - @include create-circle($circle-icon-size,$fg-color,'FG'); + @include create-circle($circle-icon-size, $fg-color); color: $white; } @@ -467,7 +462,7 @@ $lkg-ep-color: $light-blue; margin-top: 10px; cursor: default; .ep-icon { - @include create-circle($circle-icon-size,$lkg-ep-color,'EP'); + @include create-circle($circle-icon-size, $lkg-ep-color); color: $white; } .vlm-list-item-title { @@ -490,7 +485,7 @@ $lkg-ep-color: $light-blue; margin-left: $list-indentation * 2; cursor: default; .lkg-icon { - @include create-circle($circle-icon-size,$lkg-ep-color,'KG'); + @include create-circle($circle-icon-size, $lkg-ep-color); color: $white; } .vlm-list-item-title { diff --git a/openecomp-ui/resources/scss/modules/_mergeEditor.scss b/openecomp-ui/resources/scss/modules/_mergeEditor.scss new file mode 100644 index 0000000000..96648dd20f --- /dev/null +++ b/openecomp-ui/resources/scss/modules/_mergeEditor.scss @@ -0,0 +1,207 @@ +$yours-bg-color: $tlv-gray; +$theirs-bg-color: $tlv-light-gray; +$error-text-color: $red; +$selected-width: 1px; +$selected-color: $blue; + +@mixin levels { + @for $i from 1 to 6 { + .level-#{$i} { + padding-left: 18px + 10 * $i; + } + } +} + +.merge-editor-modal { + .modal-lg { + width: 1300px; + } +} + +.merge-editor { + margin: 30px 40px; + max-height: 600px; + border: 1px solid $light-gray; + .grid-section { + &.conflict-titles-section { + @extend .body-1; + background-color: $blue; + height: 33px; + padding-top: 6px; + padding-bottom: 3px; + color: $white; + position: sticky; + top: 0; + z-index: 2; + border-bottom: 1px solid $tlv-light-gray; + .grid-item { + padding-left: 10px; + } + .form-group { + margin-bottom: 0; + .checkbox { + label { + margin-right: 0; + } + + text-align: right; + + input[type="checkbox"] { + cursor: pointer; + margin-top: 1px; + } + } + } + } + } + .merge-editor-body { + max-height: 500px; + overflow-y: scroll; + padding: 10px; + .conflict-section { + margin-bottom: 0; + border-left: 0; + border-right: 0; + padding: 5px 0; + + .conflict-resolve-btn { + align-self: flex-end; + } + + .grid-items { + align-items: center; + + input[type="radio"]:not(:checked) { + cursor: pointer; + } + } + } + + .collapsible-section { + display: flex; + cursor: pointer; + + .conflict-title { + @extend .heading-5-semibold; + text-transform: uppercase; + } + } + + .merge-chevron { + margin-right: 7px; + &.right { + transform: rotate(90deg); + } + } + + .grid-section .grid-items .field-col:not(.grid-col-title) { + &.grid-col-yours { + border-top: $selected-width solid $yours-bg-color; + border-bottom: $selected-width solid $yours-bg-color; + } + + &.theirs-color { + border-top: $selected-width solid $theirs-bg-color; + border-bottom: $selected-width solid $theirs-bg-color; + } + } + + .merge-editor-text-field { + display: flex; + justify-content: space-between; + // margin: 0 0 10px 0; + margin: 0; + + .field { + color: $text-black; + + &.field-name:not(.field-object-name) { + color: $gray; + } + } + + &.diff { + .field { + color: $red; + } + } + + &.grid-section { + padding-bottom: 0; + + .grid-items { + flex: 1; + + + .field-col { + padding: 7px 0; + height: 100%; + + &:not(:first-child) { + padding-left: 8px; + } + + &.grid-col-yours { + background-color: $yours-bg-color; + } + + &.grid-col-theirs { + background-color: $theirs-bg-color; + } + + @include levels; + + + .field { + @extend .body-1; + flex: 2; + min-width: 0; + + &.field-name { + @include multiline-ellipsis($bgColor: white); + &.diff { + color: $red; + } + text-transform: uppercase; + &.field-object-name { + @extend .body-1-semibold; + margin-bottom: 5px; + margin-top: 10px; + + } + } + + &.field-yours { + @include multiline-ellipsis($bgColor: $yours-bg-color); + } + + &.field-theirs { + @include multiline-ellipsis($bgColor: $theirs-bg-color); + } + &.field-name, &.field.field-yours, &.field.field-theirs { + word-break: break-word; + text-align: initial; + } + &.empty-field { + padding-top: 2px; + } + } + + *::after { + bottom: 0; + } + } + } + } + + &.field-error { + @extend .body-1; + color: $error-text-color; + min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + } + } +} diff --git a/openecomp-ui/resources/scss/modules/_onboardingCatalog.scss b/openecomp-ui/resources/scss/modules/_onboardingCatalog.scss index 6c56d11049..4fb0f7c99e 100644 --- a/openecomp-ui/resources/scss/modules/_onboardingCatalog.scss +++ b/openecomp-ui/resources/scss/modules/_onboardingCatalog.scss @@ -8,6 +8,7 @@ $transitionLength: 0.6s; @import "onboardingCatalog/catalogHeader"; @import "onboardingCatalog/vendorPageHeader"; @import "onboardingCatalog/catalogList"; + @import "onboardingCatalog/vspOverlay"; .catalog-wrapper { height: 100%; overflow: auto; @@ -19,6 +20,38 @@ $transitionLength: 0.6s; .catalog-list { overflow: hidden; height: auto; + .sdc-tile { + margin: 9px; + .sdc-tile-header { + position: initial; + display: block; + flex-shrink: initial; + align-items: initial; + flex-direction: initial; + } + .sdc-tile-content { + position: initial; + flex: initial; + display: flex; + align-items: initial; + flex-direction: column; + justify-content: space-between; + overflow: initial; + .sdc-tile-info-line { + .with-overlay { + line-height: 1.2em; + @include ellipsis($width: initial, $max-width: 100%); + } + } + } + .sdc-tile-footer { + position: initial; + flex-shrink: initial; + display: flex; + align-items: center; + flex-direction: row; + } + } } } } diff --git a/openecomp-ui/resources/scss/modules/_permissions.scss b/openecomp-ui/resources/scss/modules/_permissions.scss new file mode 100644 index 0000000000..e652d9d82f --- /dev/null +++ b/openecomp-ui/resources/scss/modules/_permissions.scss @@ -0,0 +1,55 @@ +.modal-content { + .modal-body { + .manage-permissions-page { + .validation-form-content { + overflow-y: visible; + } + + .manage-permissions-title { + @extend .body-1-semibold; + margin-bottom: 10px; + } + .owner-details { + @extend .body-2; + display: flex; + margin-bottom: 30px; + .change-owner { + margin-left: auto; + color: $blue; + cursor: pointer; + &:hover { + color: $dark-blue; + } + } + } + .change-owner-wrapper { + .form-group { + margin-bottom: 30px; + } + + } + .change-owner-title { + display: flex; + align-items: center; + margin-bottom: 10px; + .manage-permissions-title { + margin-bottom: 0; + } + .svg-icon-wrapper { + margin-left: 5px; + .svg-icon { + width: 13px; + height: 13px; + fill: $dark-gray; + } + } + } + .contributors-select { + .Select-menu { + max-height: 150px; + overflow-y: auto + } + } + } + } +} diff --git a/openecomp-ui/resources/scss/modules/_revisions.scss b/openecomp-ui/resources/scss/modules/_revisions.scss new file mode 100644 index 0000000000..2b196c132c --- /dev/null +++ b/openecomp-ui/resources/scss/modules/_revisions.scss @@ -0,0 +1,86 @@ +.manage-revisions-modal { + .modal-dialog { + width: 700px; + } + .modal-content { + .modal-body { + .validation-form-content { + padding-top: 30px; + } + //.selected { + // .selectable { + // border-color: $light-blue; + // } + // .selectable:hover{ + // border-color: hotpink; + // } + //} + + .revision-list-item { + &.selected { + .selectable, .selectable:hover { + border-width: 2px; + border-color: $light-blue; + } + } + .selectable:hover{ + border-color: $gray; + } + .selectable:active { + border-color: $light-blue; + } + } + + .list-editor-view-list-scroller { + margin-top : 0px; + } + + .list-editor-view-header { + border-bottom: none; + .list-editor-view-title { + @extend .heading-5; + text-transform: none; + color: $blue; + } + } + + .list-editor-item-view-content { + background-color: $background-gray; + } + .revision-list-item-fields { + width: 100%; + display: flex; + flex-wrap: wrap; + .revision-user { + flex-basis: 50%; + fill: transparent; + stroke: $blue; + .svg-icon-label { + margin-left: 13px; + } + } + + .revision-date { + flex-basis: 50%; + text-align: right; + @extend .body-3; + color: $gray; + .revision-time { + margin-left: 5px; + } + } + + .revision-message { + flex-basis: 100%; + margin-top: 5px; + @extend .body-2; + .more-less { + @extend .body-3; + color: $blue; + margin-left: 5px; + } + } + } + } + } +} diff --git a/openecomp-ui/resources/scss/modules/_softwareProductAttachmentPage.scss b/openecomp-ui/resources/scss/modules/_softwareProductAttachmentPage.scss index c8d8cf4e0b..0ae3f00a29 100644 --- a/openecomp-ui/resources/scss/modules/_softwareProductAttachmentPage.scss +++ b/openecomp-ui/resources/scss/modules/_softwareProductAttachmentPage.scss @@ -1,21 +1,25 @@ .vsp-attachments-view { position: relative; - #attachments-tabs { - .nav-tabs { + .attachments-tabs { + .sdc-tabs-list { + padding-left: 28px; background-color: $tlv-gray; box-shadow: none; border-bottom: 1px solid $light-gray; - & > li { - & > a { + .sdc-tab { @extend .heading-2; - padding-left: 0; - padding-right: 0; - margin-right: 40px; - }; - &.active > a {color: $blue;}; + padding-top: 10px; + margin-top: 0; + &.sdc-tab-active { + color: $blue; + font-weight: bold; + } } } + .sdc-tab-content { + margin-top: 0; + } } .attachments-view-controllers { position: absolute; @@ -91,6 +95,11 @@ z-index: 1; padding-right: 20px; .counter { + .svg-icon { + &.__exclamationTriangleLine { + fill: $orange; + } + } display: flex; &:first-child { margin-right: 20px; @@ -215,6 +224,7 @@ .svg-icon { width: 20px; height: 20px; + fill: $orange; } } .error-item-file-type { diff --git a/openecomp-ui/resources/scss/modules/_softwareProductComponentGeneral.scss b/openecomp-ui/resources/scss/modules/_softwareProductComponentGeneral.scss index 6c5bcee03c..d31c7f0b92 100644 --- a/openecomp-ui/resources/scss/modules/_softwareProductComponentGeneral.scss +++ b/openecomp-ui/resources/scss/modules/_softwareProductComponentGeneral.scss @@ -10,7 +10,4 @@ } } } - .additional-validation-form { - margin-top: 50px; - } } diff --git a/openecomp-ui/resources/scss/modules/_softwareProductComponentImage.scss b/openecomp-ui/resources/scss/modules/_softwareProductComponentImage.scss index dad837f356..b67c448b54 100644 --- a/openecomp-ui/resources/scss/modules/_softwareProductComponentImage.scss +++ b/openecomp-ui/resources/scss/modules/_softwareProductComponentImage.scss @@ -23,9 +23,6 @@ } .image-modal-edit, .image-modal-new { - .modal-body { - padding: 0; - } .vsp-components-image-editor { .image-format, .image-md5, .image-version { @@ -35,13 +32,19 @@ padding-left: 30px; } .section-title { - text-transform: capitalize; + text-transform: uppercase; font-size: 18px; } } } .vsp-components-image { + .list-editor-view { + margin-top: 50px; + .manual-title { + @extend .body-1-semibold; + } + } .list-editor-item-view-content { flex:1; min-width: 0; diff --git a/openecomp-ui/resources/scss/modules/_softwareProductComponentNetwork.scss b/openecomp-ui/resources/scss/modules/_softwareProductComponentNetwork.scss index 402918bc5e..eaba47acb4 100644 --- a/openecomp-ui/resources/scss/modules/_softwareProductComponentNetwork.scss +++ b/openecomp-ui/resources/scss/modules/_softwareProductComponentNetwork.scss @@ -20,16 +20,7 @@ display: flex; } } -.network-nic-modal-edit, .network-nic-modal-create { - .modal-body { - padding: 0; - } - .validation-form-content { - padding-left: 50px; - padding-right: 50px; - padding-top: 20px; - } -} + .network-nic-modal-edit { .modal-dialog { width: 900px; diff --git a/openecomp-ui/resources/scss/modules/_softwareProductComponentProcessesPage.scss b/openecomp-ui/resources/scss/modules/_softwareProductComponentProcessesPage.scss index be4caacfb5..9476d7043d 100644 --- a/openecomp-ui/resources/scss/modules/_softwareProductComponentProcessesPage.scss +++ b/openecomp-ui/resources/scss/modules/_softwareProductComponentProcessesPage.scss @@ -1,7 +1,4 @@ .edit-process-modal { - .vsp-process-dropzone-view .grid-section { - padding-bottom: 30px !important; - } .component-process-description > textarea { height: 113px; } diff --git a/openecomp-ui/resources/scss/modules/_softwareProductDependencies.scss b/openecomp-ui/resources/scss/modules/_softwareProductDependencies.scss index 8fb739234f..65c558fa0e 100644 --- a/openecomp-ui/resources/scss/modules/_softwareProductDependencies.scss +++ b/openecomp-ui/resources/scss/modules/_softwareProductDependencies.scss @@ -2,14 +2,22 @@ .software-product-dependencies-title { @extend .heading-1; @extend .text-uppercase !optional; + position: sticky; + top: -30px; + z-index: 1; + background: $white; margin-bottom: 20px; color: $blue; } .select-action-table-controllers { + position: sticky; + top: 4px; + z-index: 1; + background: $white; justify-content: flex-end; cursor: pointer; color: $blue; - padding-right: 33px; + padding-right: 27px; margin-bottom: 3px; &:hover { color: $dark-blue; @@ -18,8 +26,23 @@ .select-action-table-view { min-width: 770px; } + .select-action-table-headers { + position: sticky; + top: 27px; + z-index: 1; .select-action-table-header { @extend .body-1-semibold; color: $text-black; + } + } + .select-action-table-row-wrapper { + .svg-icon { + &.__trashO, &.__plusCircle { + fill: $dark-gray; + &:hover { + fill: $black; } + } + } + } } diff --git a/openecomp-ui/resources/scss/modules/_softwareProductDeployment.scss b/openecomp-ui/resources/scss/modules/_softwareProductDeployment.scss index e0de8fc969..b5f9a546d9 100644 --- a/openecomp-ui/resources/scss/modules/_softwareProductDeployment.scss +++ b/openecomp-ui/resources/scss/modules/_softwareProductDeployment.scss @@ -2,9 +2,6 @@ .modal-dialog { width: 780px; } - .grid-section { - padding-bottom: 25px; - } .deployment-feature-groups-section.no-feature-groups { padding-bottom: 0; .form-group { @@ -25,15 +22,12 @@ } .modal-content { .modal-body { - padding: 0; .validation-form-content { + overflow-y: visible; .grid-col-1 { - flex-basis: 35%; + flex-basis: 30%; } - .Select-value, .Select-placeholder { - font-family: omnes-regular, sans-serif; - } .grid-section.vfc-table { padding-bottom: 50px; @@ -46,9 +40,6 @@ .grid-col-3 { flex-basis: 65%; } - padding-left: 54px; - padding-right: 33px; - overflow-y: visible; } } } diff --git a/openecomp-ui/resources/scss/modules/_softwareProductLandingPage.scss b/openecomp-ui/resources/scss/modules/_softwareProductLandingPage.scss index 28b54cc78f..99027d66ed 100644 --- a/openecomp-ui/resources/scss/modules/_softwareProductLandingPage.scss +++ b/openecomp-ui/resources/scss/modules/_softwareProductLandingPage.scss @@ -18,12 +18,7 @@ .description { @extend .body-1; - // overflow: hidden; padding-right: 20px; - // text-overflow: ellipsis; - // display: -webkit-box; - // -webkit-line-clamp: 2; - // -webkit-box-orient: vertical; .missing-license { display: flex; @@ -56,15 +51,9 @@ } } .software-product-landing-view { - transition: border .2s; padding-bottom: 50px; - .list-editor-view { - padding-top: 50px; - padding-left: 0; - padding-right: 0; - } .software-product-landing-view-top { .details-container { @extend .flex-column; @@ -110,6 +99,10 @@ &:last-child { margin-right: 0; } + .software-product-landing-view-top-block-col-upl { + height: 215px; + width: initial; + } } .col-md-6 { padding: 0; @@ -134,16 +127,19 @@ } } .software-product-landing-view-top-block { + &.clickable { cursor: pointer; + &:hover { + @extend .box-hover; + } + } border: 1px solid $light-gray; padding: 20px 18px 0 18px; height: 215px; display: flex; justify-content: space-between; background-color: $white; - &:hover { - @extend .box-hover; - } + .col-md-6 { @extend .body-1; } @@ -164,30 +160,12 @@ color: $light-blue; } } - } .software-product-landing-view-top-block-col-upl { @extend .flex; - height: 215px; - text-align: center; - flex-direction: column; - justify-content: center; - border: 2px dashed $light-gray; margin-bottom: 20px; - @extend .body-1; - align-items: center; - .upload-btn { - padding: 15px 55px; } - .drag-text { - color: $blue; - @extend .body-1-semibold; - } - .or-text { - margin-top: 10px; - margin-bottom: 10px; - } } } } @@ -195,6 +173,9 @@ } .vsp-details-page { + .grid-section-general { + padding-bottom: 30px; + } .vsp-general-tab { .validation-form-content { margin: 0; diff --git a/openecomp-ui/resources/scss/modules/_softwareProductProcessesPage.scss b/openecomp-ui/resources/scss/modules/_softwareProductProcessesPage.scss index d75e7447ab..3f2a2f9a69 100644 --- a/openecomp-ui/resources/scss/modules/_softwareProductProcessesPage.scss +++ b/openecomp-ui/resources/scss/modules/_softwareProductProcessesPage.scss @@ -1,10 +1,5 @@ .edit-process-modal { - background-color: $white; height: 100%; - &.modal-body { - padding: 0; - background-color: $white; - } .vsp-processes-editor { padding-left: 0; padding-right: 0; @@ -23,41 +18,22 @@ padding-top: 20px; padding-bottom: 20px; - align-items: center; - .upload-btn { - padding: 4px 20px; - } - .drag-text { - color: $blue; - @extend .body-1-semibold; - } - .or-text { - margin-top: 10px; - margin-bottom: 10px; + .process-type { + width: 100%; } } .vsp-processes-editor-data { - transition: border .2s; - .vsp-process-dropzone-view { - background-color: transparent; - &.active-dragging { - border: 3px dashed $dark-blue; - border-radius: 20px; - .draggable-wrapper { - opacity: 0.5; - } - } - .grid-section { - .section-title { - padding-bottom: 0; - } - } - } .validation-input-wrapper { .form-group.vsp-process-description > textarea { height: 113px; } } + .process-type { + width: 100%; + } + .process-editor-file-box { + width: 380px; + } } } } diff --git a/openecomp-ui/resources/scss/modules/_softwareproductComponentLoadBalancing.scss b/openecomp-ui/resources/scss/modules/_softwareproductComponentLoadBalancing.scss index d1f3f488bd..440b2424df 100644 --- a/openecomp-ui/resources/scss/modules/_softwareproductComponentLoadBalancing.scss +++ b/openecomp-ui/resources/scss/modules/_softwareproductComponentLoadBalancing.scss @@ -5,12 +5,6 @@ } .halb-data { - .load-balancing-page-title { - @extend .section-title; - &:first-child { - padding: 0 0 40px 0; - } - } .question { padding-top: 10px; &:first-child { diff --git a/openecomp-ui/resources/scss/modules/_uploadScreen.scss b/openecomp-ui/resources/scss/modules/_uploadScreen.scss index 4aa07f1580..23f41c8816 100644 --- a/openecomp-ui/resources/scss/modules/_uploadScreen.scss +++ b/openecomp-ui/resources/scss/modules/_uploadScreen.scss @@ -5,20 +5,6 @@ text-align: center; margin-bottom: 50px; } - .upload-screen-upload-block { - text-align: center; - padding: 50px; - border: 2px dashed lightgray; - } - .upload-screen-drop-zone { - &.active-dragging { - border: 3px dashed $dark-blue; - border-radius: 20px; - .draggable-wrapper { - opacity: 0.5; - } - } - } } .attachments-screen { diff --git a/openecomp-ui/resources/scss/modules/_versionsPage.scss b/openecomp-ui/resources/scss/modules/_versionsPage.scss new file mode 100644 index 0000000000..fa1dc11ec6 --- /dev/null +++ b/openecomp-ui/resources/scss/modules/_versionsPage.scss @@ -0,0 +1,325 @@ +.dox-ui-punch-out { + background-color: $content-background-color; +} + +.dox-ui-punch-out.dox-ui-punch-out-full-page { + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + overflow-y: auto; +} + +@mixin version-page-box-shadow() { + box-shadow: 0 1px 4px 0 rgba(24, 24, 24, 0.06); +} + +@mixin version-page-sub-title(){ + color: $text-black; + text-transform: uppercase; + background-color: $white; + border-bottom: 1px solid $light-gray; + padding: 12px 0 10px 23px; +} + +.versions-tree-modal { + .modal-dialog { + width: 800px; + } + + .tree-view { + display: flex; + align-items: center; + } +} + +.versions-page-view { + height: 100%; + background-color: $background-gray; + overflow: auto; + padding: 35px 50px 20px 50px; + + .svg-icon-wrapper { + justify-content: flex-start; + } + + .versions-page-title { + @extend .heading-1; + text-transform: uppercase; + margin-bottom: 29px; + color: $blue; + } + + .versions-page-permissions-view-wrapper { + @extend .body-1-semibold; + @include version-page-box-shadow(); + + .permissions-view-wrapper-title { + @include version-page-sub-title(); + } + + .svg-icon-wrapper.user-view { + fill: transparent; + stroke: $blue; + .svg-icon { + height: 18px; + width: 16px; + margin: 0 7px; + } + &.current-user { + .svg-icon { + background-color: $blue; + stroke: $white; + padding-top: 5px; + padding-bottom: 3px; + height: 29px; + width: 29px; + border-radius: 20px; + border: 1px solid $blue; + box-shadow: inset 0px 0px 0px 2px $white; + margin: 0; + } + .svg-icon-label { + margin-left: 7px; + } + } + .svg-icon-label { + @extend .body-2; + color: $dark-gray; + margin-left: 6px; + } + } + + .permissions-view-content { + padding: 20px 40px 20px 25px; + background-color: $white; + + height: 120px; + display: flex; + } + + .permissions-view { + display: flex; + flex: 1; + flex-direction: column; + justify-content: space-around; + + .permissions-view-title { + text-transform: uppercase; + color: $dark-gray; + } + + .contributors-view, .owner-view { + display: flex; + height: 16px; + @extend .body-1-semibold; + + .permissions-view-title { + width: 130px; + line-height: 16px; + } + + .extra-contributors { + border-radius: 30px; + background-color: $gray; + width: 26px; + height: 26px; + padding-right: 2px; + display: flex; + align-items: center; + justify-content: center; + color: $white; + cursor: default; + &:hover { + background-color: $dark-gray; + } + } + + .user-view { + margin-right: 38px; + } + + .manage-permissions { + color: $blue; + margin-left: auto; + cursor: pointer; + + &:hover { + color: $dark-blue; + } + } + } + } + } + + .versions-page-list-and-tree { + display: flex; + margin-top: 20px; + + .version-tree-wrapper { + display: flex; + flex-direction: column; + margin-right:10px; + transition: all 1s ease; + @include version-page-box-shadow(); + + .version-tree-title-container { + display: flex; + align-items: center; + height: 40px; + @include version-page-sub-title(); + padding-right: 10px; + + .version-tree-full-screen { + margin-left: auto; + } + } + + .tree-view { + background-color: $white; + flex: 1; + } + } + } + + .version-list { + flex: 1; + @extend .body-1-semibold; + color: $text-black; + display: flex; + flex-direction: column; + + .version-list-items { + flex: 1; + display: flex; + flex-direction: column; + + .version-item-row { + border-bottom: 1px solid $tlv-light-gray; + + &:last-child { + border-bottom: none; + } + } + } + + .version-item-row { + $row-hover-color: lighten($blue, 54%); + $row-active-color: lighten($blue, 51%); + + display: flex; + align-items: center; + padding: 15px 30px; + @include version-page-box-shadow(); + background-color: $white; + height: 70px; + + &:hover { + background-color: $row-hover-color; + } + + &.selected { + box-shadow: 0 1px 4px 0 rgba(24, 24, 24, 0.06), inset 5px 0 0 0 $blue; + background-color: $row-active-color; + &:hover { + background-color: $row-hover-color; + box-shadow: 0 1px 4px 0 rgba(24, 24, 24, 0.06), inset 5px 0 0 0 lighten($blue, 35%); + } + } + + &.header-row { + height: 40px; + + @extend .body-1-semibold; + @include version-page-sub-title(); + padding: 15px 27px; + + &:hover { + background-color: $white; + pointer-events: none; + &:active { + background-color: $white; + @include version-page-box-shadow(); + } + } + .header-field.actions { + margin-right: 57px; + } + } + + .version-item-field { + flex: 1; + display: flex; + margin-right: 10px; + + &.item-version, &.item-status { + flex: 0 1 10%; + @extend .body-1-semibold; + color: $text-black; + } + + &.item-description, &.item-last-edited { + @extend .body-1; + color: $dark-gray; + } + + &.item-description, &.header-description { + flex: 2 1 0; + } + + &.item-description > .description-text { + margin-right: 10px; + @include ellipsis($max-width: 300px); + } + + &.item-actions { + display: flex; + flex: 1 1 3%; + justify-content: space-between; + } + + &.item-select, &.item-create { + @extend .body-1; + flex: 0 1 auto; + margin-right: 0; + + .svg-icon-wrapper { + fill: $blue; + color: $blue; + + &[disabled] { + cursor: default; + } + + .svg-icon { + width: 16px; + height: 16px; + } + + &:hover:not([disabled]) { + fill: $dark-blue; + color: $dark-blue; + } + } + } + + } + + /* To keep ellipsis hider's background the same color as row background */ + &:not(.selected):hover .item-description > .description-text:after { + background: $row-hover-color + } + + &:hover:active .item-description > .description-text:after { + background: $row-active-color; + } + + } + + } + + &.clickable { + cursor: pointer; + } +} diff --git a/openecomp-ui/resources/scss/modules/_vspComponentCompute.scss b/openecomp-ui/resources/scss/modules/_vspComponentCompute.scss index ee8cfa5c7f..9f88e94393 100644 --- a/openecomp-ui/resources/scss/modules/_vspComponentCompute.scss +++ b/openecomp-ui/resources/scss/modules/_vspComponentCompute.scss @@ -1,16 +1,3 @@ -.vsp-component-computeFlavor-view { - .component-questionnaire-validation-form { - .vm-sizing-section { - .section-title { - text-transform: capitalize; - font-size: 18px; - } - .duplicate-title-line label.control-label{ - height: 2.7em; - } - } - } -} .compute-flavor-editor-modal-edit { .modal-lg { diff --git a/openecomp-ui/resources/scss/modules/_vspComponentMonitoring.scss b/openecomp-ui/resources/scss/modules/_vspComponentMonitoring.scss index bda8512f36..14bad18179 100644 --- a/openecomp-ui/resources/scss/modules/_vspComponentMonitoring.scss +++ b/openecomp-ui/resources/scss/modules/_vspComponentMonitoring.scss @@ -1,34 +1,9 @@ .vsp-component-monitoring { .dropzone { - .section-title { - padding-bottom: 20px; - } &:not(:last-child) { padding-bottom: 50px; } - .software-product-landing-view-top-block-col-upl { - @extend .body-1; - width: 400px; - display: flex; - text-align: center; - flex-direction: column; - justify-content: center; - border: 2px dashed $light-gray; - padding: 25px 0; - align-items: center; - .upload-btn { - padding: 4px 20px; - } - .drag-text { - color: $blue; - @extend .body-1-semibold - } - .or-text { - margin-top: 10px; - margin-bottom: 10px; - } - } .monitoring-file { display: flex; @@ -46,7 +21,4 @@ } } - .delete-button { - min-width: 0; - } } diff --git a/openecomp-ui/resources/scss/modules/_vspComponentQuestionnaire.scss b/openecomp-ui/resources/scss/modules/_vspComponentQuestionnaire.scss index 5696b354a7..2a99263285 100644 --- a/openecomp-ui/resources/scss/modules/_vspComponentQuestionnaire.scss +++ b/openecomp-ui/resources/scss/modules/_vspComponentQuestionnaire.scss @@ -1,6 +1,6 @@ .vsp-component-questionnaire-view { - input[type='radio'], input[type='checkbox'] { + input[type='checkbox'] { &:before { border: 1px solid $dark-gray; cursor: pointer; @@ -30,14 +30,13 @@ .radio-options-content-row { display: flex; margin-top: -4px; - .validation-input-wrapper { - width: 240px; - margin-right: 7px; + .validation-radio-wrapper { + margin-right: 20px; & > .form-group { display: flex; } - .form-group .radio { + .form-group .sdc-radio { width: auto; margin-right: 0; } diff --git a/openecomp-ui/resources/scss/modules/onboardingCatalog/_catalogHeader.scss b/openecomp-ui/resources/scss/modules/onboardingCatalog/_catalogHeader.scss index d29a95d3d6..0a234a5a96 100644 --- a/openecomp-ui/resources/scss/modules/onboardingCatalog/_catalogHeader.scss +++ b/openecomp-ui/resources/scss/modules/onboardingCatalog/_catalogHeader.scss @@ -14,7 +14,7 @@ flex-direction: row; .tab-separator { position: relative; - top: 13px; + top: 8px; } .catalog-header-tab { @extend .heading-1; diff --git a/openecomp-ui/resources/scss/modules/onboardingCatalog/_onboardHeader.scss b/openecomp-ui/resources/scss/modules/onboardingCatalog/_onboardHeader.scss index 32ebac98cf..f97641cbe3 100644 --- a/openecomp-ui/resources/scss/modules/onboardingCatalog/_onboardHeader.scss +++ b/openecomp-ui/resources/scss/modules/onboardingCatalog/_onboardHeader.scss @@ -5,15 +5,16 @@ justify-content: flex-end; background-color: $tlv-light-gray; margin-bottom: 2px; + padding-left: 60px; + padding-right: 40px; @include box-shadow(0px 1px 3px 0 rgba(0, 0, 0, 0.2)); .expandable-input-top { - margin-right: 60px; + margin-right: 20px; margin-left: auto; } .onboard-header-tabs { display: flex; flex-direction: row; - margin-left: 60px; .onboard-header-tab { @extend .body-1-semibold; margin-right: 40px; diff --git a/openecomp-ui/resources/scss/modules/onboardingCatalog/_vspOverlay.scss b/openecomp-ui/resources/scss/modules/onboardingCatalog/_vspOverlay.scss index 80ed7385e0..e0b72bf9ff 100644 --- a/openecomp-ui/resources/scss/modules/onboardingCatalog/_vspOverlay.scss +++ b/openecomp-ui/resources/scss/modules/onboardingCatalog/_vspOverlay.scss @@ -54,7 +54,7 @@ &:hover { color: $blue; } - text-transform: uppercase; + text-transform: none; @include ellipsis(auto, block); border-bottom: 1px solid $tlv-light-gray; cursor: pointer; diff --git a/openecomp-ui/resources/scss/onboarding.scss b/openecomp-ui/resources/scss/onboarding.scss index fc05f7493e..2c7c55530d 100644 --- a/openecomp-ui/resources/scss/onboarding.scss +++ b/openecomp-ui/resources/scss/onboarding.scss @@ -130,6 +130,16 @@ div[data-reactroot].tooltip { border-top-color: $dark-gray !important; } } + &.right { + .tooltip-arrow { + border-right-color: $dark-gray !important; + } + } + &.left { + .tooltip-arrow { + border-left-color: $dark-gray !important; + } + } .tooltip-inner { @extend .body-1; max-width: 100%; @@ -149,6 +159,18 @@ div[data-reactroot].tooltip { padding: 3px 12px; } } + // manage permisions modal + &.manage-permissions-owner-tooltip { + .tooltip-inner { + width: 400px; + } + } + // WS/Catalog Tile + &.tile-super-info { + .tooltip-inner { + font-size: $body-font-3; + } + } //dependency table error tooltip &.select-action-table-error-tooltip{ @include base-font-regular; diff --git a/openecomp-ui/src/nfvo-components/SubmitErrorResponse.jsx b/openecomp-ui/src/nfvo-components/SubmitErrorResponse.jsx index 40daeff9c5..c15cd1d0e8 100644 --- a/openecomp-ui/src/nfvo-components/SubmitErrorResponse.jsx +++ b/openecomp-ui/src/nfvo-components/SubmitErrorResponse.jsx @@ -60,7 +60,7 @@ class SubmitErrorResponse extends Component { return (
    - {errors.length && errors.map(error=>{return ();})} + {errors.length && errors.map((error, i) => {return ();})}
    ); @@ -71,7 +71,7 @@ class SubmitErrorResponse extends Component { return (
    - {errors.validationData.length && errors.validationData.map(item =>{ return ();})} + {errors.validationData.length && errors.validationData.map((item, i) =>{ return ();})}
    ); @@ -90,11 +90,10 @@ class SubmitErrorResponse extends Component { const ComponentError = ({item}) => { - let i = 0; return (
    {item.entityName}
    - {item.errors.map(error => {return();})} + {item.errors.map((error, i) => {return();})}
    ); }; @@ -110,7 +109,7 @@ const UploadErrorList = ({items}) => { let errors = []; for (let item of generator) {errors.push( -
    +
    {item.header}
    {item.list.map((error, i) => )}
    diff --git a/openecomp-ui/src/nfvo-components/datepicker/Datepicker.jsx b/openecomp-ui/src/nfvo-components/datepicker/Datepicker.jsx index f4673c1c93..25e7e7e02d 100644 --- a/openecomp-ui/src/nfvo-components/datepicker/Datepicker.jsx +++ b/openecomp-ui/src/nfvo-components/datepicker/Datepicker.jsx @@ -1,4 +1,5 @@ import React from 'react'; +import PropTypes from 'prop-types'; import DatePicker from 'react-datepicker'; import moment from 'moment'; import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; @@ -6,10 +7,10 @@ import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; class CustomInput extends React.Component { static propTypes = { - placeHolderText: React.PropTypes.string, - onChange: React.PropTypes.func, - onClick: React.PropTypes.func, - value: React.PropTypes.string + placeHolderText: PropTypes.string, + onChange: PropTypes.func, + onClick: PropTypes.func, + value: PropTypes.string }; render() { @@ -32,16 +33,16 @@ const parseDate = (date, format) => { class Datepicker extends React.Component { static propTypes = { - date: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]), - format: React.PropTypes.string, - onChange: React.PropTypes.func, - selectsStart: React.PropTypes.bool, - selectsEnd: React.PropTypes.bool, - startDate: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]), - endDate: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]), - disabled: React.PropTypes.bool, - label: React.PropTypes.string, - isRequired: React.PropTypes.bool + date: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), + format: PropTypes.string, + onChange: PropTypes.func, + selectsStart: PropTypes.bool, + selectsEnd: PropTypes.bool, + startDate: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), + endDate: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), + disabled: PropTypes.bool, + label: PropTypes.string, + isRequired: PropTypes.bool } render() { let {date, format, onChange, selectsStart = false, startDate = null, endDate = null, selectsEnd = false, diff --git a/openecomp-ui/src/nfvo-components/editor/TabulatedEditor.jsx b/openecomp-ui/src/nfvo-components/editor/TabulatedEditor.jsx index 2a0b7d4d2a..3c9ceed0d8 100644 --- a/openecomp-ui/src/nfvo-components/editor/TabulatedEditor.jsx +++ b/openecomp-ui/src/nfvo-components/editor/TabulatedEditor.jsx @@ -22,7 +22,8 @@ import NavigationSideBar from 'nfvo-components/panel/NavigationSideBar.jsx'; export default class TabulatedEditor extends React.Component { render() { - const {navigationBarProps, onToggle, onVersionSwitching, onCreate, onSave, onClose, onVersionControllerAction, onNavigate, children, meta} = this.props; + const {navigationBarProps, onToggle, onVersionSwitching, onMoreVersionsClick, onCreate, onSave, onClose, + onVersionControllerAction, onNavigate, children, meta, onManagePermissions, onOpenCommentCommitModal, onOpenPermissions, onOpenRevisionsModal} = this.props; let {versionControllerProps} = this.props; const {className = ''} = React.Children.only(children).props; const child = this.prepareChild(); @@ -42,7 +43,12 @@ export default class TabulatedEditor extends React.Component { onVersionSwitching(version, meta)} - callVCAction={(action, version) => onVersionControllerAction(action, version, meta)} + onMoreVersionsClick={onMoreVersionsClick} + onManagePermissions={onManagePermissions} + onOpenCommentCommitModal={onOpenCommentCommitModal} + onOpenPermissions={onOpenPermissions} + onOpenRevisionsModal={onOpenRevisionsModal} + callVCAction={(action, version, comment) => onVersionControllerAction(action, version, comment, meta)} onCreate={onCreate && this.handleCreate} onSave={onSave && this.handleSave}/>
    diff --git a/openecomp-ui/src/nfvo-components/fileupload/DraggableUploadFileBox.jsx b/openecomp-ui/src/nfvo-components/fileupload/DraggableUploadFileBox.jsx index 629b9449a2..5b4e0a8bee 100644 --- a/openecomp-ui/src/nfvo-components/fileupload/DraggableUploadFileBox.jsx +++ b/openecomp-ui/src/nfvo-components/fileupload/DraggableUploadFileBox.jsx @@ -34,11 +34,10 @@ class DraggableUploadFileBox extends Component { render() { let {className, onClick, dataTestId, isReadOnlyMode} = this.props; return ( -
    -
    {i18n('Drag & drop for upload')}
    +
    +
    {i18n('Drag & drop for upload')}
    {i18n('or')}
    - +
    ); } diff --git a/openecomp-ui/src/nfvo-components/grid/GridItem.jsx b/openecomp-ui/src/nfvo-components/grid/GridItem.jsx index 8819ab78a3..c62e042bf4 100644 --- a/openecomp-ui/src/nfvo-components/grid/GridItem.jsx +++ b/openecomp-ui/src/nfvo-components/grid/GridItem.jsx @@ -15,8 +15,8 @@ */ import React from 'react'; -const GridItem = ({colSpan = 1, children, stretch = false}) => ( -
    +const GridItem = ({colSpan = 1, children, lastColInRow = false, stretch = false, className = ''}) => ( +
    {children}
    diff --git a/openecomp-ui/src/nfvo-components/grid/GridSection.jsx b/openecomp-ui/src/nfvo-components/grid/GridSection.jsx index de8a4f3e64..8f4a024fdb 100644 --- a/openecomp-ui/src/nfvo-components/grid/GridSection.jsx +++ b/openecomp-ui/src/nfvo-components/grid/GridSection.jsx @@ -14,11 +14,12 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import classnames from 'classnames'; -const GridSection = ({title, children, className, titleClassName}) => { +const GridSection = ({title, children, className = '', titleClassName, hasLastColSet = false}) => { return ( -
    +
    {title &&
    {title}
    }
    {children} @@ -28,7 +29,9 @@ const GridSection = ({title, children, className, titleClassName}) => { }; GridSection.propTypes = { - title: React.PropTypes.string, + title: PropTypes.string, + titleClassName: PropTypes.string, + hasLastColSet: PropTypes.bool }; export default GridSection; diff --git a/openecomp-ui/src/nfvo-components/icon/Icon.jsx b/openecomp-ui/src/nfvo-components/icon/Icon.jsx deleted file mode 100644 index 125577664b..0000000000 --- a/openecomp-ui/src/nfvo-components/icon/Icon.jsx +++ /dev/null @@ -1,45 +0,0 @@ -/*! - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - */ -import React, { Component, PropTypes } from 'react'; - - -export default class Icon extends Component { - - static propTypes = { - image: PropTypes.string.isRequired, - onClick: PropTypes.func, - label: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), - className: PropTypes.string, - iconClassName: PropTypes.string - }; - - static defaultProps = { - label: '', - className: '', - iconClassName: '' - }; - - render() { - let {image, onClick, label, className, iconClassName, ...other} = this.props; - let classes = `icon-component ${className} ${onClick ? 'clickable' : ''}`; - return ( -
    - - {label} -
    - ); - } -} diff --git a/openecomp-ui/src/nfvo-components/input/ExpandableInput.jsx b/openecomp-ui/src/nfvo-components/input/ExpandableInput.jsx index eab1d45ef4..82fbe1deed 100644 --- a/openecomp-ui/src/nfvo-components/input/ExpandableInput.jsx +++ b/openecomp-ui/src/nfvo-components/input/ExpandableInput.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; import Input from 'nfvo-components/input/validation/InputWrapper.jsx'; @@ -76,9 +77,9 @@ class ExpandableInputOpened extends React.Component { class ExpandableInput extends React.Component { static propTypes = { - iconType: React.PropTypes.string, - onChange: React.PropTypes.func, - value: React.PropTypes.string + iconType: PropTypes.string, + onChange: PropTypes.func, + value: PropTypes.string }; state = {showInput: false}; diff --git a/openecomp-ui/src/nfvo-components/input/ToggleInput.jsx b/openecomp-ui/src/nfvo-components/input/ToggleInput.jsx index 23af72a26a..31a8a66d86 100644 --- a/openecomp-ui/src/nfvo-components/input/ToggleInput.jsx +++ b/openecomp-ui/src/nfvo-components/input/ToggleInput.jsx @@ -14,15 +14,16 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; export default class ToggleInput extends React.Component { static propTypes = { - label: React.PropTypes.node, - value: React.PropTypes.bool, - onChange: React.PropTypes.func, - disabled: React.PropTypes.bool + label: PropTypes.node, + value: PropTypes.bool, + onChange: PropTypes.func, + disabled: PropTypes.bool } static defaultProps = { diff --git a/openecomp-ui/src/nfvo-components/input/dualListbox/DualListboxView.jsx b/openecomp-ui/src/nfvo-components/input/dualListbox/DualListboxView.jsx index a3be363ba4..a689c50778 100644 --- a/openecomp-ui/src/nfvo-components/input/dualListbox/DualListboxView.jsx +++ b/openecomp-ui/src/nfvo-components/input/dualListbox/DualListboxView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; import Input from 'nfvo-components/input/validation/InputWrapper.jsx'; @@ -21,17 +22,17 @@ class DualListboxView extends React.Component { static propTypes = { - availableList: React.PropTypes.arrayOf(React.PropTypes.shape({ - id: React.PropTypes.string.isRequired, - name: React.PropTypes.string.isRequired + availableList: PropTypes.arrayOf(PropTypes.shape({ + id: PropTypes.string.isRequired, + name: PropTypes.string.isRequired })), - filterTitle: React.PropTypes.shape({ - left: React.PropTypes.string, - right: React.PropTypes.string + filterTitle: PropTypes.shape({ + left: PropTypes.string, + right: PropTypes.string }), - selectedValuesList: React.PropTypes.arrayOf(React.PropTypes.string), + selectedValuesList: PropTypes.arrayOf(PropTypes.string), - onChange: React.PropTypes.func.isRequired + onChange: PropTypes.func.isRequired }; static defaultProps = { diff --git a/openecomp-ui/src/nfvo-components/input/validation/Form.jsx b/openecomp-ui/src/nfvo-components/input/validation/Form.jsx index 8d53322587..6df0bf9009 100644 --- a/openecomp-ui/src/nfvo-components/input/validation/Form.jsx +++ b/openecomp-ui/src/nfvo-components/input/validation/Form.jsx @@ -15,6 +15,7 @@ */ import React from 'react'; +import PropTypes from 'prop-types'; import ValidationButtons from './ValidationButtons.jsx'; class Form extends React.Component { @@ -31,18 +32,18 @@ class Form extends React.Component { }; static propTypes = { - isValid : React.PropTypes.bool, - formReady : React.PropTypes.bool, - isReadOnlyMode : React.PropTypes.bool, - hasButtons : React.PropTypes.bool, - onSubmit : React.PropTypes.func, - onReset : React.PropTypes.func, - labledButtons: React.PropTypes.bool, - submitButtonText: React.PropTypes.string, - cancelButtonText: React.PropTypes.string, - onValidChange : React.PropTypes.func, - onValidityChanged: React.PropTypes.func, - onValidateForm: React.PropTypes.func + isValid : PropTypes.bool, + formReady : PropTypes.bool, + isReadOnlyMode : PropTypes.bool, + hasButtons : PropTypes.bool, + onSubmit : PropTypes.func, + onReset : PropTypes.func, + labledButtons: PropTypes.bool, + submitButtonText: PropTypes.string, + cancelButtonText: PropTypes.string, + onValidChange : PropTypes.func, + onValidityChanged: PropTypes.func, + onValidateForm: PropTypes.func }; constructor(props) { @@ -124,13 +125,21 @@ class Form extends React.Component { export class TabsForm extends Form { render() { // eslint-disable-next-line no-unused-vars - let {isValid, formReady, onValidateForm, isReadOnlyMode, hasButtons, onSubmit, labledButtons, onValidChange, onValidityChanged, onDataChanged, children, ...formProps} = this.props; + let {submitButtonText, cancelButtonText, isValid, formReady, onValidateForm, isReadOnlyMode, hasButtons, onSubmit, labledButtons, onValidChange, onValidityChanged, onDataChanged, children, + ...formProps} = this.props; return (
    this.form = form} onSubmit={event => this.handleFormValidation(event)}>
    {children}
    - {hasButtons && this.buttons = buttons} isReadOnlyMode={isReadOnlyMode}/>} + {hasButtons && + this.buttons = buttons} + isReadOnlyMode={isReadOnlyMode}/> + } ); } diff --git a/openecomp-ui/src/nfvo-components/input/validation/Input.jsx b/openecomp-ui/src/nfvo-components/input/validation/Input.jsx index eef8fee1ce..9f0e9acca8 100644 --- a/openecomp-ui/src/nfvo-components/input/validation/Input.jsx +++ b/openecomp-ui/src/nfvo-components/input/validation/Input.jsx @@ -17,7 +17,7 @@ import React from 'react'; import ReactDOM from 'react-dom'; import classNames from 'classnames'; import Checkbox from 'react-bootstrap/lib/Checkbox.js'; -import Radio from 'react-bootstrap/lib/Radio.js'; +import Radio from 'sdc-ui/lib/react/Radio.js'; import FormGroup from 'react-bootstrap/lib/FormGroup.js'; import FormControl from 'react-bootstrap/lib/FormControl.js'; import Overlay from 'react-bootstrap/lib/Overlay.js'; @@ -85,7 +85,7 @@ class Input extends React.Component { className={classNames({'required' : isRequired , 'has-error' : !isValid})} onChange={(e)=>this.onChangeCheckBox(e)} disabled={isReadOnlyMode || Boolean(disabled)} - checked={value} + checked={checked} data-test-id={this.props['data-test-id']}>{label}} {type === 'radio' && @@ -93,9 +93,10 @@ class Input extends React.Component { checked={checked} disabled={isReadOnlyMode || Boolean(disabled)} value={value} - onChange={(e)=>this.onChangeRadio(e)} + onChange={(isChecked)=>this.onChangeRadio(isChecked)} inputRef={(input) => this.input = input} - data-test-id={this.props['data-test-id']}>{label}} + label={label} + data-test-id={this.props['data-test-id']} />} {type === 'select' && this.optionSelect(e) } componentClass={type} @@ -156,16 +157,17 @@ class Input extends React.Component { onChangeCheckBox(e) { let {onChange} = this.props; + let checked = e.target.checked; this.setState({ - checked: e.target.checked + checked }); - onChange(e.target.checked); + onChange(checked); } - onChangeRadio(e) { + onChangeRadio(isChecked) { let {onChange} = this.props; this.setState({ - checked: e.target.checked + checked: isChecked }); onChange(this.state.value); } diff --git a/openecomp-ui/src/nfvo-components/input/validation/InputOptions.jsx b/openecomp-ui/src/nfvo-components/input/validation/InputOptions.jsx index 9b11d27c2b..11b07ba9da 100644 --- a/openecomp-ui/src/nfvo-components/input/validation/InputOptions.jsx +++ b/openecomp-ui/src/nfvo-components/input/validation/InputOptions.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import i18n from 'nfvo-utils/i18n/i18n.js'; import classNames from 'classnames'; @@ -26,27 +27,27 @@ export const other = {OTHER: 'Other'}; class InputOptions extends React.Component { static propTypes = { - values: React.PropTypes.arrayOf(React.PropTypes.shape({ - enum: React.PropTypes.string, - title: React.PropTypes.string + values: PropTypes.arrayOf(PropTypes.shape({ + enum: PropTypes.string, + title: PropTypes.string })), - isEnabledOther: React.PropTypes.bool, - label: React.PropTypes.string, - selectedValue: React.PropTypes.string, - multiSelectedEnum: React.PropTypes.oneOfType([ - React.PropTypes.string, - React.PropTypes.array + isEnabledOther: PropTypes.bool, + label: PropTypes.string, + selectedValue: PropTypes.string, + multiSelectedEnum: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.array ]), - selectedEnum: React.PropTypes.string, - otherValue: React.PropTypes.string, - overlayPos: React.PropTypes.string, - onEnumChange: React.PropTypes.func, - onOtherChange: React.PropTypes.func, - onBlur: React.PropTypes.func, - isRequired: React.PropTypes.bool, - isMultiSelect: React.PropTypes.bool, - isValid: React.PropTypes.bool, - disabled: React.PropTypes.bool + selectedEnum: PropTypes.string, + otherValue: PropTypes.string, + overlayPos: PropTypes.string, + onEnumChange: PropTypes.func, + onOtherChange: PropTypes.func, + onBlur: PropTypes.func, + isRequired: PropTypes.bool, + isMultiSelect: PropTypes.bool, + isValid: PropTypes.bool, + disabled: PropTypes.bool }; state = { diff --git a/openecomp-ui/src/nfvo-components/input/validation/InputWrapper.jsx b/openecomp-ui/src/nfvo-components/input/validation/InputWrapper.jsx index 6c8115deee..e440fcda69 100644 --- a/openecomp-ui/src/nfvo-components/input/validation/InputWrapper.jsx +++ b/openecomp-ui/src/nfvo-components/input/validation/InputWrapper.jsx @@ -17,7 +17,7 @@ import React from 'react'; import ReactDOM from 'react-dom'; import classNames from 'classnames'; import Checkbox from 'react-bootstrap/lib/Checkbox.js'; -import Radio from 'react-bootstrap/lib/Radio.js'; +import Radio from 'sdc-ui/lib/react/Radio.js'; import FormGroup from 'react-bootstrap/lib/FormGroup.js'; import FormControl from 'react-bootstrap/lib/FormControl.js'; @@ -72,8 +72,8 @@ class InputWrapper extends React.Component { disabled={isReadOnlyMode || Boolean(disabled)} value={value} ref={(input) => this.inputWrapper = input} - onChange={(e)=>this.onChangeRadio(e)} - data-test-id={this.props['data-test-id']}>{label}} + onChange={(isChecked)=>this.onChangeRadio(isChecked)} label={label} + data-test-id={this.props['data-test-id']} />} {type === 'select' && this.optionSelect(e) } componentClass={type} @@ -119,10 +119,10 @@ class InputWrapper extends React.Component { onChange(e.target.checked); } - onChangeRadio(e) { + onChangeRadio(isChecked) { let {onChange} = this.props; this.setState({ - checked: e.target.checked + checked: isChecked }); onChange(this.state.value); } diff --git a/openecomp-ui/src/nfvo-components/input/validation/Tabs.jsx b/openecomp-ui/src/nfvo-components/input/validation/Tabs.jsx index 6f33536b04..0982c133e6 100644 --- a/openecomp-ui/src/nfvo-components/input/validation/Tabs.jsx +++ b/openecomp-ui/src/nfvo-components/input/validation/Tabs.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import {default as SDCTabs} from 'sdc-ui/lib/react/Tabs.js'; import Overlay from 'react-bootstrap/lib/Overlay.js'; @@ -25,7 +26,7 @@ export default class Tabs extends React.Component { static propTypes = { - children: React.PropTypes.node + children: PropTypes.node }; cloneTab(element) { diff --git a/openecomp-ui/src/nfvo-components/input/validation/ValidationButtons.jsx b/openecomp-ui/src/nfvo-components/input/validation/ValidationButtons.jsx index c3808dd2c3..151d3fe859 100644 --- a/openecomp-ui/src/nfvo-components/input/validation/ValidationButtons.jsx +++ b/openecomp-ui/src/nfvo-components/input/validation/ValidationButtons.jsx @@ -21,6 +21,7 @@ * labledButtons - whether or not to use labeled buttons or icons only */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Button from 'sdc-ui/lib/react/Button.js'; import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; @@ -28,10 +29,10 @@ import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; class ValidationButtons extends React.Component { static propTypes = { - labledButtons: React.PropTypes.bool.isRequired, - isReadOnlyMode: React.PropTypes.bool, - submitButtonText: React.PropTypes.string, - cancelButtonText: React.PropTypes.string + labledButtons: PropTypes.bool.isRequired, + isReadOnlyMode: PropTypes.bool, + submitButtonText: PropTypes.string, + cancelButtonText: PropTypes.string }; state = { @@ -45,10 +46,10 @@ class ValidationButtons extends React.Component {
    {!this.props.isReadOnlyMode ?
    - - + +
    - : + : }
    ); diff --git a/openecomp-ui/src/nfvo-components/listEditor/ListEditorItemView.jsx b/openecomp-ui/src/nfvo-components/listEditor/ListEditorItemView.jsx index bed304b756..60c559a3d1 100644 --- a/openecomp-ui/src/nfvo-components/listEditor/ListEditorItemView.jsx +++ b/openecomp-ui/src/nfvo-components/listEditor/ListEditorItemView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import classnames from 'classnames'; import i18n from 'nfvo-utils/i18n/i18n.js'; import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; @@ -22,11 +23,11 @@ import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModal class ListEditorItem extends React.Component { static propTypes = { - onSelect: React.PropTypes.oneOfType([React.PropTypes.func, React.PropTypes.bool]), - onDelete: React.PropTypes.oneOfType([React.PropTypes.func, React.PropTypes.bool]), - onEdit: React.PropTypes.oneOfType([React.PropTypes.func, React.PropTypes.bool]), - children: React.PropTypes.node, - isReadOnlyMode: React.PropTypes.bool + onSelect: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]), + onDelete: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]), + onEdit: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]), + children: PropTypes.node, + isReadOnlyMode: PropTypes.bool }; render() { diff --git a/openecomp-ui/src/nfvo-components/listEditor/ListEditorView.jsx b/openecomp-ui/src/nfvo-components/listEditor/ListEditorView.jsx index df7d69b4ff..16823b7dc5 100644 --- a/openecomp-ui/src/nfvo-components/listEditor/ListEditorView.jsx +++ b/openecomp-ui/src/nfvo-components/listEditor/ListEditorView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import Button from 'sdc-ui/lib/react/Button.js'; import classnames from 'classnames'; import ExpandableInput from 'nfvo-components/input/ExpandableInput.jsx'; @@ -60,15 +61,15 @@ class ListEditorView extends React.Component { }; static propTypes = { - title: React.PropTypes.string, - plusButtonTitle: React.PropTypes.string, - children: React.PropTypes.node, - filterValue: React.PropTypes.string, - onFilter: React.PropTypes.func, - className: React.PropTypes.string, - isReadOnlyMode: React.PropTypes.bool, - placeholder: React.PropTypes.string, - twoColumns: React.PropTypes.bool + title: PropTypes.string, + plusButtonTitle: PropTypes.string, + children: PropTypes.node, + filterValue: PropTypes.string, + onFilter: PropTypes.func, + className: PropTypes.string, + isReadOnlyMode: PropTypes.bool, + placeholder: PropTypes.string, + twoColumns: PropTypes.bool }; render() { diff --git a/openecomp-ui/src/nfvo-components/listEditor/listEditor.stories.js b/openecomp-ui/src/nfvo-components/listEditor/listEditor.stories.js index 276b05e270..81125c84ba 100644 --- a/openecomp-ui/src/nfvo-components/listEditor/listEditor.stories.js +++ b/openecomp-ui/src/nfvo-components/listEditor/listEditor.stories.js @@ -2,7 +2,7 @@ import React from 'react'; import {storiesOf, action} from '@kadira/storybook'; import ListEditorView from './ListEditorView.jsx'; import ListEditorItemView from './ListEditorItemView.jsx'; -import ListEditorItemViewField from './ListEditorItemViewField.jsx'; +import ListEditorItemField from './ListEditorItemViewField.jsx'; import {text, number} from '@kadira/storybook-addon-knobs'; import {withKnobs} from '@kadira/storybook-addon-knobs'; @@ -13,12 +13,12 @@ function makeChildren({onEdit = false, onDelete = false} = {}) { key={index} onEdit={onEdit ? onEdit : undefined} onDelete={onDelete ? onDelete : undefined}> - +
    {text('field 1', 'Lorum Ipsum')}
    -
    - + +
    {text('field 2', 'Lorum Ipsum')}
    -
    + ) ) ); diff --git a/openecomp-ui/src/nfvo-components/loader/Loader.jsx b/openecomp-ui/src/nfvo-components/loader/Loader.jsx index 675b04c8ea..cbfed1b214 100644 --- a/openecomp-ui/src/nfvo-components/loader/Loader.jsx +++ b/openecomp-ui/src/nfvo-components/loader/Loader.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import {connect} from 'react-redux'; const mapStateToProps = ({loader}) => { @@ -25,7 +26,7 @@ const mapStateToProps = ({loader}) => { class Loader extends React.Component { static propTypes = { - isLoading: React.PropTypes.bool.isRequired + isLoading: PropTypes.bool.isRequired }; static defaultProps = { diff --git a/openecomp-ui/src/nfvo-components/modal/GlobalModal.js b/openecomp-ui/src/nfvo-components/modal/GlobalModal.js index 4e7a1a16a4..a47c42a1fb 100644 --- a/openecomp-ui/src/nfvo-components/modal/GlobalModal.js +++ b/openecomp-ui/src/nfvo-components/modal/GlobalModal.js @@ -15,6 +15,7 @@ */ import React from 'react'; +import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import Modal from 'nfvo-components/modal/Modal.jsx'; @@ -25,7 +26,7 @@ import {actionTypes, typeEnum} from './GlobalModalConstants.js'; const typeClass = { - 'default': 'default', + 'default': 'primary', error: 'negative', warning: 'warning', success: 'positive' @@ -47,11 +48,11 @@ const ModalFooter = ({type, onConfirmed, onDeclined, onClose, confirmationButton return (
    - {onConfirmed && } - + + +
    + {isCollapsed && this.props.children} +
    +
    + ); + } + +}; + +class TextCompare extends React.Component { + render() { + // let rand = Math.random() * (3000 - 1) + 1; + let {yours, theirs, field, type, isObjName, conflictsOnly} = this.props; + let typeYours = typeof yours; + let typeTheirs = typeof theirs; + + let parsedType = `${type}/${field}`.replace(/\/[0-9]+/g,'/index'); + let level = type.split('/').length; + + if (typeYours === 'boolean' || typeTheirs === 'boolean') { + yours = yours ? i18n('Yes') : i18n('No'); + theirs = theirs ? i18n('Yes') : i18n('No'); + } + + + /*if ((typeYours !== 'string' && typeYours !== 'undefined') || (typeTheirs !== 'string' && typeTheirs !== 'undefined')) { + return (
    {field} cannot be parsed for display
    ); + }*/ + let isDiff = yours !== theirs; + if (!isObjName && + ((!isDiff && conflictsOnly) || + (yours === '' && theirs === '') || + (typeYours === 'undefined' && typeTheirs === 'undefined') + ) + ) { + return null; + } + + return ( + + +
    + {i18n(parsedType)} +
    +
    + +
    {yours || (isObjName ? '' : '━━')}
    +
    + +
    {theirs || (isObjName ? '' : '━━')}
    +
    + +
    + ); + } +}; + +class MergeEditorView extends React.Component { + state = { + collapsingSections: {}, + conflictsOnly: false + }; + + render() { + let {conflicts, item, conflictFiles, onResolveConflict, currentScreen, resolution} = this.props; + + return ( +
    + {conflictFiles && this.renderConflictTableTitles()} +
    + {conflictFiles && conflictFiles.sort((a, b) => a.type > b.type).map(file => ( + {this.updateCollapseState(file.id);}} + onResolveConflict={cDetails => onResolveConflict({...cDetails, currentScreen})}> + {(conflicts && conflicts[file.id]) && + this.getUnion(conflicts[file.id].yours, conflicts[file.id].theirs).map(field => { + return this.renderField(field, file, conflicts[file.id].yours[field], conflicts[file.id].theirs[field], resolution); + })} + ))} +
    +
    ); + } + + renderConflictTableTitles() + { + return ( + + {i18n('Page')} + + + {i18n('Local (Me)')} + + + {i18n('Last Committed')} + + + this.setState({conflictsOnly: e}) } /> + + ); + } + // this.setState({conflictsOnly: checked})} /> + + renderObjects(yours, theirs, fileType, field, id, resolution) { + if (equal(yours, theirs)) { + return; + } + let {conflictsOnly} = this.state; + return ( +
    + +
    +
    + {this.getUnion(yours, theirs).map(key => + this.renderField( + key, + {type: `${fileType}/${field}`, id}, + yours && yours[key], + theirs && theirs[key] + ) + )} +
    +
    +
    + ); + } + + renderList(yours = [], theirs = [], type, field, id, resolution) { + let theirsList = theirs.join(', '); + let yoursList = yours.join(', '); + let {conflictsOnly} = this.state; + return (); + } + + renderField(field, file, yours, theirs, resolution) { + if (yours) { + if (Array.isArray(yours)) { + return this.renderList(yours, theirs, file.type, field, file.id, resolution); + } + else if (typeof yours === 'object') { + return this.renderObjects(yours, theirs, file.type, field, file.id, resolution); + } + } else if (theirs) { + if (Array.isArray(theirs)) { + return this.renderList(yours, theirs, file.type, field, file.id, resolution); + } + else if (typeof theirs === 'object') { + return this.renderObjects(yours, theirs, file.type, field, file.id, resolution); + } + } + let {conflictsOnly} = this.state; + return (); + } + + getUnion(yours = {},theirs = {}) { + let yoursKeys = Object.keys(yours); + let theirsKeys = Object.keys(theirs); + let myUn = union(yoursKeys, theirsKeys); + return myUn;//.sort((a, b) => a > b); + } + + updateCollapseState(conflictId) { + const {fetchConflict, item: {id: itemId, version}, /*conflicts*/} = this.props; + let isCollapsed = this.state.collapsingSections[conflictId]; + // if (!isCollapsed && !(conflicts && conflictId in conflicts)) { + if (!isCollapsed) { + fetchConflict({cid: conflictId, itemId, version}); + } + this.setState({ + collapsingSections: { + ...this.state.collapsingSections, + [conflictId]: !isCollapsed + } + }); + } +} + +export default MergeEditorView; diff --git a/openecomp-ui/src/sdc-app/common/modal/ModalContentMapper.js b/openecomp-ui/src/sdc-app/common/modal/ModalContentMapper.js index 8c10beb952..487ada0d88 100644 --- a/openecomp-ui/src/sdc-app/common/modal/ModalContentMapper.js +++ b/openecomp-ui/src/sdc-app/common/modal/ModalContentMapper.js @@ -17,12 +17,18 @@ import SoftwareProductCreation from 'sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreation.js'; import LicenseModelCreation from 'sdc-app/onboarding/licenseModel/creation/LicenseModelCreation.js'; import SoftwareProductComponentImageEditor from 'sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageEditor.js'; +import VersionPageCreation from 'sdc-app/onboarding/versionsPage/creation/VersionsPageCreation.js'; import SubmitErrorResponse from 'nfvo-components/SubmitErrorResponse.jsx'; import ComputeFlavorEditor from 'sdc-app/onboarding/softwareProduct/components/compute/computeComponents/computeFlavor/ComputeFlavorEditor.js'; import NICCreation from 'sdc-app/onboarding/softwareProduct/components/network/NICCreation/NICCreation.js'; import SoftwareProductComponentsNICEditor from 'sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNICEditor.js'; import ComponentCreation from 'sdc-app/onboarding/softwareProduct/components/creation/SoftwareProductComponentCreation.js'; import SoftwareProductDeploymentEditor from 'sdc-app/onboarding/softwareProduct/deployment/editor/SoftwareProductDeploymentEditor.js'; +import PermissionsManager from 'sdc-app/onboarding/permissions/PermissionsManager.js'; +import CommitCommentModal from 'nfvo-components/panel/versionController/components/CommitCommentModal.jsx'; +import Tree from 'nfvo-components/tree/Tree.jsx'; +import MergeEditor from 'sdc-app/common/merge/MergeEditor.js'; +import Revisions from 'sdc-app/onboarding/revisions/Revisions.js'; export const modalContentMapper = { SOFTWARE_PRODUCT_CREATION: 'SOFTWARE_PRODUCT_CREATION', @@ -33,17 +39,29 @@ export const modalContentMapper = { NIC_CREATION: 'NIC_CREATION', COMPONENT_CREATION: 'COMPONENT_CREATION', SOFTWARE_PRODUCT_COMPONENT_IMAGE_EDITOR : 'SOFTWARE_PRODUCT_COMPONENT_IMAGE_EDITOR', - DEPLOYMENT_FLAVOR_EDITOR: 'DEPLOYMENT_FLAVOR_EDITOR' + DEPLOYMENT_FLAVOR_EDITOR: 'DEPLOYMENT_FLAVOR_EDITOR', + MANAGE_PERMISSIONS: 'MANAGE_PERMISSIONS', + VERSION_CREATION: 'VERSION_CREATION', + COMMIT_COMMENT: 'COMMIT_COMMENT', + VERSION_TREE: 'VERSION_TREE', + MERGE_EDITOR: 'MERGE_EDITOR', + REVISIONS_LIST: 'REVISIONS_LIST' }; export const modalContentComponents = { SUMBIT_ERROR_RESPONSE: SubmitErrorResponse, SOFTWARE_PRODUCT_CREATION: SoftwareProductCreation, + VERSION_CREATION: VersionPageCreation, LICENSE_MODEL_CREATION: LicenseModelCreation, COMPONENT_COMPUTE_FLAVOR_EDITOR: ComputeFlavorEditor, NIC_EDITOR: SoftwareProductComponentsNICEditor, NIC_CREATION: NICCreation, COMPONENT_CREATION: ComponentCreation, SOFTWARE_PRODUCT_COMPONENT_IMAGE_EDITOR : SoftwareProductComponentImageEditor, - DEPLOYMENT_FLAVOR_EDITOR: SoftwareProductDeploymentEditor + DEPLOYMENT_FLAVOR_EDITOR: SoftwareProductDeploymentEditor, + MANAGE_PERMISSIONS: PermissionsManager, + COMMIT_COMMENT: CommitCommentModal, + VERSION_TREE: Tree, + MERGE_EDITOR: MergeEditor, + REVISIONS_LIST: Revisions }; diff --git a/openecomp-ui/src/sdc-app/config/Configuration.js b/openecomp-ui/src/sdc-app/config/Configuration.js index 227e36995b..3d9ab8bf72 100644 --- a/openecomp-ui/src/sdc-app/config/Configuration.js +++ b/openecomp-ui/src/sdc-app/config/Configuration.js @@ -50,6 +50,13 @@ const configuration = new Configuration(); configuration.set('restATTPrefix', configuration.get('defaultRestATTPrefix')); configuration.set('appContextPath', configuration.get('appContextPath')); })(configuration); - +(function setDefaultWebsocketConfig(configuration) { + let websocketPort = configuration.get('defaultWebsocketPort'); + if (DEBUG) { + websocketPort = configuration.get('defaultDebugWebsocketPort'); + } + configuration.set('websocketPort', websocketPort); + configuration.set('websocketPath', configuration.get('defaultWebsocketPath')); +})(configuration); export default configuration; diff --git a/openecomp-ui/src/sdc-app/config/config.json b/openecomp-ui/src/sdc-app/config/config.json index 2725cf1310..e73856e5bb 100644 --- a/openecomp-ui/src/sdc-app/config/config.json +++ b/openecomp-ui/src/sdc-app/config/config.json @@ -4,5 +4,8 @@ "build": "dev", "appContextPath" : "/onboarding", "defaultRestPrefix": "/onboarding-api", - "defaultRestATTPrefix": "/sdc1/feProxy/rest" + "defaultRestATTPrefix": "/sdc1/feProxy/rest", + "defaultWebsocketPort" : "8181", + "defaultDebugWebsocketPort" : "9000", + "defaultWebsocketPath" : "notification-api/ws/notificationHandler" } diff --git a/openecomp-ui/src/sdc-app/flows/FlowsListEditorView.jsx b/openecomp-ui/src/sdc-app/flows/FlowsListEditorView.jsx index c5dbb4f909..365b7f1bdf 100644 --- a/openecomp-ui/src/sdc-app/flows/FlowsListEditorView.jsx +++ b/openecomp-ui/src/sdc-app/flows/FlowsListEditorView.jsx @@ -13,8 +13,8 @@ * or implied. See the License for the specific language governing * permissions and limitations under the License. */ -import React, {PropTypes, Component} from 'react'; - +import React, {Component} from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Modal from 'nfvo-components/modal/Modal.jsx'; diff --git a/openecomp-ui/src/sdc-app/flows/SequenceDiagram.jsx b/openecomp-ui/src/sdc-app/flows/SequenceDiagram.jsx index 1add76b598..c128083774 100644 --- a/openecomp-ui/src/sdc-app/flows/SequenceDiagram.jsx +++ b/openecomp-ui/src/sdc-app/flows/SequenceDiagram.jsx @@ -13,7 +13,8 @@ * or implied. See the License for the specific language governing * permissions and limitations under the License. */ -import React, {Component, PropTypes} from 'react'; +import React, {Component} from 'react'; +import PropTypes from 'prop-types'; import Button from 'sdc-ui/lib/react/Button.js'; import Sequencer from 'dox-sequence-diagram-ui'; diff --git a/openecomp-ui/src/sdc-app/heatValidation.app.jsx b/openecomp-ui/src/sdc-app/heatValidation.app.jsx index 6ff3c7375c..5abe3091b3 100644 --- a/openecomp-ui/src/sdc-app/heatValidation.app.jsx +++ b/openecomp-ui/src/sdc-app/heatValidation.app.jsx @@ -24,4 +24,4 @@ import UploadScreen from './heatvalidation/UploadScreen.jsx'; import Application from './Application.jsx'; -ReactDOM.render(, document.getElementById('heat-validation-app')); +ReactDOM.render(, document.getElementById('heat-validation-app')); diff --git a/openecomp-ui/src/sdc-app/heatvalidation/UploadScreenActionHelper.js b/openecomp-ui/src/sdc-app/heatvalidation/UploadScreenActionHelper.js index 4e9120956e..3c41b126e6 100644 --- a/openecomp-ui/src/sdc-app/heatvalidation/UploadScreenActionHelper.js +++ b/openecomp-ui/src/sdc-app/heatvalidation/UploadScreenActionHelper.js @@ -26,7 +26,7 @@ import {actionTypes as HeatSetupActions} from '../onboarding/softwareProduct/att const options = { headers: { - HTTP_CSP_ATTUID: 'validationOnlyVspUser' + USER_ID: 'validationOnlyVspUser' } }; @@ -37,16 +37,18 @@ function getTimestampString() { return `${date.getFullYear()}-${z(date.getMonth())}-${z(date.getDate())}_${z(date.getHours())}-${z(date.getMinutes())}`; } -function fetchVspId() { +function fetchVspIdAndVersion() { let vspId = sessionStorage.getItem('validationAppVspId'); + let versionId = sessionStorage.getItem('validationAppVersionId'); if (vspId) { - return Promise.resolve({value: vspId}); + return Promise.resolve({value: vspId, versionId}); }else { return RestAPIUtil.fetch('/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/validation-vsp', options) .then(response => { - sessionStorage.setItem('validationAppVspId', response.value); - return Promise.resolve(response); + sessionStorage.setItem('validationAppVspId', response.itemId); + sessionStorage.setItem('validationAppVersionId', response.version.id); + return Promise.resolve({value: response.itemId, versionId: response.version.id}); }); } @@ -82,16 +84,16 @@ function showFileSaveDialog({blob, xhr, defaultFilename, addTimestamp}) { function uploadFile(formData) { - return fetchVspId() + return fetchVspIdAndVersion() .then(response => { - return RestAPIUtil.post(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/0.1/orchestration-template-candidate`, formData, options); + return RestAPIUtil.post(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/${response.versionId}/orchestration-template-candidate`, formData, options); }); } function loadSoftwareProductHeatCandidate(dispatch){ - return fetchVspId() + return fetchVspIdAndVersion() .then(response => { - return RestAPIUtil.fetch(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/0.1/orchestration-template-candidate/manifest`, options) + return RestAPIUtil.fetch(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/${response.versionId}/orchestration-template-candidate/manifest`, options) .then(response => dispatch({ type: HeatSetupActions.MANIFEST_LOADED, response @@ -100,9 +102,9 @@ function loadSoftwareProductHeatCandidate(dispatch){ } function updateHeatCandidate(dispatch, heatCandidate) { - return fetchVspId() + return fetchVspIdAndVersion() .then(response => { - return RestAPIUtil.put(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/0.1/orchestration-template-candidate/manifest`, + return RestAPIUtil.put(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/${response.versionId}/orchestration-template-candidate/manifest`, heatCandidate.heatData, options) .then(null, error => { dispatch({ @@ -122,16 +124,16 @@ function updateHeatCandidate(dispatch, heatCandidate) { } function fetchSoftwareProduct() { - return fetchVspId() + return fetchVspIdAndVersion() .then(response => { - return RestAPIUtil.fetch(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/0.1`, options); + return RestAPIUtil.fetch(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/${response.versionId}`, options); }); } function downloadHeatFile() { - return fetchVspId() + return fetchVspIdAndVersion() .then(response => { - RestAPIUtil.fetch(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/0.1/orchestration-template-candidate`, { + RestAPIUtil.fetch(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/${response.versionId}/orchestration-template-candidate`, { ...options, dataType: 'binary' }) @@ -145,9 +147,9 @@ function downloadHeatFile() { } function processAndValidateHeatCandidate(dispatch) { - return fetchVspId() + return fetchVspIdAndVersion() .then(response => { - return RestAPIUtil.put(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/0.1/orchestration-template-candidate/process`, {}, options) + return RestAPIUtil.put(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/${response.versionId}/orchestration-template-candidate/process`, {}, options) .then(response => { if (response.status === 'Success') { fetchSoftwareProduct().then(response => { diff --git a/openecomp-ui/src/sdc-app/onboarding/GridStyling.stories.js b/openecomp-ui/src/sdc-app/onboarding/GridStyling.stories.js new file mode 100644 index 0000000000..81a29cf046 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/GridStyling.stories.js @@ -0,0 +1,221 @@ +import React from 'react'; +import {storiesOf} from '@kadira/storybook'; +import {withKnobs} from '@kadira/storybook-addon-knobs'; + +import GridSection from 'nfvo-components/grid/GridSection.jsx'; +import GridItem from 'nfvo-components/grid/GridItem.jsx'; + + +const stories = storiesOf('GridColumns', module); +stories.addDecorator(withKnobs); + +var divStyle = { + 'border-style': 'solid', + 'border-size': 1 +}; + +const myDiv = (
    Text Text Text
    ); + +stories + .add('Grid Options', () => ( +
    + + + {myDiv} + + + {myDiv} + + + + + + {myDiv} + + + {myDiv} + + + + + + {myDiv} + + + {myDiv} + + + +
    + )) + .add('Last Column', () => ( + +
    + + + {myDiv} + + + {myDiv} + + + + + {myDiv} + + + {myDiv} + + + {myDiv} + + + {myDiv} + + + + + {myDiv} + + + {myDiv} + + + {myDiv} + + + + + {myDiv} + + + {myDiv} + + + {myDiv} + + + + + {myDiv} + + + + + {myDiv} + + + {myDiv} + + + + + {myDiv} + + + {myDiv} + + +
    + )) + .add('No Last Column', () => ( +
    + + + {myDiv} + + + {myDiv} + + + + + {myDiv} + + + {myDiv} + + + {myDiv} + + + {myDiv} + + + + + {myDiv} + + + {myDiv} + + + {myDiv} + + + + + {myDiv} + + + {myDiv} + + + {myDiv} + + + + + {myDiv} + + + + + {myDiv} + + + {myDiv} + + + + + {myDiv} + + + {myDiv} + + +
    + )) .add('Test LKG form', () => ( +
    + + + {myDiv} + + + {myDiv} + + + {myDiv} + + + {myDiv} + + + {myDiv} + + + {myDiv} + + + {myDiv} + + + {myDiv} + + +
    1
    +
    +
    +
    +)); \ No newline at end of file diff --git a/openecomp-ui/src/sdc-app/onboarding/OnboardingActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/OnboardingActionHelper.js index 2788d4db92..794f5c1781 100644 --- a/openecomp-ui/src/sdc-app/onboarding/OnboardingActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/OnboardingActionHelper.js @@ -13,6 +13,9 @@ * or implied. See the License for the specific language governing * permissions and limitations under the License. */ +import UsersActionHelper from './users/UsersActionHelper.js'; +import VersionsPageActionHelper from './versionsPage/VersionsPageActionHelper.js'; +import PermissionsActionHelper from './permissions/PermissionsActionHelper.js'; import LicenseModelActionHelper from './licenseModel/LicenseModelActionHelper.js'; import LicenseAgreementActionHelper from './licenseModel/licenseAgreement/LicenseAgreementActionHelper.js'; import FeatureGroupsActionHelper from './licenseModel/featureGroups/FeatureGroupsActionHelper.js'; @@ -28,13 +31,15 @@ import SoftwareProductComponentsNetworkActionHelper from './softwareProduct/comp import SoftwareProductDependenciesActionHelper from './softwareProduct/dependencies/SoftwareProductDependenciesActionHelper.js'; import ComputeFlavorActionHelper from './softwareProduct/components/compute/ComputeFlavorActionHelper.js'; import OnboardActionHelper from './onboard/OnboardActionHelper.js'; +import MergeEditorActionHelper from 'sdc-app/common/merge/MergeEditorActionHelper.js'; +// import {SyncStates} from 'sdc-app/common/merge/MergeEditorConstants.js'; import SoftwareProductComponentsMonitoringAction from './softwareProduct/components/monitoring/SoftwareProductComponentsMonitoringActionHelper.js'; import {actionTypes, enums} from './OnboardingConstants.js'; -import SoftwareProductComponentsImageActionHelper from './softwareProduct/components/images/SoftwareProductComponentsImageActionHelper.js'; -import {navigationItems as SoftwareProductNavigationItems, actionTypes as SoftwareProductActionTypes, onboardingOriginTypes} from 'sdc-app/onboarding/softwareProduct/SoftwareProductConstants.js'; +import {actionTypes as SoftwareProductActionTypes, onboardingOriginTypes} from 'sdc-app/onboarding/softwareProduct/SoftwareProductConstants.js'; import ActivityLogActionHelper from 'sdc-app/common/activity-log/ActivityLogActionHelper.js'; +import ItemsHelper from 'sdc-app/common/helpers/ItemsHelper.js'; +import SoftwareProductComponentsImageActionHelper from './softwareProduct/components/images/SoftwareProductComponentsImageActionHelper.js'; import licenseModelOverviewActionHelper from 'sdc-app/onboarding/licenseModel/overview/licenseModelOverviewActionHelper.js'; -import store from 'sdc-app/AppStore.js'; import {tabsMapping as attachmentsTabsMapping} from 'sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachmentsConstants.js'; import SoftwareProductAttachmentsActionHelper from 'sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachmentsActionHelper.js'; @@ -49,21 +54,25 @@ function setCurrentScreen(dispatch, screen, props = {}) { }); } -function getCurrentLicenseModelVersion(licenseModelId) { - return store.getState().licenseModelList.find(({id}) => id === licenseModelId).version; -} - -function getCurrentSoftwareProductVersion(softwareProductId) { - return store.getState().softwareProductList.find(({id}) => id === softwareProductId).version; +export function updateCurrentScreenProps(dispatch, props = {}) { + dispatch({ + type: actionTypes.UPDATE_CURRENT_SCREEN_PROPS, + props + }); } -export default { +const OnboardingActionHelper = { - navigateToOnboardingCatalog(dispatch) { + loadItemsLists(dispatch) { LicenseModelActionHelper.fetchLicenseModels(dispatch); LicenseModelActionHelper.fetchFinalizedLicenseModels(dispatch); SoftwareProductActionHelper.fetchSoftwareProductList(dispatch); SoftwareProductActionHelper.fetchFinalizedSoftwareProductList(dispatch); + }, + + navigateToOnboardingCatalog(dispatch) { + UsersActionHelper.fetchUsersList(dispatch); + this.loadItemsLists(dispatch); OnboardActionHelper.resetOnboardStore(dispatch); setCurrentScreen(dispatch, enums.SCREEN.ONBOARDING_CATALOG); }, @@ -79,6 +88,7 @@ export default { } return SoftwareProductActionHelper.updateSoftwareProduct(dispatch, { softwareProduct: dataToSave.softwareProduct, + version, qdata: dataToSave.qdata }); } @@ -86,25 +96,19 @@ export default { }, navigateToLicenseModelOverview(dispatch, {licenseModelId, version}) { - if (!version) { - version = getCurrentLicenseModelVersion(licenseModelId); - } /** * TODO change to specific rest */ LicenseModelActionHelper.fetchLicenseModelById(dispatch, {licenseModelId, version}).then(() => { - LicenseModelActionHelper.fetchLicenseModelItems(dispatch, {licenseModelId, version}).then(() =>{ + LicenseModelActionHelper.fetchLicenseModelItems(dispatch, {licenseModelId, version}).then(() => { setCurrentScreen(dispatch, enums.SCREEN.LICENSE_MODEL_OVERVIEW, {licenseModelId, version}); }); licenseModelOverviewActionHelper.selectVLMListView(dispatch, {buttonTab: null}); }); }, navigateToLicenseAgreements(dispatch, {licenseModelId, version}) { - if(!version) { - version = getCurrentLicenseModelVersion(licenseModelId); - } LicenseAgreementActionHelper.fetchLicenseAgreementList(dispatch, {licenseModelId, version}); LicenseModelActionHelper.fetchLicenseModelById(dispatch, {licenseModelId, version}).then(() => { setCurrentScreen(dispatch, enums.SCREEN.LICENSE_AGREEMENTS, {licenseModelId, version}); @@ -112,70 +116,45 @@ export default { }, navigateToFeatureGroups(dispatch, {licenseModelId, version}) { - if(!version) { - version = getCurrentLicenseModelVersion(licenseModelId); - } FeatureGroupsActionHelper.fetchFeatureGroupsList(dispatch, {licenseModelId, version}); setCurrentScreen(dispatch, enums.SCREEN.FEATURE_GROUPS, {licenseModelId, version}); }, navigateToEntitlementPools(dispatch, {licenseModelId, version}) { - if(!version) { - version = getCurrentLicenseModelVersion(licenseModelId); - } EntitlementPoolsActionHelper.fetchEntitlementPoolsList(dispatch, {licenseModelId, version}); setCurrentScreen(dispatch, enums.SCREEN.ENTITLEMENT_POOLS, {licenseModelId, version}); }, navigateToLicenseKeyGroups(dispatch, {licenseModelId, version}) { - if(!version) { - version = getCurrentLicenseModelVersion(licenseModelId); - } LicenseKeyGroupsActionHelper.fetchLicenseKeyGroupsList(dispatch, {licenseModelId, version}); setCurrentScreen(dispatch, enums.SCREEN.LICENSE_KEY_GROUPS, {licenseModelId, version}); }, navigateToLicenseModelActivityLog(dispatch, {licenseModelId, version}){ - if(!version) { - version = getCurrentLicenseModelVersion(licenseModelId); - } ActivityLogActionHelper.fetchActivityLog(dispatch, {itemId: licenseModelId, versionId: version.id}); setCurrentScreen(dispatch, enums.SCREEN.ACTIVITY_LOG, {licenseModelId, version}); }, - navigateToSoftwareProductLandingPage(dispatch, {softwareProductId, licenseModelId, version, licensingVersion}) { - - if (!version) { - version = getCurrentSoftwareProductVersion(softwareProductId); - } - + navigateToSoftwareProductLandingPage(dispatch, {softwareProductId, version}) { SoftwareProductComponentsActionHelper.clearComponentsStore(dispatch); SoftwareProductActionHelper.fetchSoftwareProduct(dispatch, {softwareProductId, version}).then(response => { - if(!licensingVersion) { - licensingVersion = response[0].licensingVersion; - if (!licensingVersion) { - licensingVersion = {id: '1.0', label: '1.0'}; - } - } - if (!licenseModelId) { - licenseModelId = response[0].vendorId; - } - - const newVersion = response[0].version ? response[0].version : version; - + let {vendorId: licenseModelId, licensingVersion} = response[0]; SoftwareProductActionHelper.loadSoftwareProductDetailsData(dispatch, {licenseModelId, licensingVersion}); - - SoftwareProductComponentsActionHelper.fetchSoftwareProductComponents(dispatch, {softwareProductId, version: newVersion}); + SoftwareProductComponentsActionHelper.fetchSoftwareProductComponents(dispatch, {softwareProductId, version: version}); if(response[0].onboardingOrigin === onboardingOriginTypes.ZIP) { - SoftwareProductActionHelper.loadSoftwareProductHeatCandidate(dispatch, {softwareProductId, version: newVersion}); + SoftwareProductActionHelper.loadSoftwareProductHeatCandidate(dispatch, {softwareProductId, version: version}); } - setCurrentScreen(dispatch, enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, {softwareProductId, licenseModelId, version: newVersion}); + setCurrentScreen(dispatch, enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, {softwareProductId, licenseModelId, version}); }); }, navigateToSoftwareProductDetails(dispatch, {softwareProductId, version}) { - SoftwareProductActionHelper.fetchSoftwareProduct(dispatch, {softwareProductId, version}); - setCurrentScreen(dispatch, enums.SCREEN.SOFTWARE_PRODUCT_DETAILS, {softwareProductId, version}); + SoftwareProductActionHelper.fetchSoftwareProduct(dispatch, {softwareProductId, version}).then(response => { + let {vendorId: licenseModelId, licensingVersion} = response[0]; + SoftwareProductActionHelper.loadLicensingVersionsList(dispatch, {licenseModelId}); + SoftwareProductActionHelper.loadSoftwareProductDetailsData(dispatch, {licenseModelId, licensingVersion}); + setCurrentScreen(dispatch, enums.SCREEN.SOFTWARE_PRODUCT_DETAILS, {softwareProductId, version}); + }); }, navigateToSoftwareProductAttachmentsSetupTab(dispatch, {softwareProductId, version}) { @@ -183,7 +162,6 @@ export default { SoftwareProductAttachmentsActionHelper.setActiveTab(dispatch, {activeTab: attachmentsTabsMapping.SETUP}); setCurrentScreen(dispatch, enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS, {softwareProductId, version}); }, - navigateToSoftwareProductAttachmentsValidationTab(dispatch, {softwareProductId, version}) { SoftwareProductActionHelper.processAndValidateHeatCandidate(dispatch, {softwareProductId, version}).then(() => { SoftwareProductAttachmentsActionHelper.setActiveTab(dispatch, {activeTab: attachmentsTabsMapping.VALIDATION}); @@ -206,8 +184,15 @@ export default { }, navigateToSoftwareProductDependencies(dispatch, {softwareProductId, version}) { - SoftwareProductDependenciesActionHelper.fetchDependencies(dispatch, {softwareProductId, version}); - setCurrentScreen(dispatch, enums.SCREEN.SOFTWARE_PRODUCT_DEPENDENCIES, {softwareProductId, version}); + SoftwareProductComponentsActionHelper.fetchSoftwareProductComponents(dispatch, {softwareProductId, version}).then(result => { + if(result.listCount >= 2) { + SoftwareProductDependenciesActionHelper.fetchDependencies(dispatch, {softwareProductId, version}); + setCurrentScreen(dispatch, enums.SCREEN.SOFTWARE_PRODUCT_DEPENDENCIES, {softwareProductId, version}); + } + else { + this.navigateToSoftwareProductLandingPage(dispatch, {softwareProductId, version}); + } + }); }, navigateToSoftwareProductComponents(dispatch, {softwareProductId, version}) { @@ -268,8 +253,8 @@ export default { dispatch({ type: SoftwareProductActionTypes.TOGGLE_NAVIGATION_ITEM, mapOfExpandedIds: { - [SoftwareProductNavigationItems.COMPONENTS]: true, - [SoftwareProductNavigationItems.COMPONENTS + '|' + componentId]: true + [enums.SCREEN.SOFTWARE_PRODUCT_COMPONENTS]: true, + [enums.SCREEN.SOFTWARE_PRODUCT_COMPONENTS + '|' + componentId]: true } }); }, @@ -288,11 +273,44 @@ export default { setCurrentScreen(dispatch, enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_IMAGES, {softwareProductId, version, componentId}); }, + navigateToVersionsPage(dispatch, {itemType, itemId, itemName, additionalProps, users}) { + PermissionsActionHelper.fetchItemUsers(dispatch, {itemId, allUsers: users}); + VersionsPageActionHelper.selectNone(dispatch); + VersionsPageActionHelper.fetchVersions(dispatch, {itemType, itemId}).then(() => { + setCurrentScreen(dispatch, enums.SCREEN.VERSIONS_PAGE, {itemType, itemId, itemName, additionalProps}); + }); + }, + + checkMergeStatus(dispatch, {itemId, versionId, version}) { + return ItemsHelper.fetchVersion({itemId, versionId}).then(response => { + let state = response && response.state || {}; + let {synchronizationState} = state; + // let inMerge = synchronizationState === SyncStates.MERGE; + MergeEditorActionHelper.fetchConflicts(dispatch, {itemId, version}).then(data => { + dispatch({ + type: actionTypes.CHECK_MERGE_STATUS, + synchronizationState, + conflictInfoList: data.conflictInfoList + }); + }); + }); + }, + + forceBreadCrumbsUpdate(dispatch) { + dispatch({ + type: actionTypes.SET_CURRENT_SCREEN, + currentScreen: { + forceBreadCrumbsUpdate: true + } + }); + }, + updateCurrentScreenVersion(dispatch, version) { dispatch({ type: actionTypes.SET_CURRENT_SCREEN_VERSION, version }); } - }; + +export default OnboardingActionHelper; diff --git a/openecomp-ui/src/sdc-app/onboarding/OnboardingConstants.js b/openecomp-ui/src/sdc-app/onboarding/OnboardingConstants.js index 1ce8605b63..5b33fc2099 100644 --- a/openecomp-ui/src/sdc-app/onboarding/OnboardingConstants.js +++ b/openecomp-ui/src/sdc-app/onboarding/OnboardingConstants.js @@ -21,63 +21,80 @@ export const actionTypes = keyMirror({ SET_CURRENT_SCREEN: null, SET_CURRENT_LICENSE_MODEL: null, SET_CURRENT_SCREEN_VERSION: null, + UPDATE_CURRENT_SCREEN_PROPS: null, + UPDATE_ITEM_STATUS: null }); -export const enums = keyMirror({ +export const screenTypes = keyMirror({ + LICENSE_MODEL: null, + SOFTWARE_PRODUCT: null, + SOFTWARE_PRODUCT_COMPONENT_DEFAULT_GENERAL: null +}); + +const breadcrumbsEnum = { + LICENSE_MODEL: 'LICENSE_MODEL', + VERSIONS_PAGE: 'VERSIONS_PAGE', + LICENSE_MODEL_OVERVIEW: 'LICENSE_MODEL_OVERVIEW', + LICENSE_AGREEMENTS: 'LICENSE_AGREEMENTS', + FEATURE_GROUPS: 'FEATURE_GROUPS', + ENTITLEMENT_POOLS: 'ENTITLEMENT_POOLS', + LICENSE_KEY_GROUPS: 'LICENSE_KEY_GROUPS', + ACTIVITY_LOG: 'ACTIVITY_LOG', - BREADCRUMS: { - LICENSE_MODEL: 'LICENSE_MODEL', - LICENSE_MODEL_OVERVIEW: 'LICENSE_MODEL_OVERVIEW', - LICENSE_AGREEMENTS: 'LICENSE_AGREEMENTS', - FEATURE_GROUPS: 'FEATURE_GROUPS', - ENTITLEMENT_POOLS: 'ENTITLEMENT_POOLS', - LICENSE_KEY_GROUPS: 'LICENSE_KEY_GROUPS', - ACTIVITY_LOG: 'ACTIVITY_LOG', + SOFTWARE_PRODUCT: 'SOFTWARE_PRODUCT', + SOFTWARE_PRODUCT_VERSIONS_PAGE: 'SOFTWARE_PRODUCT_VERSIONS_PAGE', + SOFTWARE_PRODUCT_LANDING_PAGE: 'SOFTWARE_PRODUCT_LANDING_PAGE', + SOFTWARE_PRODUCT_DETAILS: 'SOFTWARE_PRODUCT_DETAILS', + SOFTWARE_PRODUCT_ATTACHMENTS: 'SOFTWARE_PRODUCT_ATTACHMENTS', + SOFTWARE_PRODUCT_PROCESSES: 'SOFTWARE_PRODUCT_PROCESSES', + SOFTWARE_PRODUCT_DEPLOYMENT: 'SOFTWARE_PRODUCT_DEPLOYMENT', + SOFTWARE_PRODUCT_NETWORKS: 'SOFTWARE_PRODUCT_NETWORKS', + SOFTWARE_PRODUCT_DEPENDENCIES: 'SOFTWARE_PRODUCT_DEPENDENCIES', + SOFTWARE_PRODUCT_ACTIVITY_LOG: 'SOFTWARE_PRODUCT_ACTIVITY_LOG', + SOFTWARE_PRODUCT_COMPONENTS: 'SOFTWARE_PRODUCT_COMPONENTS', + SOFTWARE_PRODUCT_COMPONENT_PROCESSES: 'SOFTWARE_PRODUCT_COMPONENT_PROCESSES', + SOFTWARE_PRODUCT_COMPONENT_NETWORK: 'SOFTWARE_PRODUCT_COMPONENT_NETWORK', + SOFTWARE_PRODUCT_COMPONENT_STORAGE: 'SOFTWARE_PRODUCT_COMPONENT_STORAGE', + SOFTWARE_PRODUCT_COMPONENT_GENERAL: 'SOFTWARE_PRODUCT_COMPONENT_GENERAL', + SOFTWARE_PRODUCT_COMPONENT_COMPUTE: 'SOFTWARE_PRODUCT_COMPONENT_COMPUTE', + SOFTWARE_PRODUCT_COMPONENT_LOAD_BALANCING: 'SOFTWARE_PRODUCT_COMPONENT_LOAD_BALANCING', + SOFTWARE_PRODUCT_COMPONENT_MONITORING: 'SOFTWARE_PRODUCT_COMPONENT_MONITORING', + SOFTWARE_PRODUCT_COMPONENT_IMAGES: 'SOFTWARE_PRODUCT_COMPONENT_IMAGES' +}; + +export const enums = keyMirror({ - SOFTWARE_PRODUCT: 'SOFTWARE_PRODUCT', - SOFTWARE_PRODUCT_LANDING_PAGE: 'SOFTWARE_PRODUCT_LANDING_PAGE', - SOFTWARE_PRODUCT_DETAILS: 'SOFTWARE_PRODUCT_DETAILS', - SOFTWARE_PRODUCT_ATTACHMENTS: 'SOFTWARE_PRODUCT_ATTACHMENTS', - SOFTWARE_PRODUCT_PROCESSES: 'SOFTWARE_PRODUCT_PROCESSES', - SOFTWARE_PRODUCT_DEPLOYMENT: 'SOFTWARE_PRODUCT_DEPLOYMENT', - SOFTWARE_PRODUCT_NETWORKS: 'SOFTWARE_PRODUCT_NETWORKS', - SOFTWARE_PRODUCT_DEPENDENCIES: 'SOFTWARE_PRODUCT_DEPENDENCIES', - SOFTWARE_PRODUCT_ACTIVITY_LOG: 'SOFTWARE_PRODUCT_ACTIVITY_LOG', - SOFTWARE_PRODUCT_COMPONENTS: 'SOFTWARE_PRODUCT_COMPONENTS', - SOFTWARE_PRODUCT_COMPONENT_PROCESSES: 'SOFTWARE_PRODUCT_COMPONENT_PROCESSES', - SOFTWARE_PRODUCT_COMPONENT_STORAGE: 'SOFTWARE_PRODUCT_COMPONENT_STORAGE', - SOFTWARE_PRODUCT_COMPONENT_GENERAL: 'SOFTWARE_PRODUCT_COMPONENT_GENERAL', - SOFTWARE_PRODUCT_COMPONENT_COMPUTE: 'SOFTWARE_PRODUCT_COMPONENT_COMPUTE', - SOFTWARE_PRODUCT_COMPONENT_LOAD_BALANCING: 'SOFTWARE_PRODUCT_COMPONENT_LOAD_BALANCING', - SOFTWARE_PRODUCT_COMPONENT_MONITORING: 'SOFTWARE_PRODUCT_COMPONENT_MONITORING', - SOFTWARE_PRODUCT_COMPONENT_IMAGES: 'SOFTWARE_PRODUCT_COMPONENT_IMAGES' - }, + BREADCRUMS: {...breadcrumbsEnum}, SCREEN: { - ONBOARDING_CATALOG: null, - LICENSE_MODEL_OVERVIEW: null, - LICENSE_AGREEMENTS: null, - FEATURE_GROUPS: null, - ENTITLEMENT_POOLS: null, - LICENSE_KEY_GROUPS: null, - ACTIVITY_LOG: null, + ONBOARDING_CATALOG: 'ONBOARDING_CATALOG', + VERSIONS_PAGE: breadcrumbsEnum.VERSIONS_PAGE, + LICENSE_MODEL_OVERVIEW: breadcrumbsEnum.LICENSE_MODEL_OVERVIEW, + LICENSE_AGREEMENTS: breadcrumbsEnum.LICENSE_AGREEMENTS, + FEATURE_GROUPS: breadcrumbsEnum.FEATURE_GROUPS, + ENTITLEMENT_POOLS: breadcrumbsEnum.ENTITLEMENT_POOLS, + LICENSE_KEY_GROUPS: breadcrumbsEnum.LICENSE_KEY_GROUPS, + ACTIVITY_LOG: breadcrumbsEnum.ACTIVITY_LOG, - SOFTWARE_PRODUCT_LANDING_PAGE: null, - SOFTWARE_PRODUCT_DETAILS: null, - SOFTWARE_PRODUCT_ATTACHMENTS: null, - SOFTWARE_PRODUCT_PROCESSES: null, - SOFTWARE_PRODUCT_DEPLOYMENT: null, - SOFTWARE_PRODUCT_NETWORKS: null, - SOFTWARE_PRODUCT_DEPENDENCIES: null, - SOFTWARE_PRODUCT_ACTIVITY_LOG: null, - SOFTWARE_PRODUCT_COMPONENTS: null, - SOFTWARE_PRODUCT_COMPONENT_PROCESSES: null, - SOFTWARE_PRODUCT_COMPONENT_COMPUTE: null, - SOFTWARE_PRODUCT_COMPONENT_STORAGE: null, - SOFTWARE_PRODUCT_COMPONENT_NETWORK: null, - SOFTWARE_PRODUCT_COMPONENT_GENERAL: null, - SOFTWARE_PRODUCT_COMPONENT_LOAD_BALANCING: null, - SOFTWARE_PRODUCT_COMPONENT_MONITORING: null, - SOFTWARE_PRODUCT_COMPONENT_IMAGES: null + SOFTWARE_PRODUCT_VERSIONS_PAGE: breadcrumbsEnum.SOFTWARE_PRODUCT_VERSIONS_PAGE, + SOFTWARE_PRODUCT_LANDING_PAGE: breadcrumbsEnum.SOFTWARE_PRODUCT_LANDING_PAGE, + SOFTWARE_PRODUCT_DETAILS: breadcrumbsEnum.SOFTWARE_PRODUCT_DETAILS, + SOFTWARE_PRODUCT_ATTACHMENTS: breadcrumbsEnum.SOFTWARE_PRODUCT_ATTACHMENTS, + SOFTWARE_PRODUCT_ATTACHMENTS_SETUP: 'SOFTWARE_PRODUCT_ATTACHMENTS_SETUP', + SOFTWARE_PRODUCT_ATTACHMENTS_VALIDATION: 'SOFTWARE_PRODUCT_ATTACHMENTS_VALIDATION', + SOFTWARE_PRODUCT_PROCESSES: breadcrumbsEnum.SOFTWARE_PRODUCT_PROCESSES, + SOFTWARE_PRODUCT_DEPLOYMENT: breadcrumbsEnum.SOFTWARE_PRODUCT_DEPLOYMENT, + SOFTWARE_PRODUCT_NETWORKS: breadcrumbsEnum.SOFTWARE_PRODUCT_NETWORKS, + SOFTWARE_PRODUCT_DEPENDENCIES: breadcrumbsEnum.SOFTWARE_PRODUCT_DEPENDENCIES, + SOFTWARE_PRODUCT_ACTIVITY_LOG: breadcrumbsEnum.SOFTWARE_PRODUCT_ACTIVITY_LOG, + SOFTWARE_PRODUCT_COMPONENTS: breadcrumbsEnum.SOFTWARE_PRODUCT_COMPONENTS, + SOFTWARE_PRODUCT_COMPONENT_PROCESSES: breadcrumbsEnum.SOFTWARE_PRODUCT_COMPONENT_PROCESSES, + SOFTWARE_PRODUCT_COMPONENT_COMPUTE: breadcrumbsEnum.SOFTWARE_PRODUCT_COMPONENT_COMPUTE, + SOFTWARE_PRODUCT_COMPONENT_STORAGE: breadcrumbsEnum.SOFTWARE_PRODUCT_COMPONENT_STORAGE, + SOFTWARE_PRODUCT_COMPONENT_NETWORK: breadcrumbsEnum.SOFTWARE_PRODUCT_COMPONENT_NETWORK, + SOFTWARE_PRODUCT_COMPONENT_GENERAL: breadcrumbsEnum.SOFTWARE_PRODUCT_COMPONENT_GENERAL, + SOFTWARE_PRODUCT_COMPONENT_LOAD_BALANCING: breadcrumbsEnum.SOFTWARE_PRODUCT_COMPONENT_LOAD_BALANCING, + SOFTWARE_PRODUCT_COMPONENT_MONITORING: breadcrumbsEnum.SOFTWARE_PRODUCT_COMPONENT_MONITORING, + SOFTWARE_PRODUCT_COMPONENT_IMAGES: breadcrumbsEnum.SOFTWARE_PRODUCT_COMPONENT_IMAGES } }); diff --git a/openecomp-ui/src/sdc-app/onboarding/OnboardingPunchOut.jsx b/openecomp-ui/src/sdc-app/onboarding/OnboardingPunchOut.jsx index c1f3251281..905712003a 100644 --- a/openecomp-ui/src/sdc-app/onboarding/OnboardingPunchOut.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/OnboardingPunchOut.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import {connect} from 'react-redux'; import isEqual from 'lodash/isEqual.js'; @@ -23,8 +24,10 @@ import i18n from 'nfvo-utils/i18n/i18n.js'; import Application from 'sdc-app/Application.jsx'; import store from 'sdc-app/AppStore.js'; import Configuration from 'sdc-app/config/Configuration.js'; +import ScreensHelper from 'sdc-app/common/helpers/ScreensHelper.js'; import Onboard from './onboard/Onboard.js'; +import VersionsPage from './versionsPage/VersionsPage.js'; import LicenseModel from './licenseModel/LicenseModel.js'; import LicenseModelOverview from './licenseModel/overview/LicenseModelOverview.js'; import ActivityLog from 'sdc-app/common/activity-log/ActivityLog.js'; @@ -51,27 +54,21 @@ import SoftwareProductComponentsCompute from './softwareProduct/components/compu import SoftwareProductComponentLoadBalancing from './softwareProduct/components/loadBalancing/SoftwareProductComponentLoadBalancing.js'; import SoftwareProductComponentsImageList from './softwareProduct/components/images/SoftwareProductComponentsImageList.js'; import SoftwareProductComponentsMonitoring from './softwareProduct/components/monitoring/SoftwareProductComponentsMonitoring.js'; -import { - navigationItems as SoftwareProductNavigationItems, - onboardingMethod as onboardingMethodTypes, - actionTypes as SoftwareProductActionTypes, - onboardingOriginTypes -} from 'sdc-app/onboarding/softwareProduct/SoftwareProductConstants.js'; +import {onboardingMethod as onboardingMethodTypes, onboardingOriginTypes} from 'sdc-app/onboarding/softwareProduct/SoftwareProductConstants.js'; -import {statusEnum as VCItemStatus} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; +import {itemTypes} from './versionsPage/VersionsPageConstants.js'; import HeatSetupActionHelper from './softwareProduct/attachments/setup/HeatSetupActionHelper.js'; -import {actionTypes, enums} from './OnboardingConstants.js'; +import {actionTypes, enums, screenTypes} from './OnboardingConstants.js'; import OnboardingActionHelper from './OnboardingActionHelper.js'; - class OnboardingView extends React.Component { static propTypes = { - currentScreen: React.PropTypes.shape({ - screen: React.PropTypes.oneOf(objectValues(enums.SCREEN)).isRequired, - props: React.PropTypes.object.isRequired + currentScreen: PropTypes.shape({ + screen: PropTypes.oneOf(objectValues(enums.SCREEN)).isRequired, + props: PropTypes.object.isRequired, + itemPermission: PropTypes.object }).isRequired }; @@ -97,6 +94,8 @@ class OnboardingView extends React.Component { switch (screen) { case enums.SCREEN.ONBOARDING_CATALOG: return ; + case enums.SCREEN.VERSIONS_PAGE: + return ; case enums.SCREEN.LICENSE_AGREEMENTS: case enums.SCREEN.FEATURE_GROUPS: @@ -106,24 +105,24 @@ class OnboardingView extends React.Component { case enums.SCREEN.ACTIVITY_LOG: return ( - { - (()=>{ - switch(screen) { - case enums.SCREEN.LICENSE_MODEL_OVERVIEW: - return ; - case enums.SCREEN.LICENSE_AGREEMENTS: - return ; - case enums.SCREEN.FEATURE_GROUPS: - return ; - case enums.SCREEN.ENTITLEMENT_POOLS: - return ; - case enums.SCREEN.LICENSE_KEY_GROUPS: - return ; - case enums.SCREEN.ACTIVITY_LOG: - return ; - } - })() - } + { + (()=>{ + switch(screen) { + case enums.SCREEN.LICENSE_MODEL_OVERVIEW: + return ; + case enums.SCREEN.LICENSE_AGREEMENTS: + return ; + case enums.SCREEN.FEATURE_GROUPS: + return ; + case enums.SCREEN.ENTITLEMENT_POOLS: + return ; + case enums.SCREEN.LICENSE_KEY_GROUPS: + return ; + case enums.SCREEN.ACTIVITY_LOG: + return ; + } + })() + } ); @@ -146,46 +145,46 @@ class OnboardingView extends React.Component { case enums.SCREEN.SOFTWARE_PRODUCT_ACTIVITY_LOG: return ( - { - (()=>{ - switch(screen) { - case enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_DETAILS: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_PROCESSES: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_DEPLOYMENT: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_NETWORKS: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_DEPENDENCIES: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENTS: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_PROCESSES: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_STORAGE: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_NETWORK: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_GENERAL: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_COMPUTE: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_LOAD_BALANCING: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_IMAGES: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_MONITORING: - return ; - case enums.SCREEN.SOFTWARE_PRODUCT_ACTIVITY_LOG: - return ; - } - })() - } + { + (()=>{ + switch(screen) { + case enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_DETAILS: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_PROCESSES: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_DEPLOYMENT: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_NETWORKS: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_DEPENDENCIES: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENTS: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_PROCESSES: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_STORAGE: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_NETWORK: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_GENERAL: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_COMPUTE: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_LOAD_BALANCING: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_IMAGES: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_MONITORING: + return ; + case enums.SCREEN.SOFTWARE_PRODUCT_ACTIVITY_LOG: + return ; + } + })() + } ); } @@ -234,10 +233,10 @@ export default class OnboardingPunchOut { handleData(data) { let {breadcrumbs: {selectedKeys = []} = {}} = data; let dispatch = action => store.dispatch(action); - let {currentScreen, softwareProductList, softwareProduct: {softwareProductEditor: {data: vspData = {}}, - softwareProductComponents = {}, softwareProductQuestionnaire = {}}, - licenseModelList, licenseModel: {licenseModelEditor: {data: {id: currentLicenseModelId, version: currentLicenseModelVersion} = {}}}} = store.getState(); - let {id: currentSoftwareProductId, version: currentSoftwareProductVersion} = vspData; + let {currentScreen, users: {usersList}, softwareProductList, licenseModelList, softwareProduct: {softwareProductEditor: {data: vspData = {}}, + softwareProductComponents = {}, softwareProductQuestionnaire = {}}} = store.getState(); + + let {props: {version, isReadOnlyMode}, screen} = currentScreen; let {componentEditor: {data: componentData = {}, qdata: componentQData = {}}} = softwareProductComponents; if (this.programmaticBreadcrumbsUpdate) { this.prevSelectedKeys = selectedKeys; @@ -249,11 +248,11 @@ export default class OnboardingPunchOut { const [, screenType, prevVspId, , prevComponentId] = this.prevSelectedKeys || []; let preNavigate = Promise.resolve(); - if(screenType === enums.BREADCRUMS.SOFTWARE_PRODUCT && vspData.status === VCItemStatus.CHECK_OUT_STATUS && VersionControllerUtils.isCheckedOutByCurrentUser(vspData)) { + if(screenType === enums.BREADCRUMS.SOFTWARE_PRODUCT && screen !== 'VERSIONS_PAGE' && !isReadOnlyMode) { let dataToSave = prevVspId ? prevComponentId ? {componentData, qdata: componentQData} : {softwareProduct: vspData, qdata: softwareProductQuestionnaire.qdata} : {}; preNavigate = OnboardingActionHelper.autoSaveBeforeNavigate(dispatch, { softwareProductId: prevVspId, - version: currentSoftwareProductVersion, + version, vspComponentId: prevComponentId, dataToSave }); @@ -261,40 +260,19 @@ export default class OnboardingPunchOut { let {currentScreen: {props: {softwareProductId}}, softwareProduct: {softwareProductAttachments: {heatSetup, heatSetupCache}}} = store.getState(); let heatSetupPopupPromise = currentScreen.screen === enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS ? - HeatSetupActionHelper.heatSetupLeaveConfirmation(dispatch, {softwareProductId, heatSetup, heatSetupCache}) : - Promise.resolve(); + HeatSetupActionHelper.heatSetupLeaveConfirmation(dispatch, {softwareProductId, heatSetup, heatSetupCache}) : + Promise.resolve(); Promise.all([preNavigate, heatSetupPopupPromise]).then(() => { this.prevSelectedKeys = selectedKeys; if (selectedKeys.length === 0) { - OnboardingActionHelper.navigateToOnboardingCatalog(dispatch); + ScreensHelper.loadScreen(dispatch, {screen: enums.SCREEN.ONBOARDING_CATALOG}); + } else if (selectedKeys.length === 1 || selectedKeys[1] === enums.BREADCRUMS.LICENSE_MODEL) { let [licenseModelId, , licenseModelScreen] = selectedKeys; - if (!licenseModelScreen) { - licenseModelScreen = enums.BREADCRUMS.LICENSE_MODEL_OVERVIEW; - } - if (currentLicenseModelId !== licenseModelId) { - currentLicenseModelVersion = licenseModelList.find(lm => lm.id === licenseModelId).version; - } - switch (licenseModelScreen) { - case enums.BREADCRUMS.LICENSE_MODEL_OVERVIEW: - OnboardingActionHelper.navigateToLicenseModelOverview(dispatch, {licenseModelId, version: currentLicenseModelVersion}); - break; - case enums.BREADCRUMS.LICENSE_AGREEMENTS: - OnboardingActionHelper.navigateToLicenseAgreements(dispatch, {licenseModelId, version: currentLicenseModelVersion}); - break; - case enums.BREADCRUMS.FEATURE_GROUPS: - OnboardingActionHelper.navigateToFeatureGroups(dispatch, {licenseModelId, version: currentLicenseModelVersion}); - break; - case enums.BREADCRUMS.ENTITLEMENT_POOLS: - OnboardingActionHelper.navigateToEntitlementPools(dispatch, {licenseModelId, version: currentLicenseModelVersion}); - break; - case enums.BREADCRUMS.LICENSE_KEY_GROUPS: - OnboardingActionHelper.navigateToLicenseKeyGroups(dispatch, {licenseModelId, version: currentLicenseModelVersion}); - break; - case enums.BREADCRUMS.ACTIVITY_LOG: - OnboardingActionHelper.navigateToLicenseModelActivityLog(dispatch, {licenseModelId, version: currentLicenseModelVersion}); - break; - } + let licenseModel = licenseModelList.find(vlm => vlm.id === licenseModelId); + ScreensHelper.loadScreen(dispatch, {screen: licenseModelScreen, screenType: screenTypes.LICENSE_MODEL, + props: {licenseModelId, version, licenseModel, usersList}}); + } else if (selectedKeys.length <= 4 && selectedKeys[1] === enums.BREADCRUMS.SOFTWARE_PRODUCT) { let [licenseModelId, , softwareProductId, softwareProductScreen] = selectedKeys; let softwareProduct = softwareProductId ? @@ -303,52 +281,20 @@ export default class OnboardingPunchOut { if (!softwareProductId) { softwareProductId = softwareProduct.id; } - if (currentSoftwareProductId !== softwareProductId) { - currentSoftwareProductVersion = softwareProduct.version; - } - switch (softwareProductScreen) { - case enums.BREADCRUMS.SOFTWARE_PRODUCT_LANDING_PAGE: - OnboardingActionHelper.navigateToSoftwareProductLandingPage(dispatch, {softwareProductId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_DETAILS: - OnboardingActionHelper.navigateToSoftwareProductDetails(dispatch, {softwareProductId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_ATTACHMENTS: - if(softwareProduct.onboardingOrigin === onboardingOriginTypes.ZIP) { - OnboardingActionHelper.navigateToSoftwareProductAttachmentsSetupTab(dispatch, {softwareProductId, version: currentSoftwareProductVersion}); - } - else if(softwareProduct.onboardingOrigin === onboardingOriginTypes.CSAR) { - OnboardingActionHelper.navigateToSoftwareProductAttachmentsValidationTab(dispatch, {softwareProductId, version: currentSoftwareProductVersion}); - } - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_PROCESSES: - OnboardingActionHelper.navigateToSoftwareProductProcesses(dispatch, {softwareProductId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_DEPLOYMENT: - OnboardingActionHelper.navigateToSoftwareProductDeployment(dispatch, {softwareProductId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_NETWORKS: - OnboardingActionHelper.navigateToSoftwareProductNetworks(dispatch, {softwareProductId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_DEPENDENCIES: - OnboardingActionHelper.navigateToSoftwareProductDependencies(dispatch, {softwareProductId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_ACTIVITY_LOG: - OnboardingActionHelper.navigateToSoftwareProductActivityLog(dispatch, {softwareProductId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENTS: - OnboardingActionHelper.navigateToSoftwareProductComponents(dispatch, {softwareProductId, version: currentSoftwareProductVersion}); - dispatch({ - type: SoftwareProductActionTypes.TOGGLE_NAVIGATION_ITEM, - mapOfExpandedIds: { - [SoftwareProductNavigationItems.COMPONENTS]: true - } - }); - break; - default: - OnboardingActionHelper.navigateToSoftwareProductLandingPage(dispatch, {softwareProductId, version: currentSoftwareProductVersion}); - break; + if (softwareProductScreen === enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS) { + softwareProduct = vspData; + //check current vsp fields to determine which file has uploaded + if(vspData.onboardingOrigin === onboardingOriginTypes.ZIP || vspData.candidateOnboardingOrigin === onboardingOriginTypes.ZIP) { + softwareProductScreen = enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS_SETUP; + } + else if(vspData.onboardingOrigin === onboardingOriginTypes.CSAR) { + softwareProductScreen = enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS_VALIDATION; + } } + + ScreensHelper.loadScreen(dispatch, {screen: softwareProductScreen, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, softwareProduct, version, usersList}}); + } else if (selectedKeys.length === 5 && selectedKeys[1] === enums.BREADCRUMS.SOFTWARE_PRODUCT && selectedKeys[3] === enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENTS) { let [licenseModelId, , softwareProductId, , componentId] = selectedKeys; let softwareProduct = softwareProductId ? @@ -357,10 +303,9 @@ export default class OnboardingPunchOut { if (!softwareProductId) { softwareProductId = softwareProduct.id; } - if (currentSoftwareProductId !== softwareProductId) { - currentSoftwareProductVersion = softwareProduct.version; - } - OnboardingActionHelper.navigateToSoftwareProductComponentGeneralAndUpdateLeftPanel(dispatch, {softwareProductId, componentId, version: currentSoftwareProductVersion}); + ScreensHelper.loadScreen(dispatch, {screen: enums.SCREEN.SOFTWARE_PRODUCT_COMPONENTS, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, softwareProduct, componentId, version, usersList}}); + } else if (selectedKeys.length === 6 && selectedKeys[1] === enums.BREADCRUMS.SOFTWARE_PRODUCT && selectedKeys[3] === enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENTS) { let [licenseModelId, , softwareProductId, , componentId, componentScreen] = selectedKeys; let softwareProduct = softwareProductId ? @@ -369,39 +314,9 @@ export default class OnboardingPunchOut { if (!softwareProductId) { softwareProductId = softwareProduct.id; } - if (currentSoftwareProductId !== softwareProductId) { - currentSoftwareProductVersion = softwareProduct.version; - } - switch (componentScreen) { - case enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENT_GENERAL: - OnboardingActionHelper.navigateToSoftwareProductComponentGeneral(dispatch, {softwareProductId, componentId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENT_COMPUTE: - OnboardingActionHelper.navigateToComponentCompute(dispatch, {softwareProductId, componentId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENT_LOAD_BALANCING: - OnboardingActionHelper.navigateToComponentLoadBalancing(dispatch, {softwareProductId, componentId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENT_NETWORK: - OnboardingActionHelper.navigateToComponentNetwork(dispatch, {softwareProductId, componentId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENT_STORAGE: - OnboardingActionHelper.navigateToComponentStorage(dispatch, {softwareProductId, componentId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENT_PROCESSES: - OnboardingActionHelper.navigateToSoftwareProductComponentProcesses(dispatch, {softwareProductId, componentId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENT_MONITORING: - OnboardingActionHelper.navigateToSoftwareProductComponentMonitoring(dispatch, {softwareProductId, componentId, version: currentSoftwareProductVersion}); - break; - case enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENT_IMAGES: - OnboardingActionHelper.navigateToComponentImages(dispatch, { - softwareProductId, - componentId, - version: currentSoftwareProductVersion - }); - break; - } + ScreensHelper.loadScreen(dispatch, {screen: componentScreen, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, softwareProduct, componentId, version, usersList}}); + } else { console.error('Unknown breadcrumbs path: ', selectedKeys); } @@ -418,11 +333,14 @@ export default class OnboardingPunchOut { } handleStoreChange() { - let {currentScreen, licenseModelList, softwareProductList, - softwareProduct: {softwareProductEditor: {data = {onboardingMethod: ''}}, + let {currentScreen, licenseModelList, finalizedLicenseModelList, softwareProductList, finalizedSoftwareProductList, versionsPage: + {versionsList: {itemType, itemId}}, + softwareProduct: {softwareProductEditor: {data: currentSoftwareProduct = {onboardingMethod: ''}}, softwareProductComponents: {componentsList}}} = store.getState(); - let {onboardingMethod, onboardingOrigin} = data; - let breadcrumbsData = {onboardingMethod, currentScreen, licenseModelList, softwareProductList, componentsList, onboardingOrigin}; + const wholeSoftwareProductList = [...softwareProductList, ...finalizedSoftwareProductList]; + const wholeLicenseModelList = [...licenseModelList, ...finalizedLicenseModelList]; + let breadcrumbsData = {itemType, itemId, currentScreen, wholeLicenseModelList, wholeSoftwareProductList, currentSoftwareProduct, componentsList}; + if (currentScreen.forceBreadCrumbsUpdate || !isEqual(breadcrumbsData, this.prevBreadcrumbsData) || this.breadcrumbsPrefixSelected) { this.prevBreadcrumbsData = breadcrumbsData; this.breadcrumbsPrefixSelected = false; @@ -439,12 +357,58 @@ export default class OnboardingPunchOut { } } - buildBreadcrumbs({currentScreen: {screen, props}, onboardingMethod, licenseModelList, softwareProductList, componentsList, onboardingOrigin}) { + buildBreadcrumbs({currentScreen: {screen, props}, itemType, itemId, currentSoftwareProduct, + wholeLicenseModelList, wholeSoftwareProductList, componentsList}) { + let {onboardingMethod, onboardingOrigin, candidateOnboardingOrigin} = currentSoftwareProduct; let screenToBreadcrumb; switch (screen) { case enums.SCREEN.ONBOARDING_CATALOG: return []; + case enums.SCREEN.VERSIONS_PAGE: + let firstMenuItems = itemType === itemTypes.LICENSE_MODEL ? [ + { + selectedKey: itemId, + menuItems: wholeLicenseModelList.map(({id, name}) => ({ + key: id, + displayText: name + })) + }] : [ + { + selectedKey: props.additionalProps.licenseModelId || currentSoftwareProduct.vendorId, + menuItems: wholeLicenseModelList.map(({id, name}) => ({ + key: id, + displayText: name + })) + }, + { + selectedKey: enums.BREADCRUMS.SOFTWARE_PRODUCT, + menuItems: [{ + key: enums.BREADCRUMS.LICENSE_MODEL, + displayText: i18n('License Model') + }, { + key: enums.BREADCRUMS.SOFTWARE_PRODUCT, + displayText: i18n('Software Products') + }] + }, + { + selectedKey: itemId, + menuItems: wholeSoftwareProductList + .filter(({id, vendorId}) => vendorId === currentSoftwareProduct.vendorId || id === itemId) + .map(({id, name}) => ({ + key: id, + displayText: name + })) + }, + ]; + return [ + ...firstMenuItems, + { + selectedKey: enums.BREADCRUMS.VERSIONS_PAGE, + menuItems: [{key: enums.BREADCRUMS.VERSIONS_PAGE, displayText: i18n('Versions Page')}] + } + ]; + case enums.SCREEN.LICENSE_AGREEMENTS: case enums.SCREEN.FEATURE_GROUPS: case enums.SCREEN.ENTITLEMENT_POOLS: @@ -462,9 +426,9 @@ export default class OnboardingPunchOut { return [ { selectedKey: props.licenseModelId, - menuItems: licenseModelList.map(({id, vendorName}) => ({ + menuItems: wholeLicenseModelList.map(({id, name}) => ({ key: id, - displayText: vendorName + displayText: name })) }, { @@ -473,10 +437,10 @@ export default class OnboardingPunchOut { key: enums.BREADCRUMS.LICENSE_MODEL, displayText: i18n('License Model') }, - ...(softwareProductList.findIndex(({vendorId}) => vendorId === props.licenseModelId) === -1 ? [] : [{ - key: enums.BREADCRUMS.SOFTWARE_PRODUCT, - displayText: i18n('Software Products') - }])] + ...(wholeSoftwareProductList.findIndex(({vendorId}) => vendorId === props.licenseModelId) === -1 ? [] : [{ + key: enums.BREADCRUMS.SOFTWARE_PRODUCT, + displayText: i18n('Software Products') + }])] }, { selectedKey: screenToBreadcrumb[screen], menuItems: [{ @@ -540,13 +504,13 @@ export default class OnboardingPunchOut { [enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_IMAGES]: enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENT_IMAGES, [enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_MONITORING]: enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENT_MONITORING }; - let licenseModelId = softwareProductList.find(({id}) => id === props.softwareProductId).vendorId; + let licenseModelId = currentSoftwareProduct.vendorId; let returnedBreadcrumb = [ { selectedKey: licenseModelId, - menuItems: licenseModelList.map(({id, vendorName}) => ({ + menuItems: wholeLicenseModelList.map(({id, name}) => ({ key: id, - displayText: vendorName + displayText: name })) }, { @@ -561,8 +525,8 @@ export default class OnboardingPunchOut { }, { selectedKey: props.softwareProductId, - menuItems: softwareProductList - .filter(({vendorId}) => vendorId === licenseModelId) + menuItems: wholeSoftwareProductList + .filter(({vendorId, id}) => vendorId === licenseModelId || id === props.softwareProductId) .map(({id, name}) => ({ key: id, displayText: name @@ -598,14 +562,14 @@ export default class OnboardingPunchOut { key: enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENTS, displayText: i18n('Components') }].filter(item => { - let isHeatData = onboardingOrigin !== onboardingOriginTypes.NONE; - let isManualMode = onboardingMethod === onboardingMethodTypes.MANUAL; switch (item.key) { case enums.BREADCRUMS.SOFTWARE_PRODUCT_ATTACHMENTS: + let isHeatData = onboardingOrigin !== onboardingOriginTypes.NONE || candidateOnboardingOrigin === onboardingOriginTypes.ZIP; return isHeatData; case enums.BREADCRUMS.SOFTWARE_PRODUCT_COMPONENTS: return (componentsList.length > 0); case enums.BREADCRUMS.SOFTWARE_PRODUCT_DEPLOYMENT: + let isManualMode = onboardingMethod === onboardingMethodTypes.MANUAL; return isManualMode; case enums.BREADCRUMS.SOFTWARE_PRODUCT_DEPENDENCIES: return (componentsList.length > 1); diff --git a/openecomp-ui/src/sdc-app/onboarding/OnboardingReducers.js b/openecomp-ui/src/sdc-app/onboarding/OnboardingReducers.js index e63bcb16af..2eb455f9dd 100644 --- a/openecomp-ui/src/sdc-app/onboarding/OnboardingReducers.js +++ b/openecomp-ui/src/sdc-app/onboarding/OnboardingReducers.js @@ -14,21 +14,127 @@ * permissions and limitations under the License. */ import {actionTypes, enums} from './OnboardingConstants.js'; +import {actionTypes as permissionActionTypes} from './permissions/PermissionsConstants.js'; +import {actionTypes as licenseModelCreateActionTypes} from './licenseModel/creation/LicenseModelCreationConstants.js'; +import {actionTypes as softwareProductCreateActionTypes} from './softwareProduct/creation/SoftwareProductCreationConstants.js'; +import {actionTypes as versionCreateActionTypes} from './versionsPage/creation/VersionsPageCreationConstants.js'; +import {SyncStates} from 'sdc-app/common/merge/MergeEditorConstants.js'; + +import {catalogItemStatuses} from './onboard/onboardingCatalog/OnboardingCatalogConstants.js'; +import Configuration from 'sdc-app/config/Configuration.js'; + +const checkReadOnly = ({isCollaborator = true, inMerge = false, isCertified = false}) => !isCollaborator || inMerge || isCertified; + +const currentScreen = (state = { + forceBreadCrumbsUpdate: false, + screen: enums.SCREEN.ONBOARDING_CATALOG, + itemPermission: {}, + props: {} +}, action) => { -export const currentScreenReducer = (state = {forceBreadCrumbsUpdate: false, screen: enums.SCREEN.ONBOARDING_CATALOG, props: {}}, action) => { switch (action.type) { - case actionTypes.SET_CURRENT_SCREEN: - return action.currentScreen; + + case actionTypes.SET_CURRENT_SCREEN: { + let itemPermission = {...state.itemPermission}; + let {currentScreen} = action; + + if (currentScreen.props.version) { + let {status} = currentScreen.props.version; + itemPermission.isCertified = itemPermission.isCertified && status === catalogItemStatuses.CERTIFIED; + } + + let isReadOnlyMode = checkReadOnly(itemPermission); + let props = {...currentScreen.props, isReadOnlyMode}; + + return { + ...state, + ...currentScreen, + itemPermission, + props + }; + } + + case actionTypes.UPDATE_CURRENT_SCREEN_PROPS: + return { + ...state, + props: { + ...state.props, + ...action.props, + isReadOnlyMode: checkReadOnly(state.itemPermission) + } + }; + case actionTypes.SET_CURRENT_SCREEN_VERSION: return { ...state, props: { ...state.props, - version: action.version + version: action.version, + isReadOnlyMode: checkReadOnly(state.itemPermission) } - }; + }; + + case licenseModelCreateActionTypes.LICENSE_MODEL_CREATED: + case softwareProductCreateActionTypes.SOFTWARE_PRODUCT_CREATED: + case versionCreateActionTypes.VERSION_CREATED: + return { + ...state, + itemPermission: { + isCollaborator: true, + inMerge: false, + isCertified: false + }, + props: { + ...state.props, + isReadOnlyMode: false + } + }; + + case permissionActionTypes.ITEM_USERS_LOADED: { + let userId = Configuration.get('UserID'); + let isCollaborator = false; + + if (userId === action.owner.userId) { + isCollaborator = true; + } else { + isCollaborator = action.contributors.reduce( + (foundUser, contributor) => foundUser || contributor.userId === userId, false + ); + } + + let itemPermission = {...state.itemPermission, isCollaborator}; + let isReadOnlyMode = checkReadOnly(itemPermission); + let props = {...state.props, isReadOnlyMode}; + + return { + ...state, + itemPermission, + props + }; + } + + case actionTypes.UPDATE_ITEM_STATUS: { + const {itemState: {synchronizationState, dirty}, itemStatus, updatedVersion} = action; + const inMerge = synchronizationState === SyncStates.MERGE; + const isOutOfSync = synchronizationState === SyncStates.OUT_OF_SYNC; + const isUpToDate = synchronizationState === SyncStates.UP_TO_DATE; + const isCertified = itemStatus === catalogItemStatuses.CERTIFIED; + const itemPermission = {...state.itemPermission, inMerge, isDirty: dirty, isOutOfSync, isUpToDate, isCertified}; + const isReadOnlyMode = checkReadOnly(itemPermission); + const props = {...state.props, isReadOnlyMode, version: {...state.props.version, ...updatedVersion}}; + + return { + ...state, + itemPermission, + props + }; + } + default: return state; - } + + } + }; +export default currentScreen; diff --git a/openecomp-ui/src/sdc-app/onboarding/OnboardingReducersMap.js b/openecomp-ui/src/sdc-app/onboarding/OnboardingReducersMap.js index 9428dd5829..f69bc0da5e 100644 --- a/openecomp-ui/src/sdc-app/onboarding/OnboardingReducersMap.js +++ b/openecomp-ui/src/sdc-app/onboarding/OnboardingReducersMap.js @@ -13,7 +13,7 @@ * or implied. See the License for the specific language governing * permissions and limitations under the License. */ -import {currentScreenReducer} from './OnboardingReducers.js'; +import currentScreenReducer from './OnboardingReducers.js'; import licenseModelListReducer from './licenseModel/LicenseModelListReducer.js'; import finalizedLicenseModelListReducer from './licenseModel/FinalizedLicenseModelListReducer.js'; import licenseModelReducer from './licenseModel/LicenseModelReducer.js'; @@ -21,14 +21,22 @@ import softwareProductReducer from './softwareProduct/SoftwareProductReducer.js' import softwareProductListReducer from './softwareProduct/SoftwareProductListReducer.js'; import finalizedSoftwareProductReducer from './softwareProduct/FinalizedSoftwareProductReducer.js'; import onboardReducer from './onboard/OnboardReducer.js'; +import versionsPageReducer from './versionsPage/VersionsPageReducer.js'; +import usersReducer from './users/UsersReducers.js'; +import mergeEditorReducer from 'sdc-app/common/merge/MergeEditorReducer.js'; +import revisionsReducer from './revisions/RevisionsReducer.js'; export default { currentScreen: currentScreenReducer, + licenseModel: licenseModelReducer, licenseModelList: licenseModelListReducer, finalizedLicenseModelList: finalizedLicenseModelListReducer, finalizedSoftwareProductList: finalizedSoftwareProductReducer, - licenseModel: licenseModelReducer, + mergeEditor: mergeEditorReducer, + onboard: onboardReducer, softwareProduct: softwareProductReducer, softwareProductList: softwareProductListReducer, - onboard: onboardReducer + users: usersReducer, + versionsPage: versionsPageReducer, + revisions: revisionsReducer }; diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModel.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModel.js index 895a329047..73027c7e36 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModel.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModel.js @@ -16,18 +16,17 @@ import {connect} from 'react-redux'; import i18n from 'nfvo-utils/i18n/i18n.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import TabulatedEditor from 'src/nfvo-components/editor/TabulatedEditor.jsx'; -import ActivityLogActionHelper from 'sdc-app/common/activity-log/ActivityLogActionHelper.js'; -import {enums} from 'sdc-app/onboarding/OnboardingConstants.js'; -import OnboardingActionHelper from 'sdc-app/onboarding/OnboardingActionHelper.js'; +import ScreensHelper from 'sdc-app/common/helpers/ScreensHelper.js'; +import {enums, screenTypes} from 'sdc-app/onboarding/OnboardingConstants.js'; + +import PermissionsActionHelper from './../permissions/PermissionsActionHelper.js'; +import RevisionsActionHelper from './../revisions/RevisionsActionHelper.js'; -import {navigationItems} from './LicenseModelConstants.js'; import LicenseModelActionHelper from './LicenseModelActionHelper.js'; -import LicenseAgreementActionHelper from './licenseAgreement/LicenseAgreementActionHelper.js'; -import FeatureGroupsActionHelper from './featureGroups/FeatureGroupsActionHelper.js'; -import EntitlementPoolsActionHelper from './entitlementPools/EntitlementPoolsActionHelper.js'; -import LicenseKeyGroupsActionHelper from './licenseKeyGroups/LicenseKeyGroupsActionHelper.js'; +import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; +import {modalContentMapper} from 'sdc-app/common/modal/ModalContentMapper.js'; +import {CommitModalType} from 'nfvo-components/panel/versionController/components/CommitCommentModal.jsx'; const buildNavigationBarProps = (licenseModel, screen) => { @@ -39,131 +38,135 @@ const buildNavigationBarProps = (licenseModel, screen) => { name: vendorName, items: [ { - id: navigationItems.LICENSE_MODEL_OVERVIEW, + id: enums.SCREEN.LICENSE_MODEL_OVERVIEW, name: i18n('Overview'), meta }, { - id: navigationItems.LICENSE_AGREEMENTS, + id: enums.SCREEN.LICENSE_AGREEMENTS, name: i18n('License Agreements'), meta }, { - id: navigationItems.FEATURE_GROUPS, + id: enums.SCREEN.FEATURE_GROUPS, name: i18n('Feature Groups'), meta }, { - id: navigationItems.ENTITLEMENT_POOLS, + id: enums.SCREEN.ENTITLEMENT_POOLS, name: i18n('Entitlement Pools'), meta }, { - id: navigationItems.LICENSE_KEY_GROUPS, + id: enums.SCREEN.LICENSE_KEY_GROUPS, name: i18n('License Key Groups'), meta }, { - id: navigationItems.ACTIVITY_LOG, + id: enums.SCREEN.ACTIVITY_LOG, name: i18n('Activity Log'), meta } ] }]; - const activeItemId = ({ - [enums.SCREEN.LICENSE_MODEL_OVERVIEW]: navigationItems.LICENSE_MODEL_OVERVIEW, - [enums.SCREEN.LICENSE_AGREEMENTS]: navigationItems.LICENSE_AGREEMENTS, - [enums.SCREEN.FEATURE_GROUPS]: navigationItems.FEATURE_GROUPS, - [enums.SCREEN.ENTITLEMENT_POOLS]: navigationItems.ENTITLEMENT_POOLS, - [enums.SCREEN.LICENSE_KEY_GROUPS]: navigationItems.LICENSE_KEY_GROUPS, - [enums.SCREEN.ACTIVITY_LOG]: navigationItems.ACTIVITY_LOG - })[screen]; - return { - activeItemId, groups + activeItemId: screen, groups }; }; -const buildVersionControllerProps = (licenseModel) => { - let {version, viewableVersions, status: currentStatus, lockingUser} = licenseModel; - let {status, isCheckedOut} = VersionControllerUtils.getCheckOutStatusKindByUserID(currentStatus, lockingUser); - +const buildVersionControllerProps = ({ + licenseModelEditor = {data: {}}, + versions, + currentVersion, + userInfo, + usersList, + permissions, + itemPermission, + isReadOnlyMode +}) => { + const {isValidityData = true} = licenseModelEditor; return { - version, - viewableVersions, - status, - isCheckedOut + version: currentVersion, + viewableVersions: versions, + isFormDataValid: isValidityData, + permissions, + userInfo, + usersList, + itemName: licenseModelEditor.data.vendorName, + itemPermission, + isReadOnlyMode }; }; -const mapStateToProps = ({licenseModel: {licenseModelEditor}}, {currentScreen: {screen}}) => { +const mapStateToProps = ({ + users: {userInfo, usersList}, + licenseModel: {licenseModelEditor}, + versionsPage: {permissions, versionsList: {versions, itemName}} +}, { + currentScreen: {screen, itemPermission, props: {isReadOnlyMode, version: currentVersion}} +}) => { return { - versionControllerProps: buildVersionControllerProps(licenseModelEditor.data), + versionControllerProps: buildVersionControllerProps({ + licenseModelEditor, + versions, + currentVersion, + userInfo, + permissions, + usersList, + itemPermission, + isReadOnlyMode + }), navigationBarProps: buildNavigationBarProps(licenseModelEditor.data, screen) }; }; -const mapActionsToProps = (dispatch, {currentScreen: {screen, props: {licenseModelId}}}) => { +const mapActionsToProps = (dispatch, {currentScreen: {screen, props: {licenseModelId, version}}}) => { return { - onVersionControllerAction: (action, version) => - LicenseModelActionHelper.performVCAction(dispatch, {licenseModelId, action, version}).then((newVersion) => { - switch(screen) { - case enums.SCREEN.LICENSE_MODEL_OVERVIEW: - /** - * TODO change to specific rest - */ - LicenseAgreementActionHelper.fetchLicenseAgreementList(dispatch, {licenseModelId, version: newVersion}); - break; - case enums.SCREEN.LICENSE_AGREEMENTS: - LicenseAgreementActionHelper.fetchLicenseAgreementList(dispatch, {licenseModelId, version: newVersion}); - break; - case enums.SCREEN.FEATURE_GROUPS: - FeatureGroupsActionHelper.fetchFeatureGroupsList(dispatch, {licenseModelId, version: newVersion}); - break; - case enums.SCREEN.ENTITLEMENT_POOLS: - EntitlementPoolsActionHelper.fetchEntitlementPoolsList(dispatch, {licenseModelId, version: newVersion}); - break; - case enums.SCREEN.LICENSE_KEY_GROUPS: - LicenseKeyGroupsActionHelper.fetchLicenseKeyGroupsList(dispatch, {licenseModelId, version: newVersion}); - break; - case enums.SCREEN.ACTIVITY_LOG: - ActivityLogActionHelper.fetchActivityLog(dispatch, {itemId: licenseModelId, versionId: newVersion.id}); - break; - } + onVersionControllerAction: (action, version, comment) => + LicenseModelActionHelper.performVCAction(dispatch, {licenseModelId, action, version, comment}).then(updatedVersion => { + ScreensHelper.loadScreen(dispatch, {screen, screenType: screenTypes.LICENSE_MODEL, props: {licenseModelId, version: updatedVersion}}); }), - onVersionSwitching: version => { - LicenseModelActionHelper.switchVersion(dispatch, {licenseModelId, version}); - if(screen === enums.SCREEN.ACTIVITY_LOG) { - ActivityLogActionHelper.fetchActivityLog(dispatch, {itemId: licenseModelId, versionId: version.id}); + + onOpenCommentCommitModal: ({onCommit, title}) => dispatch({ + type: modalActionTypes.GLOBAL_MODAL_SHOW, + data: { + modalComponentName: modalContentMapper.COMMIT_COMMENT, + modalComponentProps: { + onCommit, + type: CommitModalType.COMMIT + }, + title } + }), + + onVersionSwitching: version => { + ScreensHelper.loadScreen(dispatch, {screen, screenType: screenTypes.LICENSE_MODEL, props: {licenseModelId, version}}); }, - onNavigate: ({id, meta: {version}}) => { - switch(id) { - case navigationItems.LICENSE_MODEL_OVERVIEW: - OnboardingActionHelper.navigateToLicenseModelOverview(dispatch, {licenseModelId, version}); - break; - case navigationItems.LICENSE_AGREEMENTS: - OnboardingActionHelper.navigateToLicenseAgreements(dispatch, {licenseModelId, version}); - break; - case navigationItems.FEATURE_GROUPS: - OnboardingActionHelper.navigateToFeatureGroups(dispatch, {licenseModelId, version}); - break; - case navigationItems.ENTITLEMENT_POOLS: - OnboardingActionHelper.navigateToEntitlementPools(dispatch, {licenseModelId, version}); - break; - case navigationItems.LICENSE_KEY_GROUPS: - OnboardingActionHelper.navigateToLicenseKeyGroups(dispatch, {licenseModelId, version}); - break; - case navigationItems.ACTIVITY_LOG: - OnboardingActionHelper.navigateToLicenseModelActivityLog(dispatch, {licenseModelId, version}); - break; - } + onManagePermissions() { + PermissionsActionHelper.openPermissonsManager(dispatch, {itemId: licenseModelId, askForRights: false}); + }, + + onMoreVersionsClick: ({itemName, users}) => { + ScreensHelper.loadScreen(dispatch, {screen: enums.SCREEN.VERSIONS_PAGE, screenType: screenTypes.LICENSE_MODEL, + props: {licenseModelId, licenseModel: {name: itemName}, usersList: users}}); + }, + + onOpenPermissions: ({users}) => { + return PermissionsActionHelper.fetchItemUsers(dispatch, {itemId: licenseModelId, allUsers: users}); + }, + + onOpenRevisionsModal: () => { + return RevisionsActionHelper.openRevisionsView(dispatch, {itemId: licenseModelId, version: version, itemType: screenTypes.LICENSE_MODEL}); + }, + + onNavigate: ({id}) => { + ScreensHelper.loadScreen(dispatch, {screen: id, screenType: screenTypes.LICENSE_MODEL, props: {licenseModelId, version}}); } }; }; diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModelActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModelActionHelper.js index 788528fd75..ff264b3003 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModelActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModelActionHelper.js @@ -23,7 +23,14 @@ import LicenseAgreementActionHelper from './licenseAgreement/LicenseAgreementAct import FeatureGroupsActionHelper from './featureGroups/FeatureGroupsActionHelper.js'; import EntitlementPoolsActionHelper from './entitlementPools/EntitlementPoolsActionHelper.js'; import LicenseKeyGroupsActionHelper from './licenseKeyGroups/LicenseKeyGroupsActionHelper.js'; -import OnboardingActionHelper from 'sdc-app/onboarding/OnboardingActionHelper.js'; +import ItemsHelper from '../../common/helpers/ItemsHelper.js'; +import MergeEditorActionHelper from 'sdc-app/common/merge/MergeEditorActionHelper.js'; +import {modalContentMapper} from 'sdc-app/common/modal/ModalContentMapper.js'; +import {CommitModalType} from 'nfvo-components/panel/versionController/components/CommitCommentModal.jsx'; +import versionPageActionHelper from 'sdc-app/onboarding/versionsPage/VersionsPageActionHelper.js'; +import {itemTypes} from 'sdc-app/onboarding/versionsPage/VersionsPageConstants.js'; +import {catalogItemStatuses} from 'sdc-app/onboarding/onboard/onboardingCatalog/OnboardingCatalogConstants.js'; +import {actionsEnum as VersionControllerActionsEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; function baseUrl() { const restPrefix = Configuration.get('restPrefix'); @@ -31,11 +38,11 @@ function baseUrl() { } function fetchLicenseModels() { - return RestAPIUtil.fetch(baseUrl()); + return RestAPIUtil.fetch(`${baseUrl()}?versionFilter=Draft`); } function fetchFinalizedLicenseModels() { - return RestAPIUtil.fetch(`${baseUrl()}?versionFilter=Final`); + return RestAPIUtil.fetch(`${baseUrl()}?versionFilter=Certified`); } function fetchLicenseModelById(licenseModelId, version) { @@ -43,11 +50,6 @@ function fetchLicenseModelById(licenseModelId, version) { return RestAPIUtil.fetch(`${baseUrl()}${licenseModelId}/versions/${versionId}`); } -function putLicenseModelAction(id, action, version) { - const {id: versionId} = version; - return RestAPIUtil.put(`${baseUrl()}${id}/versions/${versionId}/actions`, {action: action}); -} - function putLicenseModel(licenseModel) { let {id, vendorName, description, iconRef, version: {id: versionId}} = licenseModel; return RestAPIUtil.put(`${baseUrl()}${id}/versions/${versionId}`, { @@ -57,14 +59,9 @@ function putLicenseModel(licenseModel) { }); } -function adjustMinorVersion(version, value) { - let ar = version.split('.'); - return ar[0] + '.' + (parseInt(ar[1]) + value); -} - -function adjustMajorVersion(version, value) { - let ar = version.split('.'); - return (parseInt(ar[0]) + value) + '.0'; +function putLicenseModelAction({itemId, action, version}) { + const {id: versionId} = version; + return RestAPIUtil.put(`${baseUrl()}${itemId}/versions/${versionId}/actions`, {action: action}); } const LicenseModelActionHelper = { @@ -87,8 +84,8 @@ const LicenseModelActionHelper = { }, fetchLicenseModelById(dispatch, {licenseModelId, version}) { - - return fetchLicenseModelById(licenseModelId, version).then(response => { + + return fetchLicenseModelById(licenseModelId, version).then(response => { dispatch({ type: actionTypes.LICENSE_MODEL_LOADED, response: {...response, version} @@ -96,13 +93,6 @@ const LicenseModelActionHelper = { }); }, - addLicenseModel(dispatch, {licenseModel}){ - dispatch({ - type: actionTypes.ADD_LICENSE_MODEL, - licenseModel - }); - }, - fetchLicenseModelItems(dispatch, {licenseModelId, version}) { return Promise.all([ LicenseAgreementActionHelper.fetchLicenseAgreementList(dispatch, {licenseModelId, version}), @@ -112,58 +102,94 @@ const LicenseModelActionHelper = { ]); }, - performVCAction(dispatch, {licenseModelId, action, version}) { - return putLicenseModelAction(licenseModelId, action, version).then(() => { - if(action === vcActionsEnum.SUBMIT){ + manageSubmitAction(dispatch, {licenseModelId, version, isDirty}) { + if(isDirty) { + const onCommit = comment => { + return this.performVCAction(dispatch, {licenseModelId, action: vcActionsEnum.COMMIT, version, comment}).then(() => { + return this.performSubmitAction(dispatch, {licenseModelId, version}); + }); + }; + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_SHOW, + data: { + modalComponentName: modalContentMapper.COMMIT_COMMENT, + modalComponentProps: { + onCommit, + type: CommitModalType.COMMIT_SUBMIT + }, + title: i18n('Commit & Submit') + } + }); + return Promise.reject(); + } + return this.performSubmitAction(dispatch, {licenseModelId, version}); + }, + + performSubmitAction(dispatch, {licenseModelId, version}) { + return putLicenseModelAction({itemId: licenseModelId, action: vcActionsEnum.SUBMIT, version}).then(() => { + return ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}).then(updatedVersion => { dispatch({ type: modalActionTypes.GLOBAL_MODAL_SUCCESS, data: { - title: i18n('Submit Succeeded'), + title: i18n('Submit Succeeded'), msg: i18n('This license model successfully submitted'), - cancelButtonText: i18n('OK'), + cancelButtonText: i18n('OK'), timeout: 2000 } }); - } - - let newVersionId = version.id; - /* - TODO Temorary switch to change version label - */ - switch(action) { - case vcActionsEnum.CHECK_OUT: - newVersionId = adjustMinorVersion(version.label, 1); - break; - case vcActionsEnum.UNDO_CHECK_OUT: - newVersionId = adjustMinorVersion(version.label, -1); - break; - case vcActionsEnum.SUBMIT: - newVersionId = adjustMajorVersion(version.label, 1); - } - - OnboardingActionHelper.updateCurrentScreenVersion(dispatch, {label: newVersionId, id: newVersionId}); - - LicenseModelActionHelper.fetchLicenseModelById(dispatch, {licenseModelId, version:{id: newVersionId, label: newVersionId}}); - return Promise.resolve({id: newVersionId, label: newVersionId}); + versionPageActionHelper.fetchVersions(dispatch, {itemType: itemTypes.LICENSE_MODEL, itemId: licenseModelId}); + return Promise.resolve(updatedVersion); + }); }); }, - switchVersion(dispatch, {licenseModelId, version}) { - LicenseModelActionHelper.fetchLicenseModelById(dispatch, {licenseModelId, version: {id: version.id, label: version.label}}).then(() => { - LicenseModelActionHelper.fetchLicenseModelItems(dispatch, {licenseModelId, version}); + performVCAction(dispatch, {licenseModelId, action, version, comment}) { + return MergeEditorActionHelper.analyzeSyncResult(dispatch, {itemId: licenseModelId, version}).then(({inMerge, isDirty, updatedVersion}) => { + if (updatedVersion.status === catalogItemStatuses.CERTIFIED && + (action === VersionControllerActionsEnum.COMMIT || action === VersionControllerActionsEnum.SYNC)) { + versionPageActionHelper.fetchVersions(dispatch, {itemType: itemTypes.LICENSE_MODEL, itemId: licenseModelId}); + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_WARNING, + data: { + title: i18n('Commit error'), + msg: i18n('Item version already Certified'), + cancelButtonText: i18n('Cancel') + } + }); + return Promise.resolve(updatedVersion); + } + if (!inMerge) { + if(action === vcActionsEnum.SUBMIT) { + return this.manageSubmitAction(dispatch, {licenseModelId, version, isDirty}); + } + else { + return ItemsHelper.performVCAction({itemId: licenseModelId, action, version, comment}).then(() => { + versionPageActionHelper.fetchVersions(dispatch, {itemType: itemTypes.LICENSE_MODEL, itemId: licenseModelId}); + if (action === vcActionsEnum.SYNC) { + return MergeEditorActionHelper.analyzeSyncResult(dispatch, {itemId: licenseModelId, version}).then(({updatedVersion}) => { + return Promise.resolve(updatedVersion); + }); + } else { + return ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); + } + }); + } + } }); }, saveLicenseModel(dispatch, {licenseModel}) { return putLicenseModel(licenseModel).then(() => { - dispatch({ - type: actionTypes.ADD_LICENSE_MODEL, - licenseModel - }); dispatch({ type: actionTypes.LICENSE_MODEL_LOADED, response: licenseModel }); + const {id, version: {id: versionId}} = licenseModel; + return ItemsHelper.checkItemStatus(dispatch, {itemId: id, versionId}).then(updatedVersion => { + if (updatedVersion.status !== licenseModel.version.status) { + versionPageActionHelper.fetchVersions(dispatch, {itemType: itemTypes.LICENSE_MODEL, itemId: licenseModel.id}); + } + }); }); } diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModelConstants.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModelConstants.js index 960090c2d8..283cb23168 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModelConstants.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModelConstants.js @@ -20,18 +20,9 @@ export const actionTypes = keyMirror({ LICENSE_MODEL_LOADED: null, LICENSE_MODELS_LIST_LOADED: null, FINALIZED_LICENSE_MODELS_LIST_LOADED: null, - ADD_LICENSE_MODEL: null, EDIT_LICENSE_MODEL: null }); -export const navigationItems = keyMirror({ - LICENSE_MODEL_OVERVIEW: 'overview', - LICENSE_AGREEMENTS: 'license-agreements', - FEATURE_GROUPS: 'feature-groups', - ENTITLEMENT_POOLS: 'entitlement-pools', - LICENSE_KEY_GROUPS: 'license-key-groups', - ACTIVITY_LOG: 'activity-log' -}); export const thresholdUnitType = { ABSOLUTE: 'Absolute', diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModelListReducer.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModelListReducer.js index fd73b462a3..36a190a39c 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModelListReducer.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/LicenseModelListReducer.js @@ -19,8 +19,6 @@ export default (state = [], action) => { switch (action.type) { case actionTypes.LICENSE_MODELS_LIST_LOADED: return [...action.response.results]; - case actionTypes.ADD_LICENSE_MODEL: - return [...state, action.licenseModel]; default: return state; } diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreation.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreation.js index 39b3c15c6a..71f41710db 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreation.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreation.js @@ -14,34 +14,42 @@ * permissions and limitations under the License. */ import {connect} from 'react-redux'; -import OnboardingActionHelper from 'sdc-app/onboarding/OnboardingActionHelper.js'; import LicenseModelCreationActionHelper from './LicenseModelCreationActionHelper.js'; import LicenseModelCreationView from './LicenseModelCreationView.jsx'; import ValidationHelper from 'sdc-app/common/helpers/ValidationHelper.js'; import LicenseModelActionHelper from 'sdc-app/onboarding/licenseModel/LicenseModelActionHelper.js'; +import VersionsPageActionHelper from 'sdc-app/onboarding/versionsPage/VersionsPageActionHelper.js'; +import {itemTypes as versionItemTypes} from 'sdc-app/onboarding/versionsPage/VersionsPageConstants.js'; +import ScreensHelper from 'sdc-app/common/helpers/ScreensHelper.js'; +import {enums, screenTypes} from 'sdc-app/onboarding/OnboardingConstants.js'; +import PermissionsActionHelper from 'sdc-app/onboarding/permissions/PermissionsActionHelper.js'; -export const mapStateToProps = ({licenseModelList, licenseModel: {licenseModelCreation}}) => { +export const mapStateToProps = ({users: {usersList}, licenseModelList, licenseModel: {licenseModelCreation}}) => { let {genericFieldInfo} = licenseModelCreation; let isFormValid = ValidationHelper.checkFormValid(genericFieldInfo); let VLMNames = {}; for (let i = 0; i < licenseModelList.length; i++) { - VLMNames[licenseModelList[i].vendorName.toLowerCase()] = licenseModelList[i].id; + VLMNames[licenseModelList[i].name.toLowerCase()] = licenseModelList[i].id; } - return {...licenseModelCreation, isFormValid: isFormValid, VLMNames}; + return {...licenseModelCreation, isFormValid: isFormValid, VLMNames, usersList}; }; export const mapActionsToProps = (dispatch) => { return { onDataChanged: (deltaData, formName, customValidations) => ValidationHelper.dataChanged(dispatch, {deltaData, formName, customValidations}), onCancel: () => LicenseModelCreationActionHelper.close(dispatch), - onSubmit: (licenseModel) => { + onSubmit: (licenseModel, usersList) => { LicenseModelCreationActionHelper.close(dispatch); LicenseModelCreationActionHelper.createLicenseModel(dispatch, {licenseModel}).then(response => { - LicenseModelActionHelper.fetchLicenseModels(dispatch).then(() => { - OnboardingActionHelper.navigateToLicenseModelOverview(dispatch, {licenseModelId: response.value}); - }); + let {itemId, version} = response; + LicenseModelActionHelper.fetchLicenseModels(dispatch).then(() => + PermissionsActionHelper.fetchItemUsers(dispatch, {itemId, allUsers: usersList}).then(() => + VersionsPageActionHelper.fetchVersions(dispatch, {itemType: versionItemTypes.LICENSE_MODEL, itemId}).then(() => + ScreensHelper.loadScreen(dispatch, {screen: enums.SCREEN.LICENSE_MODEL_OVERVIEW, screenType: screenTypes.LICENSE_MODEL, + props: {licenseModelId: itemId, version}}) + ))); }); }, onValidateForm: (formName) => ValidationHelper.validateForm(dispatch, formName) diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreationActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreationActionHelper.js index 51f5b7f276..87df1386b6 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreationActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreationActionHelper.js @@ -61,7 +61,13 @@ export default { }, createLicenseModel(dispatch, {licenseModel}){ - return createLicenseModel(licenseModel); + return createLicenseModel(licenseModel).then(result => { + dispatch({ + type: actionTypes.LICENSE_MODEL_CREATED, + result + }); + return result; + }); } }; diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreationConstants.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreationConstants.js index 28f1175676..e9b1c46bef 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreationConstants.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreationConstants.js @@ -17,7 +17,8 @@ import keyMirror from 'nfvo-utils/KeyMirror.js'; export const actionTypes = keyMirror({ OPEN: null, - CLOSE: null + CLOSE: null, + LICENSE_MODEL_CREATED: null }); export const LICENSE_MODEL_CREATION_FORM_NAME = 'LMCREATIONFORM'; diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreationView.jsx b/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreationView.jsx index 80040460c0..948bdc158d 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreationView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/creation/LicenseModelCreationView.jsx @@ -14,27 +14,29 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Validator from 'nfvo-utils/Validator.js'; import Input from 'nfvo-components/input/validation/Input.jsx'; import Form from 'nfvo-components/input/validation/Form.jsx'; import {LICENSE_MODEL_CREATION_FORM_NAME} from './LicenseModelCreationConstants.js'; -const LicenseModelPropType = React.PropTypes.shape({ - id: React.PropTypes.string, - vendorName: React.PropTypes.string, - description: React.PropTypes.string +const LicenseModelPropType = PropTypes.shape({ + id: PropTypes.string, + vendorName: PropTypes.string, + description: PropTypes.string }); class LicenseModelCreationView extends React.Component { static propTypes = { data: LicenseModelPropType, - VLMNames: React.PropTypes.object, - onDataChanged: React.PropTypes.func.isRequired, - onSubmit: React.PropTypes.func.isRequired, - onValidateForm: React.PropTypes.func.isRequired, - onCancel: React.PropTypes.func.isRequired + VLMNames: PropTypes.object, + usersList: PropTypes.array, + onDataChanged: PropTypes.func.isRequired, + onSubmit: PropTypes.func.isRequired, + onValidateForm: PropTypes.func.isRequired, + onCancel: PropTypes.func.isRequired }; render() { @@ -46,6 +48,7 @@ class LicenseModelCreationView extends React.Component { ref='validationForm' hasButtons={true} onSubmit={ () => this.submit() } + submitButtonText={i18n('Create')} onReset={ () => this.props.onCancel() } labledButtons={true} isValid={this.props.isFormValid} @@ -79,8 +82,8 @@ class LicenseModelCreationView extends React.Component { submit() { - const {data:licenseModel} = this.props; - this.props.onSubmit(licenseModel); + const {data:licenseModel, usersList} = this.props; + this.props.onSubmit(licenseModel, usersList); } validateName(value) { diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsActionHelper.js index ce4327d810..09a6e8228c 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsActionHelper.js @@ -16,9 +16,9 @@ import RestAPIUtil from 'nfvo-utils/RestAPIUtil.js'; import Configuration from 'sdc-app/config/Configuration.js'; import {actionTypes as entitlementPoolsActionTypes } from './EntitlementPoolsConstants.js'; -import LicenseModelActionHelper from 'sdc-app/onboarding/licenseModel/LicenseModelActionHelper.js'; import {actionTypes as limitEditorActions} from 'sdc-app/onboarding/licenseModel/limits/LimitEditorConstants.js'; import {default as getValue, getStrValue} from 'nfvo-utils/getValue.js'; +import ItemsHelper from 'sdc-app/common/helpers/ItemsHelper.js'; function baseUrl(licenseModelId, version) { const restPrefix = Configuration.get('restPrefix'); @@ -124,6 +124,7 @@ export default { type: entitlementPoolsActionTypes.DELETE_ENTITLEMENT_POOL, entitlementPoolId }); + ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); }); }, @@ -147,6 +148,7 @@ export default { type: entitlementPoolsActionTypes.EDIT_ENTITLEMENT_POOL, entitlementPool }); + ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); }); } else { @@ -159,6 +161,7 @@ export default { id: response.value } }); + ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); }); } }, @@ -176,11 +179,6 @@ export default { }); }, - switchVersion(dispatch, {licenseModelId, version}) { - LicenseModelActionHelper.fetchLicenseModelById(dispatch, {licenseModelId, version}).then(() => { - this.fetchEntitlementPoolsList(dispatch, {licenseModelId, version}); - }); - }, fetchLimits(dispatch, {licenseModelId, version, entitlementPool}) { @@ -200,12 +198,14 @@ export default { type: limitEditorActions.CLOSE }); this.fetchLimits(dispatch, {licenseModelId, version, entitlementPool}); + ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); }); }, deleteLimit(dispatch, {licenseModelId, version, entitlementPool, limit}) { return deleteLimit(licenseModelId,entitlementPool.id, version, limit.id).then(() => { this.fetchLimits(dispatch, {licenseModelId, version, entitlementPool}); + ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); }); } }; diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsEditorView.jsx index 8473c1a2be..154174cf6c 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsEditorView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Validator from 'nfvo-utils/Validator.js'; @@ -34,19 +35,19 @@ import Tab from 'sdc-ui/lib/react/Tab.js'; import EntitlementPoolsLimits from './EntitlementPoolsLimits.js'; import {limitType, NEW_LIMIT_TEMP_ID} from '../limits/LimitEditorConstants.js'; -const EntitlementPoolPropType = React.PropTypes.shape({ - id: React.PropTypes.string, - name: React.PropTypes.string, - description: React.PropTypes.string, - operationalScope: React.PropTypes.shape({ - choices: React.PropTypes.array, - other: React.PropTypes.string +const EntitlementPoolPropType = PropTypes.shape({ + id: PropTypes.string, + name: PropTypes.string, + description: PropTypes.string, + operationalScope: PropTypes.shape({ + choices: PropTypes.array, + other: PropTypes.string }), - thresholdUnits: React.PropTypes.string, - thresholdValue: React.PropTypes.number, - increments: React.PropTypes.string, - startDate: React.PropTypes.string, - expiryDate: React.PropTypes.string + thresholdUnits: PropTypes.string, + thresholdValue: PropTypes.string, + increments: PropTypes.string, + startDate: PropTypes.string, + expiryDate: PropTypes.string }); const EntitlementPoolsFormContent = ({data, genericFieldInfo, onDataChanged, validateName, @@ -55,7 +56,7 @@ const EntitlementPoolsFormContent = ({data, genericFieldInfo, onDataChanged, val let {name, description, operationalScope, thresholdUnits, thresholdValue, increments, startDate, expiryDate} = data; return ( - + onDataChanged({name}, SP_ENTITLEMENT_POOL_FORM, {name: validateName})} @@ -67,7 +68,7 @@ const EntitlementPoolsFormContent = ({data, genericFieldInfo, onDataChanged, val data-test-id='create-ep-name' type='text'/> - + {}} isMultiSelect={true} @@ -94,7 +95,7 @@ const EntitlementPoolsFormContent = ({data, genericFieldInfo, onDataChanged, val data-test-id='create-ep-description' type='textarea'/> - +
    { @@ -152,7 +153,7 @@ const EntitlementPoolsFormContent = ({data, genericFieldInfo, onDataChanged, val )} isValid={genericFieldInfo.startDate.isValid} errorText={genericFieldInfo.startDate.errorText} - selectsStart/> + selectsStart/> -
    -
    +
    + ); }; @@ -178,18 +179,18 @@ class EntitlementPoolsEditorView extends React.Component { static propTypes = { data: EntitlementPoolPropType, previousData: EntitlementPoolPropType, - EPNames: React.PropTypes.object, - isReadOnlyMode: React.PropTypes.bool, - onDataChanged: React.PropTypes.func.isRequired, - onSubmit: React.PropTypes.func.isRequired, - onCancel: React.PropTypes.func.isRequired + EPNames: PropTypes.object, + isReadOnlyMode: PropTypes.bool, + onDataChanged: PropTypes.func.isRequired, + onSubmit: PropTypes.func.isRequired, + onCancel: PropTypes.func.isRequired }; static defaultProps = { data: {} }; - componentDidUpdate(prevProps) { + componentDidUpdate(prevProps) { if (this.props.formReady && this.props.formReady !== prevProps.formReady) { // if form validation succeeded -> continue with submit this.submit(); } @@ -207,9 +208,9 @@ class EntitlementPoolsEditorView extends React.Component { return (
    - { if (tabIndex === tabIds.ADD_LIMIT_BUTTON) { this.onAddLimit(); @@ -218,14 +219,13 @@ class EntitlementPoolsEditorView extends React.Component { this.setState({selectedLimit: ''}); onCloseLimitEditor(); } - - }} + }} invalidTabs={[]}> { genericFieldInfo &&
    - {selectedTab === tabIds.SP_LIMITS && - item.type === limitType.SERVICE_PROVIDER)} selectedLimit={this.state.selectedLimit} onCloseLimitEditor={() => this.onCloseLimitEditor()} onSelectLimit={limit => this.onSelectLimit(limit)}/>} - {selectedTab === tabIds.VENDOR_LIMITS && - item.type === limitType.VENDOR)} selectedLimit={this.state.selectedLimit} onCloseLimitEditor={() => this.onCloseLimitEditor()} @@ -273,7 +273,7 @@ class EntitlementPoolsEditorView extends React.Component { {i18n('Add Limit')} : -
    // Render empty div to not break tabs +
    // Render empty div to not break tabs } @@ -285,21 +285,18 @@ class EntitlementPoolsEditorView extends React.Component { - +
    ); } submit() { const {data: entitlementPool, previousData: previousEntitlementPool, formReady} = this.props; - if (!formReady) { this.props.onValidateForm(SP_ENTITLEMENT_POOL_FORM); } else { this.props.onSubmit({entitlementPool, previousEntitlementPool}); } - - } validateName(value) { @@ -329,8 +326,6 @@ class EntitlementPoolsEditorView extends React.Component { this.props.onOpenLimitEditor(); } - - } export default EntitlementPoolsEditorView; diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsLimits.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsLimits.js index 1eb6eebff8..8300594098 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsLimits.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsLimits.js @@ -20,10 +20,10 @@ import Limits from 'sdc-app/onboarding/licenseModel/limits/Limits.jsx'; import {actionTypes as globalModalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; import EntitlementPoolsActionHelper from './EntitlementPoolsActionHelper.js'; -const mapStateToProps = ({licenseModel: {entitlementPool: {entitlementPoolEditor: {data}}, limitEditor}, currentScreen}) => { +const mapStateToProps = ({licenseModel: {entitlementPool: {entitlementPoolEditor: {data}}, limitEditor}, currentScreen}) => { let {props: {licenseModelId, version}} = currentScreen; return { - parent: data, + parent: data, limitEditor, licenseModelId, version @@ -42,10 +42,10 @@ const mapActionsToProps = (dispatch) => { onDelete: ({limit, parent, licenseModelId, version, onCloseLimitEditor, selectedLimit}) => dispatch({ type: globalModalActionTypes.GLOBAL_MODAL_WARNING, data:{ - msg: i18n(`Are you sure you want to delete ${limit.name}?`), + msg: i18n('Are you sure you want to delete {name}?', {name: limit.name}), confirmationButtonText: i18n('Delete'), title: i18n('Delete'), - onConfirmed: ()=> EntitlementPoolsActionHelper.deleteLimit(dispatch, {limit, entitlementPool: parent, licenseModelId, version}).then(() => + onConfirmed: ()=> EntitlementPoolsActionHelper.deleteLimit(dispatch, {limit, entitlementPool: parent, licenseModelId, version}).then(() => selectedLimit === limit.id && onCloseLimitEditor() ) } @@ -53,4 +53,4 @@ const mapActionsToProps = (dispatch) => { }; }; -export default connect(mapStateToProps, mapActionsToProps)(Limits); \ No newline at end of file +export default connect(mapStateToProps, mapActionsToProps)(Limits); diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsListEditor.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsListEditor.js index fa21109541..f1dc1f8542 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsListEditor.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsListEditor.js @@ -14,26 +14,24 @@ * permissions and limitations under the License. */ import {connect} from 'react-redux'; -import i18n from 'nfvo-utils/i18n/i18n.js'; +import i18n from 'nfvo-utils/i18n/i18n.js'; import EntitlementPoolsActionHelper from './EntitlementPoolsActionHelper.js'; import EntitlementPoolsListEditorView, {generateConfirmationMsg} from './EntitlementPoolsListEditorView.jsx'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import {actionTypes as globalMoadlActions} from 'nfvo-components/modal/GlobalModalConstants.js'; const mapStateToProps = ({licenseModel: {entitlementPool, licenseModelEditor}}) => { - let {entitlementPoolsList} = entitlementPool; - let {data} = entitlementPool.entitlementPoolEditor; - let {vendorName} = licenseModelEditor.data; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(licenseModelEditor.data); + const {entitlementPoolsList} = entitlementPool; + const {data} = entitlementPool.entitlementPoolEditor; + const {vendorName} = licenseModelEditor.data; return { vendorName, entitlementPoolsList, - isReadOnlyMode, isDisplayModal: Boolean(data), isModalInEditMode: Boolean(data && data.id), }; + }; const mapActionsToProps = (dispatch, {licenseModelId, version}) => { @@ -46,7 +44,7 @@ const mapActionsToProps = (dispatch, {licenseModelId, version}) => { msg: generateConfirmationMsg(entitlementPool), confirmationButtonText: i18n('Delete'), title: i18n('Delete'), - onConfirmed: ()=>EntitlementPoolsActionHelper.deleteEntitlementPool(dispatch, { + onConfirmed: () => EntitlementPoolsActionHelper.deleteEntitlementPool(dispatch, { licenseModelId, entitlementPoolId: entitlementPool.id, version diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsListEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsListEditorView.jsx index c730d669c7..cc0cda1992 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsListEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsListEditorView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Modal from 'nfvo-components/modal/Modal.jsx'; @@ -25,15 +26,15 @@ import {extractUnits} from './EntitlementPoolsConstants'; class EntitlementPoolsListEditorView extends React.Component { static propTypes = { - vendorName: React.PropTypes.string, - licenseModelId: React.PropTypes.string.isRequired, - entitlementPoolsList: React.PropTypes.array, - isReadOnlyMode: React.PropTypes.bool.isRequired, - isDisplayModal: React.PropTypes.bool, - isModalInEditMode: React.PropTypes.bool, - onAddEntitlementPoolClick: React.PropTypes.func, - onEditEntitlementPoolClick: React.PropTypes.func, - onDeleteEntitlementPool: React.PropTypes.func, + vendorName: PropTypes.string, + licenseModelId: PropTypes.string.isRequired, + entitlementPoolsList: PropTypes.array, + isReadOnlyMode: PropTypes.bool.isRequired, + isDisplayModal: PropTypes.bool, + isModalInEditMode: PropTypes.bool, + onAddEntitlementPoolClick: PropTypes.func, + onEditEntitlementPoolClick: PropTypes.func, + onDeleteEntitlementPool: PropTypes.func, }; static defaultProps = { @@ -50,7 +51,7 @@ class EntitlementPoolsListEditorView extends React.Component { const {localFilter} = this.state; return ( -
    +
    0 ? diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupEditorView.jsx index 6a5ee4617c..6d0acaa65d 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupEditorView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import Tabs from 'nfvo-components/input/validation/Tabs.jsx'; import Tab from 'sdc-ui/lib/react/Tab.js'; import GridSection from 'nfvo-components/grid/GridSection.jsx'; @@ -26,20 +27,20 @@ import Validator from 'nfvo-utils/Validator.js'; import {state as FeatureGroupStateConstants, FG_EDITOR_FORM} from './FeatureGroupsConstants.js'; -const FeatureGroupsPropType = React.PropTypes.shape({ - id: React.PropTypes.string, - name: React.PropTypes.string, - description: React.PropTypes.string, - partNumber: React.PropTypes.string, - manufacturerReferenceNumber: React.PropTypes.string, - entitlementPoolsIds: React.PropTypes.arrayOf(React.PropTypes.string), - licenseKeyGroupsIds: React.PropTypes.arrayOf(React.PropTypes.string) +const FeatureGroupsPropType = PropTypes.shape({ + id: PropTypes.string, + name: PropTypes.string, + description: PropTypes.string, + partNumber: PropTypes.string, + manufacturerReferenceNumber: PropTypes.string, + entitlementPoolsIds: PropTypes.arrayOf(PropTypes.string), + licenseKeyGroupsIds: PropTypes.arrayOf(PropTypes.string) }); const GeneralTab = ({data = {}, onDataChanged, genericFieldInfo, validateName}) => { let {name, description, partNumber, manufacturerReferenceNumber} = data; return ( - + - + - + onDataChanged({manufacturerReferenceNumber}, FG_EDITOR_FORM)} @@ -142,14 +143,14 @@ class FeatureGroupEditorView extends React.Component { static propTypes = { data: FeatureGroupsPropType, previousData: FeatureGroupsPropType, - isReadOnlyMode: React.PropTypes.bool, - FGNames: React.PropTypes.object, + isReadOnlyMode: PropTypes.bool, + FGNames: PropTypes.object, - onSubmit: React.PropTypes.func, - onCancel: React.PropTypes.func, + onSubmit: PropTypes.func, + onCancel: PropTypes.func, - selectedTab: React.PropTypes.number, - onTabSelect: React.PropTypes.func, + selectedTab: PropTypes.number, + onTabSelect: PropTypes.func, entitlementPoolsList: DualListboxView.propTypes.availableList, licenseKeyGroupsList: DualListboxView.propTypes.availableList diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupListEditor.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupListEditor.js index fc892387c6..26925487db 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupListEditor.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupListEditor.js @@ -14,17 +14,16 @@ * permissions and limitations under the License. */ import {connect} from 'react-redux'; - import FeatureGroupsActionHelper from './FeatureGroupsActionHelper.js'; import FeatureGroupListEditorView, {generateConfirmationMsg} from './FeatureGroupListEditorView.jsx'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import i18n from 'nfvo-utils/i18n/i18n.js'; import {actionTypes as globalMoadlActions} from 'nfvo-components/modal/GlobalModalConstants.js'; export const mapStateToProps = ({licenseModel: {featureGroup, licenseModelEditor}}) => { + const {featureGroupEditor: {data}, featureGroupsList} = featureGroup; - let {vendorName, version} = licenseModelEditor.data; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(licenseModelEditor.data); + const {vendorName, version} = licenseModelEditor.data; + return { vendorName, version, @@ -32,9 +31,9 @@ export const mapStateToProps = ({licenseModel: {featureGroup, licenseModelEditor show: Boolean(data), editMode: Boolean(data && data.id) }, - featureGroupsList, - isReadOnlyMode + featureGroupsList }; + }; diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupListEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupListEditorView.jsx index 497c29d14c..f59e000c21 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupListEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupListEditorView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Modal from 'nfvo-components/modal/Modal.jsx'; @@ -24,18 +25,18 @@ import FeatureGroupEditor from './FeatureGroupEditor.js'; class FeatureGroupListEditorView extends React.Component { static propTypes = { - vendorName: React.PropTypes.string, - licenseModelId: React.PropTypes.string.isRequired, - featureGroupsModal: React.PropTypes.shape({ - show: React.PropTypes.bool, - editMode: React.PropTypes.bool + vendorName: PropTypes.string, + licenseModelId: PropTypes.string.isRequired, + featureGroupsModal: PropTypes.shape({ + show: PropTypes.bool, + editMode: PropTypes.bool }), - isReadOnlyMode: React.PropTypes.bool.isRequired, - onAddFeatureGroupClick: React.PropTypes.func, - onEditFeatureGroupClick: React.PropTypes.func, - onDeleteFeatureGroupClick: React.PropTypes.func, - onCancelFeatureGroupsEditor: React.PropTypes.func, - featureGroupsList: React.PropTypes.array + isReadOnlyMode: PropTypes.bool.isRequired, + onAddFeatureGroupClick: PropTypes.func, + onEditFeatureGroupClick: PropTypes.func, + onDeleteFeatureGroupClick: PropTypes.func, + onCancelFeatureGroupsEditor: PropTypes.func, + featureGroupsList: PropTypes.array }; static defaultProps = { @@ -54,7 +55,7 @@ class FeatureGroupListEditorView extends React.Component { let {licenseModelId, featureGroupsModal, isReadOnlyMode, onAddFeatureGroupClick, version} = this.props; const {localFilter} = this.state; return ( -
    +
    0 ? i18n('This feature group is associated with one ore more license agreements') : diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupsActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupsActionHelper.js index b8c03750fb..aadf8e0301 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupsActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupsActionHelper.js @@ -16,9 +16,9 @@ import RestAPIUtil from 'nfvo-utils/RestAPIUtil.js'; import Configuration from 'sdc-app/config/Configuration.js'; import {actionTypes as featureGroupsActionConstants} from './FeatureGroupsConstants.js'; -import LicenseModelActionHelper from 'sdc-app/onboarding/licenseModel/LicenseModelActionHelper.js'; import EntitlementPoolsActionHelper from 'sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsActionHelper.js'; import LicenseKeyGroupsActionHelper from 'sdc-app/onboarding/licenseModel/licenseKeyGroups/LicenseKeyGroupsActionHelper.js'; +import ItemsHelper from 'sdc-app/common/helpers/ItemsHelper.js'; function baseUrl(licenseModelId, version) { const restPrefix = Configuration.get('restPrefix'); @@ -26,6 +26,10 @@ function baseUrl(licenseModelId, version) { return `${restPrefix}/v1.0/vendor-license-models/${licenseModelId}/versions/${versionId}/feature-groups`; } +function fetchFeatureGroup(licenseModelId, featureGroupId, version) { + return RestAPIUtil.fetch(`${baseUrl(licenseModelId, version)}/${featureGroupId}`); +} + function fetchFeatureGroupsList(licenseModelId, version) { return RestAPIUtil.fetch(`${baseUrl(licenseModelId, version)}`); } @@ -65,6 +69,10 @@ function updateFeatureGroup(licenseModelId, previousFeatureGroup, featureGroup, } export default { + fetchFeatureGroup(dispatch, {licenseModelId, featureGroupId, version}) { + return fetchFeatureGroup(licenseModelId, featureGroupId, version); + }, + fetchFeatureGroupsList(dispatch, {licenseModelId, version}) { return fetchFeatureGroupsList(licenseModelId, version).then(response => dispatch({ type: featureGroupsActionConstants.FEATURE_GROUPS_LIST_LOADED, @@ -73,10 +81,13 @@ export default { }, deleteFeatureGroup(dispatch, {licenseModelId, featureGroupId, version}) { - return deleteFeatureGroup(licenseModelId, featureGroupId, version).then(() => dispatch({ - type: featureGroupsActionConstants.DELETE_FEATURE_GROUPS, - featureGroupId - })); + return deleteFeatureGroup(licenseModelId, featureGroupId, version).then(() => { + dispatch({ + type: featureGroupsActionConstants.DELETE_FEATURE_GROUPS, + featureGroupId + }); + ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); + }); }, saveFeatureGroup(dispatch, {licenseModelId, previousFeatureGroup, featureGroup, version}) { @@ -88,6 +99,7 @@ export default { }); EntitlementPoolsActionHelper.fetchEntitlementPoolsList(dispatch, {licenseModelId, version}); LicenseKeyGroupsActionHelper.fetchLicenseKeyGroupsList(dispatch, {licenseModelId, version}); + ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); }); } else { @@ -102,6 +114,7 @@ export default { }); EntitlementPoolsActionHelper.fetchEntitlementPoolsList(dispatch, {licenseModelId, version}); LicenseKeyGroupsActionHelper.fetchLicenseKeyGroupsList(dispatch, {licenseModelId, version}); + ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); }); } }, @@ -114,11 +127,14 @@ export default { }, openFeatureGroupsEditor(dispatch, {featureGroup, licenseModelId, version}) { - EntitlementPoolsActionHelper.fetchEntitlementPoolsList(dispatch, {licenseModelId, version}); - LicenseKeyGroupsActionHelper.fetchLicenseKeyGroupsList(dispatch, {licenseModelId, version}); - dispatch({ - type: featureGroupsActionConstants.featureGroupsEditor.OPEN, - featureGroup + return Promise.all([ + EntitlementPoolsActionHelper.fetchEntitlementPoolsList(dispatch, {licenseModelId, version}), + LicenseKeyGroupsActionHelper.fetchLicenseKeyGroupsList(dispatch, {licenseModelId, version}) + ]).then(() => { + dispatch({ + type: featureGroupsActionConstants.featureGroupsEditor.OPEN, + featureGroup + }); }); }, @@ -126,12 +142,5 @@ export default { dispatch({ type: featureGroupsActionConstants.featureGroupsEditor.CLOSE }); - }, - - - switchVersion(dispatch, {licenseModelId, version}) { - LicenseModelActionHelper.fetchLicenseModelById(dispatch, {licenseModelId, version}).then(() => { - this.fetchFeatureGroupsList(dispatch, {licenseModelId, version}); - }); } }; diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementActionHelper.js index e9d922c212..b4f03a68cd 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementActionHelper.js @@ -17,7 +17,7 @@ import RestAPIUtil from 'nfvo-utils/RestAPIUtil.js'; import Configuration from 'sdc-app/config/Configuration.js'; import {actionTypes as licenseAgreementActionTypes} from './LicenseAgreementConstants.js'; import FeatureGroupsActionHelper from 'sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupsActionHelper.js'; -import LicenseModelActionHelper from 'sdc-app/onboarding/licenseModel/LicenseModelActionHelper.js'; +import ItemsHelper from 'sdc-app/common/helpers/ItemsHelper.js'; function baseUrl(licenseModelId, version) { const restPrefix = Configuration.get('restPrefix'); @@ -29,6 +29,10 @@ function fetchLicenseAgreementList(licenseModelId, version) { return RestAPIUtil.fetch(`${baseUrl(licenseModelId, version)}`); } +function fetchLicenseAgreement(licenseModelId, licenseAgreementId, version) { + return RestAPIUtil.fetch(`${baseUrl(licenseModelId, version)}/${licenseAgreementId}`); +} + function postLicenseAgreement(licenseModelId, licenseAgreement, version) { return RestAPIUtil.post(baseUrl(licenseModelId, version), { name: licenseAgreement.name, @@ -65,6 +69,10 @@ export default { })); }, + fetchLicenseAgreement(dispatch, {licenseModelId, licenseAgreementId, version}) { + return fetchLicenseAgreement(licenseModelId, licenseAgreementId, version); + }, + openLicenseAgreementEditor(dispatch, {licenseModelId, licenseAgreement, version}) { FeatureGroupsActionHelper.fetchFeatureGroupsList(dispatch, {licenseModelId, version}); dispatch({ @@ -84,12 +92,14 @@ export default { if (previousLicenseAgreement) { return putLicenseAgreement(licenseModelId, previousLicenseAgreement, licenseAgreement, version).then(() => { this.fetchLicenseAgreementList(dispatch, {licenseModelId, version}); + ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); }); } else { return postLicenseAgreement(licenseModelId, licenseAgreement, version).then(() => { this.fetchLicenseAgreementList(dispatch, {licenseModelId, version}); FeatureGroupsActionHelper.fetchFeatureGroupsList(dispatch, {licenseModelId, version}); + ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); }); } }, @@ -100,6 +110,7 @@ export default { type: licenseAgreementActionTypes.DELETE_LICENSE_AGREEMENT, licenseAgreementId }); + ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); }); }, @@ -108,11 +119,5 @@ export default { type: licenseAgreementActionTypes.licenseAgreementEditor.SELECT_TAB, tab }); - }, - - switchVersion(dispatch, {licenseModelId, version}) { - LicenseModelActionHelper.fetchLicenseModelById(dispatch, {licenseModelId, version}).then(() => { - this.fetchLicenseAgreementList(dispatch, {licenseModelId, version}); - }); } }; diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementEditorView.jsx index 0b418686fd..a3e73f4f14 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementEditorView.jsx @@ -14,7 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; - +import PropTypes from 'prop-types'; import GridSection from 'nfvo-components/grid/GridSection.jsx'; import GridItem from 'nfvo-components/grid/GridItem.jsx'; import {TabsForm as Form} from 'nfvo-components/input/validation/Form.jsx'; @@ -34,21 +34,21 @@ const dualBoxFilterTitle = { right: i18n('Selected Feature Groups') }; -const LicenseAgreementPropType = React.PropTypes.shape({ - id: React.PropTypes.string, - name: React.PropTypes.string, - description: React.PropTypes.string, - requirementsAndConstrains: React.PropTypes.string, - licenseTerm: React.PropTypes.object, - featureGroupsIds: React.PropTypes.arrayOf(React.PropTypes.string), - version: React.PropTypes.object +const LicenseAgreementPropType = PropTypes.shape({ + id: PropTypes.string, + name: PropTypes.string, + description: PropTypes.string, + requirementsAndConstrains: PropTypes.string, + licenseTerm: PropTypes.object, + featureGroupsIds: PropTypes.arrayOf(PropTypes.string), + version: PropTypes.object }); const GeneralTabContent = ({data, genericFieldInfo, onDataChanged, validateName}) => { let {name, description, requirementsAndConstrains, licenseTerm} = data; return ( - + - +
    - this.validateLTChoice(value)} validateName={(value)=>this.validateName(value)}/>
    @@ -181,6 +181,12 @@ class LicenseAgreementEditorView extends React.Component { this.props.onSubmit({licenseAgreement, previousLicenseAgreement}); } + validateLTChoice(value) { + if (!value.choice) { + return {isValid: false, errorText: i18n('Field is required')}; + } + return {isValid: true, errorText: ''}; + } validateName(value) { const {data: {id}, LANames} = this.props; diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementListEditor.js b/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementListEditor.js index 92c2550c1c..72474ecdd3 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementListEditor.js +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementListEditor.js @@ -17,24 +17,22 @@ import {connect} from 'react-redux'; import i18n from 'nfvo-utils/i18n/i18n.js'; import LicenseAgreementActionHelper from './LicenseAgreementActionHelper.js'; import LicenseAgreementListEditorView from './LicenseAgreementListEditorView.jsx'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import {actionTypes as globalMoadlActions} from 'nfvo-components/modal/GlobalModalConstants.js'; const mapStateToProps = ({licenseModel: {licenseAgreement, licenseModelEditor}}) => { + let {licenseAgreementList} = licenseAgreement; let {data} = licenseAgreement.licenseAgreementEditor; let {vendorName, version} = licenseModelEditor.data; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(licenseModelEditor.data); - return { vendorName, version, licenseAgreementList, - isReadOnlyMode, isDisplayModal: Boolean(data), isModalInEditMode: Boolean(data && data.id) }; + }; const mapActionsToProps = (dispatch, {licenseModelId}) => { @@ -44,7 +42,7 @@ const mapActionsToProps = (dispatch, {licenseModelId}) => { onDeleteLicenseAgreement: (licenseAgreement, version) => dispatch({ type: globalMoadlActions.GLOBAL_MODAL_WARNING, data:{ - msg: i18n(`Are you sure you want to delete "${licenseAgreement.name}"?`), + msg: i18n('Are you sure you want to delete "{name}"?', {name: licenseAgreement.name}), confirmationButtonText: i18n('Delete'), title: i18n('Delete'), onConfirmed: ()=>LicenseAgreementActionHelper.deleteLicenseAgreement(dispatch, {licenseModelId, licenseAgreementId: licenseAgreement.id, version}) diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementListEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementListEditorView.jsx index 6247723d72..ad3cdb0b58 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementListEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementListEditorView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Modal from 'nfvo-components/modal/Modal.jsx'; @@ -24,15 +25,15 @@ import {extractValue} from './LicenseAgreementConstants'; class LicenseAgreementListEditorView extends React.Component { static propTypes = { - vendorName: React.PropTypes.string, - licenseModelId: React.PropTypes.string.isRequired, - licenseAgreementList: React.PropTypes.array, - isReadOnlyMode: React.PropTypes.bool.isRequired, - isDisplayModal: React.PropTypes.bool, - isModalInEditMode: React.PropTypes.bool, - onAddLicenseAgreementClick: React.PropTypes.func, - onEditLicenseAgreementClick: React.PropTypes.func, - onDeleteLicenseAgreement: React.PropTypes.func, + vendorName: PropTypes.string, + licenseModelId: PropTypes.string.isRequired, + licenseAgreementList: PropTypes.array, + isReadOnlyMode: PropTypes.bool.isRequired, + isDisplayModal: PropTypes.bool, + isModalInEditMode: PropTypes.bool, + onAddLicenseAgreementClick: PropTypes.func, + onEditLicenseAgreementClick: PropTypes.func, + onDeleteLicenseAgreement: PropTypes.func, }; static defaultProps = { @@ -49,7 +50,7 @@ class LicenseAgreementListEditorView extends React.Component { const {localFilter} = this.state; return ( -
    +
    { - this.fetchLicenseKeyGroupsList(dispatch, {licenseModelId, version}); - }); - }, - fetchLimits(dispatch, {licenseModelId, version, licenseKeyGroup}) { return fetchLimitsList(licenseModelId, licenseKeyGroup.id, version).then(response => { @@ -193,12 +190,14 @@ export default { type: limitEditorActions.CLOSE }); this.fetchLimits(dispatch, {licenseModelId, version, licenseKeyGroup}); + ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); }); }, deleteLimit(dispatch, {licenseModelId, version, licenseKeyGroup, limit}) { return deleteLimit(licenseModelId,licenseKeyGroup.id, version, limit.id).then(() => { this.fetchLimits(dispatch, {licenseModelId, version, licenseKeyGroup}); + ItemsHelper.checkItemStatus(dispatch, {itemId: licenseModelId, versionId: version.id}); }); } diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseKeyGroups/LicenseKeyGroupsEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseKeyGroups/LicenseKeyGroupsEditorView.jsx index 70fb43ee88..87c947eb02 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseKeyGroups/LicenseKeyGroupsEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseKeyGroups/LicenseKeyGroupsEditorView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Validator from 'nfvo-utils/Validator.js'; @@ -36,26 +37,26 @@ import {DATE_FORMAT} from 'sdc-app/onboarding/OnboardingConstants.js'; import LicenseKeyGroupsLimits from './LicenseKeyGroupsLimits.js'; import {limitType, NEW_LIMIT_TEMP_ID} from '../limits/LimitEditorConstants.js'; - const LicenseKeyGroupPropType = React.PropTypes.shape({ - id: React.PropTypes.string, - name: React.PropTypes.string, - description: React.PropTypes.string, - increments: React.PropTypes.string, - operationalScope: React.PropTypes.shape({ - choices: React.PropTypes.array, - other: React.PropTypes.string + const LicenseKeyGroupPropType = PropTypes.shape({ + id: PropTypes.string, + name: PropTypes.string, + description: PropTypes.string, + increments: PropTypes.string, + operationalScope: PropTypes.shape({ + choices: PropTypes.array, + other: PropTypes.string }), - type: React.PropTypes.string, - thresholdUnits: React.PropTypes.string, - thresholdValue: React.PropTypes.number, - startDate: React.PropTypes.string, - expiryDate: React.PropTypes.string + type: PropTypes.string, + thresholdUnits: PropTypes.string, + thresholdValue: PropTypes.number, + startDate: PropTypes.string, + expiryDate: PropTypes.string }); const LicenseKeyGroupFormContent = ({data, onDataChanged, genericFieldInfo, validateName, validateStartDate, thresholdValueValidation}) => { let {name, description, increments, operationalScope, type, thresholdUnits, thresholdValue, startDate, expiryDate} = data; return ( - + onDataChanged({name}, LKG_FORM_NAME, {name: validateName})} @@ -67,7 +68,7 @@ const LicenseKeyGroupFormContent = ({data, onDataChanged, genericFieldInfo, vali isRequired={true} type='text'/> - + {}} isMultiSelect={true} @@ -95,7 +96,7 @@ const LicenseKeyGroupFormContent = ({data, onDataChanged, genericFieldInfo, vali type='textarea' overlayPos='bottom' /> - + { const selectedIndex = e.target.selectedIndex; @@ -108,6 +109,7 @@ const LicenseKeyGroupFormContent = ({data, onDataChanged, genericFieldInfo, vali errorText={genericFieldInfo.type.errorText} groupClassName='bootstrap-input-options' className='input-options-select' + overlayPos='bottom' type='select' > { licenseKeyGroupOptionsInputValues.TYPE.map(type => @@ -167,7 +169,7 @@ const LicenseKeyGroupFormContent = ({data, onDataChanged, genericFieldInfo, vali errorText={genericFieldInfo.startDate.errorText} selectsStart/> - + continue with submit this.submit(); } @@ -229,8 +231,8 @@ class LicenseKeyGroupsEditorView extends React.Component { return (
    { if (tabIndex === tabIds.ADD_LIMIT_BUTTON) { this.onAddLimit(); @@ -239,7 +241,7 @@ class LicenseKeyGroupsEditorView extends React.Component { onCloseLimitEditor(); this.setState({selectedLimit: ''}); } - }} + }} invalidTabs={[]}> { genericFieldInfo && @@ -292,10 +294,10 @@ class LicenseKeyGroupsEditorView extends React.Component { {i18n('Add Limit')} : -
    // Render empty div to not break tabs +
    // Render empty div to not break tabs }
    - + {!this.state.selectedLimit && + {shouldShowOverlay && softwareProductList.length > 0 && + onVendorSelect(vendor)} /> + } + + + + + + + + ); } - onClick(vlm) { - this.setState({ - licenseModelToShow: vlm - }); - } - - onCreateVspClick(event) { - let {onAddVSP, vendor: {id}} = this.props; - event.stopPropagation(); - event.preventDefault(); + onCreateVspClick(e) { + e.stopPropagation(); + e.preventDefault(); + const {onAddVSP, vendor: {id}} = this.props; onAddVSP(id); } handleVspCountClick(e){ - let {onVSPIconClick, vendor: {softwareProductList}} = this.props; e.stopPropagation(); e.preventDefault(); + const {onVSPButtonClick, vendor: {softwareProductList}} = this.props; const hasVSP = Boolean(softwareProductList.length); - onVSPIconClick(hasVSP); + onVSPButtonClick(hasVSP); } } diff --git a/openecomp-ui/src/sdc-app/onboarding/onboard/workspace/WorkspaceView.jsx b/openecomp-ui/src/sdc-app/onboarding/onboard/workspace/WorkspaceView.jsx index d86b674f13..523bbb2c8e 100644 --- a/openecomp-ui/src/sdc-app/onboarding/onboard/workspace/WorkspaceView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/onboard/workspace/WorkspaceView.jsx @@ -15,43 +15,31 @@ */ import React from 'react'; import DetailsCatalogView from '../DetailsCatalogView.jsx'; -import {statusEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import i18n from 'nfvo-utils/i18n/i18n.js'; -import {tabsMapping} from 'sdc-app/onboarding/onboard/OnboardConstants.js'; const WorkspaceView = (props) => { let { - licenseModelList, softwareProductList, onAddLicenseModelClick, + licenseModelList, softwareProductList, onAddLicenseModelClick, users, onAddSoftwareProductClick, onSelectLicenseModel, onSelectSoftwareProduct, searchValue, onMigrate } = props; - let {getCheckOutStatusKindByUserID} = VersionControllerUtils; - let unfinalizedLicenseModelList = licenseModelList.filter(vlm => { - let {status} = getCheckOutStatusKindByUserID(vlm.status, vlm.lockingUser); - return status !== statusEnum.SUBMIT_STATUS && status !== statusEnum.LOCK_STATUS; - }); - let unfinalizedSoftwareProductList = softwareProductList.filter(vsp =>{ - let {status} = getCheckOutStatusKindByUserID(vsp.status, vsp.lockingUser); - return status !== statusEnum.SUBMIT_STATUS && status !== statusEnum.LOCK_STATUS; - }); - return (
    {i18n('WORKSPACE')}
    -
    ); + filter={searchValue} /> +
    + ); }; export default WorkspaceView; diff --git a/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsActionHelper.js new file mode 100644 index 0000000000..c25d93f2fc --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsActionHelper.js @@ -0,0 +1,108 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import i18n from 'nfvo-utils/i18n/i18n.js'; +import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; +import {actionTypes} from './PermissionsConstants.js'; +import {permissionTypes} from './PermissionsConstants.js'; +import {modalContentMapper} from 'sdc-app/common/modal/ModalContentMapper.js'; +import {askForRightsMsg} from './PermissionsManager.jsx'; +import ItemsHelper from 'sdc-app/common/helpers/ItemsHelper.js'; + +const PermissionsActionHelper = { + openPermissonsManager(dispatch, {itemId, askForRights}) { + if (askForRights) { + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_SHOW, + data: { + title: i18n('Ask For Contributers Rights'), + msg: askForRightsMsg(), + confirmationButtonText: i18n('SEND'), + onConfirmed: () => this.askForContributorRights() + } + }); + } else { + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_SHOW, + data: { + modalComponentName: modalContentMapper.MANAGE_PERMISSIONS, + title: i18n('Manage Permissions'), + modalComponentProps: { + itemId + } + } + }); + } + }, + + closePermissionManager(dispatch) { + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_CLOSE + }); + }, + + saveItemUsers(dispatch, {itemId, removedUsersIds, addedUsersIds, allUsers}) { + return ItemsHelper.updateContributors({itemId, removedUsersIds, addedUsersIds}).then(() => + PermissionsActionHelper.fetchItemUsers(dispatch, {itemId, allUsers}) + ); + }, + + changeOwner(dispatch, {itemId, newOwnerId, allUsers}) { + return ItemsHelper.changeOwner({itemId, ownerId: newOwnerId}).then(() => + PermissionsActionHelper.fetchItemUsers(dispatch, {itemId, allUsers}) + ); + }, + + fetchItemUsers(dispatch, {itemId, allUsers}) { + return ItemsHelper.fetchUsers({itemId}).then(response => { + + let allContributors = response.results; + + let owner = {}; + let contributors = []; + allContributors.map(user => { + let userObject = allUsers.find(userObject => userObject.userId === user.userId); + if (userObject) { + user = {...user, fullName: userObject.fullName, role: userObject.role}; + + switch(user.permission) { + case permissionTypes.OWNER: + owner = user; + break; + case permissionTypes.CONTRIBUTOR: + contributors.push(user); + break; + } + } + }); + + dispatch({ + type: actionTypes.ITEM_USERS_LOADED, + contributors, + owner + }); + }); + }, + + askForContributorRights() { + console.log('asked for contributor rights'); + } + + + +}; + +export default PermissionsActionHelper; diff --git a/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsConstants.js b/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsConstants.js new file mode 100644 index 0000000000..48a3461799 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsConstants.js @@ -0,0 +1,27 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import keyMirror from 'nfvo-utils/KeyMirror.js'; + +export const actionTypes = keyMirror({ + ITEM_USERS_LOADED: null +}); + +export const permissionTypes = { + OWNER: 'Owner', + CONTRIBUTOR: 'Contributor' +}; + +export const changeOwnerMessage = 'You will no longer be able to manage the permissions of this item.\nYour permission level will be set to contributor.'; diff --git a/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsManager.js b/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsManager.js new file mode 100644 index 0000000000..ba6562b28f --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsManager.js @@ -0,0 +1,43 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import {connect} from 'react-redux'; +import PermissionsManager from './PermissionsManager.jsx'; +import PermissionsActionHelper from './PermissionsActionHelper.js'; + +export const mapStateToProps = ({versionsPage, users: {usersList, userInfo}}) => { + let {permissions} = versionsPage; + + return { + users: usersList, + userInfo, + owner: permissions.owner, + itemUsers: permissions.contributors + }; +}; + +const mapActionsToProps = (dispatch) => { + return { + onCancel: () => PermissionsActionHelper.closePermissionManager(dispatch), + onSubmit: ({itemId, addedUsersIds, removedUsersIds, allUsers, newOwnerId}) => { + return PermissionsActionHelper.saveItemUsers(dispatch,{itemId, addedUsersIds, removedUsersIds, allUsers}).then(() => { + return newOwnerId ? PermissionsActionHelper.changeOwner(dispatch, {itemId, newOwnerId, allUsers}) : Promise.resolve(); + }).then(() => PermissionsActionHelper.closePermissionManager(dispatch)); + } + }; +}; + +export default connect(mapStateToProps, mapActionsToProps)(PermissionsManager); diff --git a/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsManager.jsx b/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsManager.jsx new file mode 100644 index 0000000000..b7d5d57cca --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsManager.jsx @@ -0,0 +1,117 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import React from 'react'; +import Form from 'nfvo-components/input/validation/Form.jsx'; +import Select from 'nfvo-components/input/SelectInput.jsx'; +import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; +import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger.js'; +import Tooltip from 'react-bootstrap/lib/Tooltip.js'; +import i18n from 'nfvo-utils/i18n/i18n.js'; + +import {permissionTypes, changeOwnerMessage} from './PermissionsConstants.js'; + +export const askForRightsMsg = () => { + return ( +
    +

    {i18n('Send a Contributor rights reguest to Owner')}

    +
    + ); +}; + + +class Permissions extends React.Component { + constructor(props) { + super(props); + this.state = { + itemUsers: props.itemUsers, + newOwnerId: '', + showChangeOwner: false + }; + } + + buildUserOptions() { + let {users, owner} = this.props; + return users.filter(user => user.userId !== owner.userId).map(item => {return {label: item.fullName, value: item.userId};}); + } + + render() { + let {onCancel, owner} = this.props; + let {newOwnerId} = this.state; + return ( +
    + this.onsaveItemUsers()} + onReset={() => onCancel() } + labledButtons={true}> +
    {i18n('Owner')}
    +
    + {owner.fullName} + this.setState({showChangeOwner: !this.state.showChangeOwner})}>{i18n('Change Owner')} +
    + {this.state.showChangeOwner &&
    +
    + {i18n('Change Owner')} + {i18n(changeOwnerMessage)} }> + + +
    + item.userId)} + className='options-input contributors-select' + clearable={false} + onMultiSelectChanged={(value) => {this.onChangeItemUsers({itemUsers: value});}} + options={this.buildUserOptions()} + multi/> + +
    + ); + } + + onChangeItemUsers({itemUsers}) { + this.setState({ + itemUsers: itemUsers.map(contributor => { + let contributorFromProps = this.props.itemUsers.find(user => user.userId === contributor.userId); + return { + userId: contributor.value, + fullName: contributor.label, + permission: contributorFromProps ? contributorFromProps.permission : permissionTypes.CONTRIBUTOR + }; + }) + }); + } + + onsaveItemUsers() { + let {itemUsers: newUsers, newOwnerId} = this.state; + let {itemUsers: oldUsers, onSubmit, itemId, users} = this.props; + let addedUsersIds = newUsers.filter(newUser => !oldUsers.map(oldUser => oldUser.userId).includes(newUser.userId)) + .map(user => user.userId); + let removedUsersIds = oldUsers.filter(oldUser => !newUsers.map(newUser => newUser.userId).includes(oldUser.userId)) + .map(user => user.userId); + onSubmit({itemId, addedUsersIds, removedUsersIds, allUsers: users, newOwnerId}); + } +} + +export default Permissions; diff --git a/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsReducer.js b/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsReducer.js new file mode 100644 index 0000000000..b4ab78964d --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/permissions/PermissionsReducer.js @@ -0,0 +1,28 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import {actionTypes} from './PermissionsConstants.js'; + +export default (state = {}, action) => { + switch (action.type) { + case actionTypes.ITEM_USERS_LOADED: + return { + owner: action.owner, + contributors: action.contributors + }; + default: + return state; + } +}; \ No newline at end of file diff --git a/openecomp-ui/src/sdc-app/onboarding/revisions/Revisions.js b/openecomp-ui/src/sdc-app/onboarding/revisions/Revisions.js new file mode 100644 index 0000000000..73ee5dea21 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/revisions/Revisions.js @@ -0,0 +1,37 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import {connect} from 'react-redux'; +import RevisionsView from './RevisionsView.jsx'; +import RevisionsActionHelper from './RevisionsActionHelper.js'; + +export const mapStateToProps = ({revisions, users}) => { + return { + revisions: revisions, + users: users.usersList + }; +}; + +export const mapActionsToProps = (dispatch, {itemId, version, itemType}) => { + return { + onCancel: () => RevisionsActionHelper.closeRevisionsView(dispatch), + onRevert: (revisionId) => { + RevisionsActionHelper.revertToRevision(dispatch, {itemId, version, revisionId, itemType}); + } + }; +}; + +export default connect(mapStateToProps, mapActionsToProps, null, {withRef: true})(RevisionsView); diff --git a/openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsActionHelper.js new file mode 100644 index 0000000000..4fd9082b5b --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsActionHelper.js @@ -0,0 +1,100 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import i18n from 'nfvo-utils/i18n/i18n.js'; +import RestAPIUtil from 'nfvo-utils/RestAPIUtil.js'; +import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; +import {actionsEnum as vcActionsEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; + +import Configuration from 'sdc-app/config/Configuration.js'; +import {modalContentMapper} from 'sdc-app/common/modal/ModalContentMapper.js'; +import ScreensHelper from 'sdc-app/common/helpers/ScreensHelper.js'; +import {enums, screenTypes} from 'sdc-app/onboarding/OnboardingConstants.js'; + +import {actionTypes} from './RevisionsConstants.js'; + +function baseUrl(itemId, version) { + const restPrefix = Configuration.get('restPrefix'); + return `${restPrefix}/v1.0/items/${itemId}/versions/${version.id}`; +} + +function fetchRevisions(itemId, version){ + let fetchUrl = `${baseUrl(itemId, version)}/revisions`; + return RestAPIUtil.fetch(fetchUrl); +} + +function revertToRevision(itemId, version, revisionId) { + let putUrl = `${baseUrl(itemId, version)}/actions`; + let requestBody = { + action: vcActionsEnum.REVERT, + revisionRequest: { + revisionId: revisionId + } + }; + return RestAPIUtil.put(putUrl, requestBody); +} + +const RevisionaActionHelper = { + openRevisionsView(dispatch, {itemId, version, itemType}) { + this.fetchRevisions(dispatch, {itemId, version}).then(() => { + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_SHOW, + data: { + modalComponentName: modalContentMapper.REVISIONS_LIST, + modalClassName: 'manage-revisions-modal', + title: i18n('Revert'), + modalComponentProps: { + itemId: itemId, + version: version, + itemType + } + } + }); + }); + }, + + closeRevisionsView(dispatch) { + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_CLOSE + }); + }, + + + fetchRevisions(dispatch, {itemId, version}) { + return fetchRevisions(itemId, version).then((response) => { + dispatch({ + type: actionTypes.ITEM_REVISIONS_LOADED, + response: response + }); + }); + }, + + revertToRevision(dispatch, {itemId, version, revisionId, itemType}) { + return revertToRevision(itemId, version, revisionId).then(() => { + this.closeRevisionsView(dispatch); + if (itemType === screenTypes.LICENSE_MODEL) { + ScreensHelper.loadScreen(dispatch, {screen: enums.SCREEN.LICENSE_MODEL_OVERVIEW, screenType: screenTypes.LICENSE_MODEL, + props: {licenseModelId: itemId, version}}); + } else { + ScreensHelper.loadScreen(dispatch, {screen: enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId: itemId, version}}); + } + }); + + } +}; + +export default RevisionaActionHelper; diff --git a/openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsConstants.js b/openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsConstants.js new file mode 100644 index 0000000000..28a9fa0ff5 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsConstants.js @@ -0,0 +1,20 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import keyMirror from 'nfvo-utils/KeyMirror.js'; + +export const actionTypes = keyMirror({ + ITEM_REVISIONS_LOADED: null +}); diff --git a/openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsReducer.js b/openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsReducer.js new file mode 100644 index 0000000000..778350b93f --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsReducer.js @@ -0,0 +1,25 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import {actionTypes} from './RevisionsConstants.js'; + +export default (state = [], action) => { + switch (action.type) { + case actionTypes.ITEM_REVISIONS_LOADED: + return action.response.results; + default: + return state; + } +}; \ No newline at end of file diff --git a/openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsView.jsx b/openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsView.jsx new file mode 100644 index 0000000000..d6ef604a22 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/revisions/RevisionsView.jsx @@ -0,0 +1,87 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 + * revisions and limitations under the License. + */ +import React from 'react'; +import Form from 'nfvo-components/input/validation/Form.jsx'; +import i18n from 'nfvo-utils/i18n/i18n.js'; +import ShowMore from 'react-show-more'; +import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; + +import ListEditorView from 'nfvo-components/listEditor/ListEditorView.jsx'; +import ListEditorItemView from 'nfvo-components/listEditor/ListEditorItemView.jsx'; +import ListEditorItemViewField from 'nfvo-components/listEditor/ListEditorItemViewField.jsx'; + + +class RevisionsView extends React.Component { + constructor(props) { + super(props); + this.state = { + revertId : null + }; + } + + render() { + let {onCancel, onRevert, revisions, users} = this.props; + return ( +
    +
    onRevert(this.state.revertId)} + onReset={() => onCancel() } + submitButtonText={i18n('Revert')} + labledButtons={true}> + + {revisions.map((revision) => { + return ( +
    + this.setState({revertId : revision.id})}> + +
    +
    + userObject.userId === revision.user).fullName} labelPosition='right'/> +
    +
    + {i18n.dateNormal(revision.time, { + year: 'numeric', month: 'numeric', day: 'numeric' + })} + {i18n.dateNormal(revision.time, { + hour: 'numeric', minute: 'numeric', + hour12: true + })} +
    +
    + {revision.message && + {revision.message} + }
    +
    +
    +
    +
    + + ); + })} +
    +
    +
    + ); + } + +} + +export default RevisionsView; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProduct.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProduct.js index ae3d3932ed..cdaf189fc0 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProduct.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProduct.js @@ -16,64 +16,69 @@ import {connect} from 'react-redux'; import i18n from 'nfvo-utils/i18n/i18n.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; +import ScreensHelper from 'sdc-app/common/helpers/ScreensHelper.js'; import TabulatedEditor from 'src/nfvo-components/editor/TabulatedEditor.jsx'; -import {enums} from 'sdc-app/onboarding/OnboardingConstants.js'; -import OnboardingActionHelper from 'sdc-app/onboarding/OnboardingActionHelper.js'; +import {enums, screenTypes} from 'sdc-app/onboarding/OnboardingConstants.js'; -import {navigationItems, mapScreenToNavigationItem, onboardingMethod as onboardingMethodTypes, onboardingOriginTypes} from './SoftwareProductConstants.js'; +import {onboardingMethod as onboardingMethodTypes, onboardingOriginTypes} from './SoftwareProductConstants.js'; import SoftwareProductActionHelper from './SoftwareProductActionHelper.js'; import SoftwareProductComponentsActionHelper from './components/SoftwareProductComponentsActionHelper.js'; -import SoftwareProductDependenciesActionHelper from './dependencies/SoftwareProductDependenciesActionHelper.js'; - +import PermissionsActionHelper from './../permissions/PermissionsActionHelper.js'; +import RevisionsActionHelper from './../revisions/RevisionsActionHelper.js'; import HeatSetupActionHelper from './attachments/setup/HeatSetupActionHelper.js'; import { actionsEnum as versionControllerActions } from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; +import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; +import {modalContentMapper} from 'sdc-app/common/modal/ModalContentMapper.js'; +import {CommitModalType} from 'nfvo-components/panel/versionController/components/CommitCommentModal.jsx'; +import {onboardingMethod as onboardingMethodType} from 'sdc-app/onboarding/softwareProduct/SoftwareProductConstants.js'; +import {SyncStates} from 'sdc-app/common/merge/MergeEditorConstants.js'; +import {catalogItemStatuses} from 'sdc-app/onboarding/onboard/onboardingCatalog/OnboardingCatalogConstants.js'; function getActiveNavigationId(screen, componentId) { - let activeItemId = componentId ? mapScreenToNavigationItem[screen] + '|' + componentId : mapScreenToNavigationItem[screen]; + let activeItemId = componentId ? screen + '|' + componentId : screen; return activeItemId; } const buildComponentNavigationBarGroups = ({componentId, meta}) => { const groups = ([ { - id: navigationItems.GENERAL + '|' + componentId, + id: enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_GENERAL + '|' + componentId, name: i18n('General'), disabled: false, meta }, { - id: navigationItems.COMPUTE + '|' + componentId, + id: enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_COMPUTE + '|' + componentId, name: i18n('Compute'), disabled: false, meta }, { - id: navigationItems.LOAD_BALANCING + '|' + componentId, + id: enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_LOAD_BALANCING + '|' + componentId, name: i18n('High Availability & Load Balancing'), disabled: false, meta }, { - id: navigationItems.NETWORKS + '|' + componentId, + id: enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_NETWORK + '|' + componentId, name: i18n('Networks'), disabled: false, meta }, { - id: navigationItems.STORAGE + '|' + componentId, + id: enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_STORAGE + '|' + componentId, name: i18n('Storage'), disabled: false, meta }, { - id: navigationItems.IMAGES + '|' + componentId, + id: enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_IMAGES + '|' + componentId, name: i18n('Images'), disabled: false, meta }, { - id: navigationItems.PROCESS_DETAILS + '|' + componentId, + id: enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_PROCESSES + '|' + componentId, name: i18n('Process Details'), disabled: false, meta }, { - id: navigationItems.MONITORING + '|' + componentId, + id: enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_MONITORING + '|' + componentId, name: i18n('Monitoring'), disabled: false, meta @@ -85,67 +90,67 @@ const buildComponentNavigationBarGroups = ({componentId, meta}) => { const buildNavigationBarProps = ({softwareProduct, meta, screen, componentId, componentsList, mapOfExpandedIds}) => { const {softwareProductEditor: {data: currentSoftwareProduct = {}}} = softwareProduct; - const {id, name, onboardingMethod, onboardingOrigin} = currentSoftwareProduct; + const {id, name, onboardingMethod, candidateOnboardingOrigin} = currentSoftwareProduct; const groups = [{ id: id, name: name, items: [ { - id: navigationItems.VENDOR_SOFTWARE_PRODUCT, + id: enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, name: i18n('Overview'), disabled: false, meta }, { - id: navigationItems.GENERAL, + id: enums.SCREEN.SOFTWARE_PRODUCT_DETAILS, name: i18n('General'), disabled: false, meta }, { - id: navigationItems.DEPLOYMENT_FLAVORS, + id: enums.SCREEN.SOFTWARE_PRODUCT_DEPLOYMENT, name: i18n('Deployment Flavors'), disabled: false, hidden: onboardingMethod !== onboardingMethodTypes.MANUAL, meta }, { - id: navigationItems.PROCESS_DETAILS, + id: enums.SCREEN.SOFTWARE_PRODUCT_PROCESSES, name: i18n('Process Details'), disabled: false, meta }, { - id: navigationItems.NETWORKS, + id: enums.SCREEN.SOFTWARE_PRODUCT_NETWORKS, name: i18n('Networks'), disabled: false, meta }, { - id: navigationItems.ATTACHMENTS, + id: enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS, name: i18n('Attachments'), disabled: false, - hidden: onboardingOrigin === onboardingOriginTypes.NONE, + hidden: candidateOnboardingOrigin === onboardingOriginTypes.NONE, meta }, { - id: navigationItems.ACTIVITY_LOG, + id: enums.SCREEN.SOFTWARE_PRODUCT_ACTIVITY_LOG, name: i18n('Activity Log'), disabled: false, meta }, { - id: navigationItems.DEPENDENCIES, + id: enums.SCREEN.SOFTWARE_PRODUCT_DEPENDENCIES, name: i18n('Component Dependencies'), hidden: componentsList.length <= 1, disabled: false, meta }, { - id: navigationItems.COMPONENTS, + id: enums.SCREEN.SOFTWARE_PRODUCT_COMPONENTS, name: i18n('Components'), hidden: componentsList.length <= 0, meta, - expanded: mapOfExpandedIds[navigationItems.COMPONENTS] === true && screen !== enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, + expanded: mapOfExpandedIds[enums.SCREEN.SOFTWARE_PRODUCT_COMPONENTS] === true && screen !== enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, items: [ ...componentsList.map(({id, displayName}) => ({ - id: navigationItems.COMPONENTS + '|' + id, + id: enums.SCREEN.SOFTWARE_PRODUCT_COMPONENTS + '|' + id, name: displayName, meta, - expanded: mapOfExpandedIds[navigationItems.COMPONENTS + '|' + id] === true && screen !== enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, + expanded: mapOfExpandedIds[enums.SCREEN.SOFTWARE_PRODUCT_COMPONENTS + '|' + id] === true && screen !== enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, items: buildComponentNavigationBarGroups({componentId: id, meta}) })) ] @@ -158,24 +163,28 @@ const buildNavigationBarProps = ({softwareProduct, meta, screen, componentId, co }; }; -const buildVersionControllerProps = (softwareProduct) => { - const {softwareProductEditor} = softwareProduct; - const {data: currentSoftwareProduct = {}, isValidityData = true} = softwareProductEditor; - - const {version, viewableVersions, status: currentStatus, lockingUser} = currentSoftwareProduct; - const {status, isCheckedOut} = VersionControllerUtils.getCheckOutStatusKindByUserID(currentStatus, lockingUser); +const buildVersionControllerProps = ({softwareProduct, versions, currentVersion, permissions, userInfo, usersList, itemPermission, isReadOnlyMode}) => { + const {softwareProductEditor = {data: {}}} = softwareProduct; + const {isValidityData = true, data: {name, onboardingMethod}} = softwareProductEditor; return { - status, isCheckedOut, version, viewableVersions, - isFormDataValid: isValidityData + version: currentVersion, + viewableVersions: versions, + isFormDataValid: isValidityData, + permissions, + itemName: name, + itemPermission, + isReadOnlyMode, + userInfo, + usersList, + isManual: onboardingMethod === onboardingMethodType.MANUAL }; }; -function buildMeta({softwareProduct, componentId, softwareProductDependencies}) { +function buildMeta({softwareProduct, componentId, softwareProductDependencies, isReadOnlyMode}) { const {softwareProductEditor, softwareProductComponents, softwareProductQuestionnaire, softwareProductAttachments} = softwareProduct; const {data: currentSoftwareProduct = {}} = softwareProductEditor; - const {version, onboardingOrigin} = currentSoftwareProduct; - const isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); + const {version, onboardingOrigin, candidateOnboardingOrigin} = currentSoftwareProduct; const {qdata} = softwareProductQuestionnaire; const {heatSetup, heatSetupCache} = softwareProductAttachments; let currentComponentMeta = {}; @@ -183,35 +192,52 @@ function buildMeta({softwareProduct, componentId, softwareProductDependencies}) const {componentEditor: {data: componentData = {} , qdata: componentQdata}} = softwareProductComponents; currentComponentMeta = {componentData, componentQdata}; } - const meta = {softwareProduct: currentSoftwareProduct, qdata, version, onboardingOrigin, heatSetup, heatSetupCache, isReadOnlyMode, currentComponentMeta, softwareProductDependencies}; + const meta = {softwareProduct: currentSoftwareProduct, qdata, version, onboardingOrigin, candidateOnboardingOrigin, heatSetup, heatSetupCache, + isReadOnlyMode, currentComponentMeta, softwareProductDependencies}; return meta; } -const mapStateToProps = ({softwareProduct}, {currentScreen: {screen, props: {componentId}}}) => { +const mapStateToProps = ( + { + softwareProduct, + users: {usersList, userInfo}, + versionsPage: {versionsList: {versions}, permissions} + }, + { + currentScreen: {screen, itemPermission, props: {version: currentVersion, componentId, isReadOnlyMode}} + } +) => { const {softwareProductEditor, softwareProductComponents, softwareProductDependencies} = softwareProduct; const {mapOfExpandedIds = []} = softwareProductEditor; const {componentsList = []} = softwareProductComponents; - const meta = buildMeta({softwareProduct, componentId, softwareProductDependencies}); + const meta = buildMeta({softwareProduct, componentId, softwareProductDependencies, isReadOnlyMode}); return { - versionControllerProps: buildVersionControllerProps(softwareProduct), + versionControllerProps: buildVersionControllerProps({ + softwareProduct, + versions, + currentVersion, + userInfo, + usersList, + permissions, + itemPermission: {...itemPermission, isDirty: true}, + isReadOnlyMode + }), navigationBarProps: buildNavigationBarProps({softwareProduct, meta, screen, componentId, componentsList, mapOfExpandedIds}), meta }; }; -const autoSaveBeforeNavigate = ({dispatch, screen, softwareProductId, componentId, - meta: {isReadOnlyMode, softwareProduct, version, qdata, softwareProductDependencies, +const autoSaveBeforeNavigate = ({dispatch, screen, softwareProductId, version, componentId, + meta: {isReadOnlyMode, softwareProduct, qdata, currentComponentMeta: {componentData, componentQdata}}}) => { let promise; if (isReadOnlyMode) { promise = Promise.resolve(); } else { switch(screen) { - case enums.SCREEN.SOFTWARE_PRODUCT_DEPENDENCIES: - promise = SoftwareProductDependenciesActionHelper.saveDependencies(dispatch,{softwareProductId, version, dependenciesList: softwareProductDependencies}); case enums.SCREEN.SOFTWARE_PRODUCT_DETAILS: - promise = SoftwareProductActionHelper.updateSoftwareProduct(dispatch, {softwareProduct, qdata}); + promise = SoftwareProductActionHelper.updateSoftwareProduct(dispatch, {softwareProduct, version, qdata}); break; case enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_GENERAL: promise = SoftwareProductComponentsActionHelper.updateSoftwareProductComponent(dispatch, @@ -233,96 +259,65 @@ const autoSaveBeforeNavigate = ({dispatch, screen, softwareProductId, componentI }; -const onComponentNavigate = (dispatch, {id, softwareProductId, version, currentComponentId}) => { - const [nextScreen, nextComponentId] = id.split('|'); - switch(nextScreen) { - case navigationItems.COMPONENTS: - if(nextComponentId === currentComponentId) { - OnboardingActionHelper.navigateToSoftwareProductComponents(dispatch, {softwareProductId}); - } else { - OnboardingActionHelper.navigateToSoftwareProductComponentGeneral(dispatch, {softwareProductId, componentId: nextComponentId, version}); - } - break; - case navigationItems.GENERAL: - OnboardingActionHelper.navigateToSoftwareProductComponentGeneral(dispatch, {softwareProductId, componentId: nextComponentId, version}); - break; - case navigationItems.COMPUTE: - OnboardingActionHelper.navigateToComponentCompute(dispatch, {softwareProductId, componentId: nextComponentId, version}); - break; - case navigationItems.LOAD_BALANCING: - OnboardingActionHelper.navigateToComponentLoadBalancing(dispatch, {softwareProductId, componentId: nextComponentId, version}); - break; - case navigationItems.NETWORKS: - OnboardingActionHelper.navigateToComponentNetwork(dispatch, {softwareProductId, componentId: nextComponentId, version}); - break; - case navigationItems.IMAGES: - OnboardingActionHelper.navigateToComponentImages(dispatch, {softwareProductId, componentId: nextComponentId, version}); - break; - case navigationItems.STORAGE: - OnboardingActionHelper.navigateToComponentStorage(dispatch, {softwareProductId, componentId: nextComponentId, version}); - break; - case navigationItems.PROCESS_DETAILS: - OnboardingActionHelper.navigateToSoftwareProductComponentProcesses(dispatch, {softwareProductId, componentId: nextComponentId, version}); - break; - case navigationItems.MONITORING: - OnboardingActionHelper.navigateToSoftwareProductComponentMonitoring(dispatch, {softwareProductId, componentId: nextComponentId, version}); - break; - } -}; - -const mapActionsToProps = (dispatch, {currentScreen: {screen, props: {softwareProductId, componentId: currentComponentId}}}) => { +const mapActionsToProps = (dispatch, {currentScreen: {screen, props: {softwareProductId, licenseModelId, version, componentId: currentComponentId}}}) => { const props = { - onVersionSwitching: (version, meta) => { - const screenToLoad = !currentComponentId ? screen : enums.SCREEN.SOFTWARE_PRODUCT_COMPONENTS; - SoftwareProductActionHelper.fetchSoftwareProduct(dispatch, {softwareProductId, version}); - props.onNavigate({id: getActiveNavigationId(screenToLoad), meta, version}); + onVersionSwitching: (versionToSwitch, meta) => { + ScreensHelper.loadScreen(dispatch, {screen: enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId: meta.softwareProduct.id, version: versionToSwitch}}); + }, + onOpenPermissions: ({users}) => { + return PermissionsActionHelper.fetchItemUsers(dispatch, {itemId: softwareProductId, allUsers: users}); + }, + onOpenRevisionsModal: () => { + return RevisionsActionHelper.openRevisionsView(dispatch, {itemId: softwareProductId, version: version, itemType: screenTypes.SOFTWARE_PRODUCT}); + }, + onOpenCommentCommitModal: ({onCommit, title}) => dispatch({ + type: modalActionTypes.GLOBAL_MODAL_SHOW, + data: { + modalComponentName: modalContentMapper.COMMIT_COMMENT, + modalComponentProps: { + onCommit, + type: CommitModalType.COMMIT + }, + title + } + }), + onMoreVersionsClick: ({itemName, users}) => { + ScreensHelper.loadScreen(dispatch, {screen: enums.SCREEN.SOFTWARE_PRODUCT_VERSIONS_PAGE, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, softwareProduct: {name: itemName, vendorId: licenseModelId}, usersList: users}}); + }, onToggle: (groups, itemIdToExpand) => groups.map(({items}) => SoftwareProductActionHelper.toggleNavigationItems(dispatch, {items, itemIdToExpand})), - onNavigate: ({id, meta, version}) => { - let {onboardingOrigin, heatSetup, heatSetupCache} = meta; + onNavigate: ({id, meta, newVersion}) => { + let navigationVersion = newVersion || version; + let {onboardingOrigin, candidateOnboardingOrigin, heatSetup, heatSetupCache} = meta; let heatSetupPopupPromise = screen === enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS ? HeatSetupActionHelper.heatSetupLeaveConfirmation(dispatch, {softwareProductId, heatSetup, heatSetupCache}) : Promise.resolve(); - let preNavigate = meta ? autoSaveBeforeNavigate({dispatch, screen, meta, softwareProductId, componentId: currentComponentId}) : Promise.resolve(); + let preNavigate = meta ? autoSaveBeforeNavigate({dispatch, screen, meta, version, softwareProductId, componentId: currentComponentId}) : Promise.resolve(); version = version || (meta ? meta.version : undefined); Promise.all([preNavigate, heatSetupPopupPromise]).then(() => { - switch(id) { - case navigationItems.VENDOR_SOFTWARE_PRODUCT: - OnboardingActionHelper.navigateToSoftwareProductLandingPage(dispatch, {softwareProductId, version}); - break; - case navigationItems.GENERAL: - OnboardingActionHelper.navigateToSoftwareProductDetails(dispatch, {softwareProductId, version}); - break; - case navigationItems.DEPLOYMENT_FLAVORS: - OnboardingActionHelper.navigateToSoftwareProductDeployment(dispatch, {softwareProductId, version}); - break; - case navigationItems.PROCESS_DETAILS: - OnboardingActionHelper.navigateToSoftwareProductProcesses(dispatch, {softwareProductId, version}); - break; - case navigationItems.NETWORKS: - OnboardingActionHelper.navigateToSoftwareProductNetworks(dispatch, {softwareProductId, version}); - break; - case navigationItems.DEPENDENCIES: - OnboardingActionHelper.navigateToSoftwareProductDependencies(dispatch, {softwareProductId, version}); - break; - case navigationItems.ATTACHMENTS: - if(onboardingOrigin === onboardingOriginTypes.ZIP) { - OnboardingActionHelper.navigateToSoftwareProductAttachmentsSetupTab(dispatch, {softwareProductId, version}); + let [nextScreen, nextComponentId] = id.split('|'); + if(nextScreen === enums.SCREEN.SOFTWARE_PRODUCT_COMPONENTS && nextComponentId && nextComponentId === currentComponentId) { + ScreensHelper.loadScreen(dispatch, { + screen: nextScreen, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, version: navigationVersion} + }); + } + else { + if(nextScreen === enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS) { + if(onboardingOrigin === onboardingOriginTypes.ZIP || candidateOnboardingOrigin === onboardingOriginTypes.ZIP) { + nextScreen = enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS_SETUP; } else if(onboardingOrigin === onboardingOriginTypes.CSAR) { - OnboardingActionHelper.navigateToSoftwareProductAttachmentsValidationTab(dispatch, {softwareProductId, version}); + nextScreen = enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS_VALIDATION; } - break; - case navigationItems.COMPONENTS: - OnboardingActionHelper.navigateToSoftwareProductComponents(dispatch, {softwareProductId, version}); - break; - case navigationItems.ACTIVITY_LOG: - OnboardingActionHelper.navigateToSoftwareProductActivityLog(dispatch, {softwareProductId, version}); - break; - default: - onComponentNavigate(dispatch, {id, softwareProductId, version, screen, currentComponentId}); - break; + } + ScreensHelper.loadScreen(dispatch, { + screen: nextScreen, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, version: navigationVersion, componentId: nextComponentId} + }); } }).catch((e) => {console.error(e);}); } @@ -342,25 +337,33 @@ const mapActionsToProps = (dispatch, {currentScreen: {screen, props: {softwarePr props.onSave = () => Promise.resolve(); break; default: - props.onSave = ({softwareProduct, qdata}) => SoftwareProductActionHelper.updateSoftwareProduct(dispatch, {softwareProduct, qdata}); + props.onSave = ({softwareProduct, qdata}) => SoftwareProductActionHelper.updateSoftwareProduct(dispatch, {softwareProduct, qdata, version}); break; } - props.onVersionControllerAction = (action, version, meta) => { + props.onVersionControllerAction = (action, version, comment, meta) => { let {heatSetup, heatSetupCache} = meta; - let heatSetupPopupPromise = screen === enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS && action === versionControllerActions.CHECK_IN ? + let autoSavePromise = meta ? autoSaveBeforeNavigate({dispatch, screen, meta, version, softwareProductId, componentId: currentComponentId}) : Promise.resolve(); + let heatSetupPopupPromise = screen === enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS && action === versionControllerActions.COMMIT ? HeatSetupActionHelper.heatSetupLeaveConfirmation(dispatch, {softwareProductId, heatSetup, heatSetupCache}) : Promise.resolve(); - heatSetupPopupPromise.then(() => { - return SoftwareProductActionHelper.performVCAction(dispatch, {softwareProductId, action, version}).then(({newVersion}) => { - //props.onNavigate({id: getActiveNavigationId(screen, currentComponentId), version}); - if(screen === enums.SCREEN.SOFTWARE_PRODUCT_ACTIVITY_LOG) { - OnboardingActionHelper.navigateToSoftwareProductActivityLog(dispatch, {softwareProductId, version: newVersion}); + Promise.all([autoSavePromise, heatSetupPopupPromise]).then(() => { + return SoftwareProductActionHelper.performVCAction(dispatch, {softwareProductId, action, version, comment, meta}).then(updatedVersion => { + const inMerge = updatedVersion && updatedVersion.state && updatedVersion.state.synchronizationState === SyncStates.MERGE; + if((action === versionControllerActions.SYNC && !inMerge) || + ((action === versionControllerActions.COMMIT || action === versionControllerActions.SYNC) && updatedVersion.status === catalogItemStatuses.CERTIFIED)) { + ScreensHelper.loadLandingScreen(dispatch, {previousScreenName: screen, props: {softwareProductId, version: updatedVersion}}); + + } else { + ScreensHelper.loadScreen(dispatch, {screen, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, version: updatedVersion, componentId: currentComponentId}}); } }); }).catch((e) => {console.error(e);}); }; + + props.onManagePermissions = () => PermissionsActionHelper.openPermissonsManager(dispatch, {itemId: softwareProductId, askForRights: false}); return props; }; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductActionHelper.js index db7afd27d9..735c6d7f8b 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductActionHelper.js @@ -31,8 +31,26 @@ import {actionTypes as componentActionTypes} from './components/SoftwareProductC import ValidationHelper from 'sdc-app/common/helpers/ValidationHelper.js'; import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; import {modalContentMapper} from 'sdc-app/common/modal/ModalContentMapper.js'; -import {statusEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; +import ItemsHelper from 'sdc-app/common/helpers/ItemsHelper.js'; +import ScreensHelper from 'sdc-app/common/helpers/ScreensHelper.js'; +import {enums, screenTypes} from 'sdc-app/onboarding/OnboardingConstants.js'; +import MergeEditorActionHelper from 'sdc-app/common/merge/MergeEditorActionHelper.js'; +import {CommitModalType} from 'nfvo-components/panel/versionController/components/CommitCommentModal.jsx'; import {actionTypes as commonActionTypes} from 'sdc-app/common/reducers/PlainDataReducerConstants.js'; +import versionPageActionHelper from 'sdc-app/onboarding/versionsPage/VersionsPageActionHelper.js'; +import {itemTypes} from 'sdc-app/onboarding/versionsPage/VersionsPageConstants.js'; +import {catalogItemStatuses} from 'sdc-app/onboarding/onboard/onboardingCatalog/OnboardingCatalogConstants.js'; +import getValue from 'nfvo-utils/getValue.js'; + +function getLicensingData(licensingData = {}) { + const {licenseAgreement, featureGroups} = licensingData; + const newlicenseAgreement = getValue(licenseAgreement); + const newfeatureGroups = getValue(featureGroups); + return newlicenseAgreement ? { + licenseAgreement: newlicenseAgreement, + featureGroups: newfeatureGroups + } : undefined; +}; function baseUrl() { const restPrefix = Configuration.get('restPrefix'); @@ -48,20 +66,17 @@ function uploadFile(vspId, formData, version) { } -function putSoftwareProduct(softwareProduct) { - return RestAPIUtil.put(`${baseUrl()}${softwareProduct.id}/versions/${softwareProduct.version.id}`, { +function putSoftwareProduct({softwareProduct, version}) { + return RestAPIUtil.put(`${baseUrl()}${softwareProduct.id}/versions/${version.id}`, { name: softwareProduct.name, description: softwareProduct.description, category: softwareProduct.category, subCategory: softwareProduct.subCategory, vendorId: softwareProduct.vendorId, vendorName: softwareProduct.vendorName, - licensingVersion: softwareProduct.licensingVersion && softwareProduct.licensingVersion.id ? softwareProduct.licensingVersion : {} , + licensingVersion: softwareProduct.licensingVersion ? softwareProduct.licensingVersion : undefined, icon: softwareProduct.icon, - licensingData: softwareProduct.licensingData, - onboardingMethod: softwareProduct.onboardingMethod, - networkPackageName: softwareProduct.networkPackageName, - onboardingOrigin: softwareProduct.onboardingOrigin + licensingData: getLicensingData(softwareProduct.licensingData) }); } @@ -74,11 +89,11 @@ function putSoftwareProductAction(id, action, version) { } function fetchSoftwareProductList() { - return RestAPIUtil.fetch(baseUrl()); + return RestAPIUtil.fetch(`${baseUrl()}?versionFilter=Draft`); } function fetchFinalizedSoftwareProductList() { - return RestAPIUtil.fetch(`${baseUrl()}?versionFilter=Final`); + return RestAPIUtil.fetch(`${baseUrl()}?versionFilter=Certified`); } function fetchSoftwareProduct(vspId, version) { @@ -138,10 +153,12 @@ function fetchSoftwareProductCategories(dispatch) { } function loadLicensingData(dispatch, {licenseModelId, licensingVersion}) { - return Promise.all([ - LicenseAgreementActionHelper.fetchLicenseAgreementList(dispatch, {licenseModelId, version: licensingVersion}), - FeatureGroupsActionHelper.fetchFeatureGroupsList(dispatch, {licenseModelId, version: licensingVersion}) - ]); + return ItemsHelper.fetchVersion({itemId: licenseModelId, versionId: licensingVersion}).then(() => { + return Promise.all([ + LicenseAgreementActionHelper.fetchLicenseAgreementList(dispatch, {licenseModelId, version: {id: licensingVersion}}), + FeatureGroupsActionHelper.fetchFeatureGroupsList(dispatch, {licenseModelId, version: {id: licensingVersion}}) + ]); + }); } function getExpandedItemsId(items, itemIdToToggle) { @@ -203,15 +220,7 @@ function migrateSoftwareProduct(vspId, version) { return RestAPIUtil.put(`${baseUrl()}${vspId}/versions/${version.id}/heal`); } -function adjustMinorVersion(version, value) { - let ar = version.split('.'); - return ar[0] + '.' + (parseInt(ar[1]) + value); -} -function adjustMajorVersion(version, value) { - let ar = version.split('.'); - return (parseInt(ar[0]) + value) + '.0'; -} const SoftwareProductActionHelper = { @@ -229,7 +238,10 @@ const SoftwareProductActionHelper = { loadSoftwareProductDetailsData(dispatch, {licenseModelId, licensingVersion}) { SoftwareProductActionHelper.loadSoftwareProductAssociatedData(dispatch); - return loadLicensingData(dispatch, {licenseModelId, licensingVersion}); + if (licensingVersion) { + return loadLicensingData(dispatch, {licenseModelId, licensingVersion}); + } + return Promise.resolve(); }, fetchSoftwareProductList(dispatch) { @@ -246,6 +258,14 @@ const SoftwareProductActionHelper = { })); }, + loadLicensingVersionsList(dispatch, {licenseModelId}){ + return ItemsHelper.fetchVersions({itemId: licenseModelId}).then(response => { + dispatch({ + type: actionTypes.LOAD_LICENSING_VERSIONS_LIST, + licensingVersionsList: response.results + }); + }); + }, updateSoftwareProductHeatCandidate(dispatch, {softwareProductId, heatCandidate, version}){ return updateSoftwareProductHeatCandidate(softwareProductId, heatCandidate, version); }, @@ -276,10 +296,16 @@ const SoftwareProductActionHelper = { }); switch(response.onboardingOrigin){ case onboardingOriginTypes.ZIP: - OnboardingActionHelper.navigateToSoftwareProductAttachmentsSetupTab(dispatch, {softwareProductId, version}); + ScreensHelper.loadScreen(dispatch, { + screen: enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS_SETUP, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, version} + }); break; case onboardingOriginTypes.CSAR: - OnboardingActionHelper.navigateToSoftwareProductAttachmentsValidationTab(dispatch, {softwareProductId, version}); + ScreensHelper.loadScreen(dispatch, { + screen: enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS_VALIDATION, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, version} + }); break; } } @@ -292,7 +318,7 @@ const SoftwareProductActionHelper = { type: modalActionTypes.GLOBAL_MODAL_ERROR, data: { title: failedNotificationTitle, - msg: error.message + msg: error.message || (error.responseJSON && error.responseJSON.message) } }); }); @@ -311,9 +337,9 @@ const SoftwareProductActionHelper = { type: actionTypes.softwareProductEditor.UPLOAD_CONFIRMATION }); }, - updateSoftwareProduct(dispatch, {softwareProduct, qdata}) { + updateSoftwareProduct(dispatch, {softwareProduct, version, qdata}) { return Promise.all([ - SoftwareProductActionHelper.updateSoftwareProductData(dispatch, {softwareProduct}).then( + SoftwareProductActionHelper.updateSoftwareProductData(dispatch, {softwareProduct, version}).then( () => dispatch({ type: actionTypes.SOFTWARE_PRODUCT_LIST_EDIT, payload: {softwareProduct} @@ -322,13 +348,13 @@ const SoftwareProductActionHelper = { SoftwareProductActionHelper.updateSoftwareProductQuestionnaire(dispatch, { softwareProductId: softwareProduct.id, qdata, - version: softwareProduct.version + version }) ]); }, - updateSoftwareProductData(dispatch, {softwareProduct}) { - return putSoftwareProduct(softwareProduct); + updateSoftwareProductData(dispatch, {softwareProduct, version}) { + return putSoftwareProduct({softwareProduct, version}); }, updateSoftwareProductQuestionnaire(dispatch, {softwareProductId, qdata, version}) { @@ -350,19 +376,18 @@ const SoftwareProductActionHelper = { }, softwareProductEditorVendorChanged(dispatch, {deltaData, formName}) { - if (deltaData.licensingVersion.id){ - let p = Promise.all([ - LicenseAgreementActionHelper.fetchLicenseAgreementList(dispatch, { - licenseModelId: deltaData.vendorId, - version: {id: deltaData.licensingVersion.id} - }), - FeatureGroupsActionHelper.fetchFeatureGroupsList(dispatch, { - licenseModelId: deltaData.vendorId, - version: {id: deltaData.licensingVersion.id} - }) - ]); + if (deltaData.licensingVersion){ + return loadLicensingData(dispatch, {licenseModelId: deltaData.vendorId, licensingVersion: deltaData.licensingVersion}).then(() => { + ValidationHelper.dataChanged(dispatch, {deltaData, formName}); + return Promise.resolve(); + }); + } else if (deltaData.vendorId) { ValidationHelper.dataChanged(dispatch, {deltaData, formName}); - return p; + return SoftwareProductActionHelper.loadLicensingVersionsList(dispatch, { + licenseModelId: deltaData.vendorId + }).then( () => + OnboardingActionHelper.forceBreadCrumbsUpdate(dispatch) + ); } else { ValidationHelper.dataChanged(dispatch, {deltaData, formName}); @@ -386,13 +411,6 @@ const SoftwareProductActionHelper = { }); }, - addSoftwareProduct(dispatch, {softwareProduct}) { - dispatch({ - type: actionTypes.ADD_SOFTWARE_PRODUCT, - softwareProduct - }); - }, - fetchSoftwareProduct(dispatch, {softwareProductId, version}) { return Promise.all([ fetchSoftwareProduct(softwareProductId, version).then(response => { @@ -409,10 +427,33 @@ const SoftwareProductActionHelper = { ]); }, - performVCAction(dispatch, {softwareProductId, action, version}) { - if (action === VersionControllerActionsEnum.SUBMIT) { - return putSoftwareProductAction(softwareProductId, action, version).then(() => { - return putSoftwareProductAction(softwareProductId, VersionControllerActionsEnum.CREATE_PACKAGE, version).then(() => { + manageSubmitAction(dispatch, {softwareProductId, version, isDirty}) { + if (isDirty) { + const onCommit = comment => { + return this.performVCAction(dispatch, {softwareProductId, action: VersionControllerActionsEnum.COMMIT, version, comment}).then(() => { + return this.performSubmitAction(dispatch, {softwareProductId, version}); + }); + }; + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_SHOW, + data: { + modalComponentName: modalContentMapper.COMMIT_COMMENT, + modalComponentProps: { + onCommit, + type: CommitModalType.COMMIT_SUBMIT + }, + title: i18n('Commit & Submit') + } + }); + return Promise.resolve(version); + } + return this.performSubmitAction(dispatch, {softwareProductId, version}); + }, + + performSubmitAction(dispatch, {softwareProductId, version}) { + return putSoftwareProductAction(softwareProductId, VersionControllerActionsEnum.SUBMIT, version).then(() => { + return putSoftwareProductAction(softwareProductId, VersionControllerActionsEnum.CREATE_PACKAGE, version).then(() => { + return ItemsHelper.checkItemStatus(dispatch, {itemId: softwareProductId, versionId: version.id}).then(updatedVersion => { dispatch({ type: modalActionTypes.GLOBAL_MODAL_SUCCESS, data: { @@ -422,12 +463,13 @@ const SoftwareProductActionHelper = { timeout: 2000 } }); - const newVersionId = adjustMajorVersion(version.label, 1); - OnboardingActionHelper.updateCurrentScreenVersion(dispatch, {label: newVersionId, id: newVersionId}); - SoftwareProductActionHelper.fetchSoftwareProduct(dispatch,{softwareProductId, version: {id: newVersionId}}); - return Promise.resolve({newVersion: {id: newVersionId}}); + versionPageActionHelper.fetchVersions(dispatch, {itemType: itemTypes.SOFTWARE_PRODUCT, itemId: softwareProductId}); + return Promise.resolve(updatedVersion); }); - }, error => dispatch({ + }); + }, error => + { + dispatch({ type: modalActionTypes.GLOBAL_MODAL_ERROR, data: { modalComponentName: modalContentMapper.SUMBIT_ERROR_RESPONSE, @@ -435,36 +477,57 @@ const SoftwareProductActionHelper = { modalComponentProps: { validationResponse: error.responseJSON }, - cancelButtonText: i18n('Ok') + cancelButtonText: i18n('OK') } - })); - } - else { - return putSoftwareProductAction(softwareProductId, action, version).then(() => { - let newVersionId = version.id; - /* - TODO Temorary switch to change version label - */ - switch(action) { - case VersionControllerActionsEnum.CHECK_OUT: - newVersionId = adjustMinorVersion(version.label, 1); - break; - case VersionControllerActionsEnum.UNDO_CHECK_OUT: - newVersionId = adjustMinorVersion(version.label, -1); - break; - } - OnboardingActionHelper.updateCurrentScreenVersion(dispatch, {label: newVersionId, id: newVersionId}); - SoftwareProductActionHelper.fetchSoftwareProduct(dispatch,{softwareProductId, version:{id: newVersionId}}); - return Promise.resolve({newVersion: {id: newVersionId}}); }); - } + return Promise.reject(error.responseJSON); + }); }, - switchVersion(dispatch, {softwareProductId, licenseModelId, version}) { - OnboardingActionHelper.navigateToSoftwareProductLandingPage(dispatch, { - softwareProductId, - licenseModelId, - version + performVCAction(dispatch, {softwareProductId, action, version, comment}) { + return MergeEditorActionHelper.analyzeSyncResult(dispatch, {itemId: softwareProductId, version}).then(({inMerge, isDirty, updatedVersion}) => { + if (updatedVersion.status === catalogItemStatuses.CERTIFIED && + (action === VersionControllerActionsEnum.COMMIT || action === VersionControllerActionsEnum.SYNC)) { + versionPageActionHelper.fetchVersions(dispatch, {itemType: itemTypes.SOFTWARE_PRODUCT, itemId: softwareProductId}); + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_WARNING, + data: { + title: i18n('Commit error'), + msg: i18n('Item version already Certified'), + cancelButtonText: i18n('Cancel') + } + }); + return Promise.resolve(updatedVersion); + } + if (!inMerge) { + if (action === VersionControllerActionsEnum.SUBMIT) { + return this.manageSubmitAction(dispatch, {softwareProductId, version, isDirty}); + } + else { + let isCallActionValid = action !== VersionControllerActionsEnum.COMMIT || isDirty; + if(isCallActionValid) { + return ItemsHelper.performVCAction({itemId: softwareProductId, action, version, comment}).then(() => { + versionPageActionHelper.fetchVersions(dispatch, {itemType: itemTypes.LICENSE_MODEL, itemId: softwareProductId}); + if (action === VersionControllerActionsEnum.SYNC) { + return MergeEditorActionHelper.analyzeSyncResult(dispatch, {itemId: softwareProductId, version}).then(({updatedVersion}) => { + return Promise.resolve(updatedVersion); + }); + } else { + return ItemsHelper.checkItemStatus(dispatch, {itemId: softwareProductId, versionId: version.id}); + } + }); + } + else { + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_ERROR, + data: { + title: i18n('Commit Failed'), + msg: i18n('There is nothing to commit') + } + }); + } + } + } }); }, @@ -477,7 +540,7 @@ const SoftwareProductActionHelper = { }, /** for the next verision */ - addComponent(dispatch, {softwareProductId, modalClassName}) { + addComponent(dispatch, {softwareProductId, modalClassName, version}) { SoftwareProductComponentsActionHelper.clearComponentCreationData(dispatch); dispatch({ type: componentActionTypes.COMPONENT_CREATE_OPEN @@ -486,7 +549,7 @@ const SoftwareProductActionHelper = { type: modalActionTypes.GLOBAL_MODAL_SHOW, data: { modalComponentName: modalContentMapper.COMPONENT_CREATION, - modalComponentProps: {softwareProductId}, + modalComponentProps: {softwareProductId, version}, modalClassName, title: 'Create Virtual Function Component' } @@ -494,12 +557,12 @@ const SoftwareProductActionHelper = { }, migrateSoftwareProduct(dispatch, {softwareProduct}) { - let {licenseModelId, licensingVersion, id: softwareProductId, version, status} = softwareProduct; - const newVer = status === statusEnum.CHECK_IN_STATUS || status === statusEnum.SUBMIT_STATUS ? - adjustMinorVersion(version.id, 1) : version.id; - migrateSoftwareProduct(softwareProductId, version) - .then(() =>OnboardingActionHelper.navigateToSoftwareProductLandingPage(dispatch, - {softwareProductId, version: {id: newVer, label: newVer}, licenseModelId, licensingVersion})); + let {id: softwareProductId, version} = softwareProduct; + const newVer = version.id; + migrateSoftwareProduct(softwareProductId, version).then(() => ScreensHelper.loadScreen(dispatch, { + screen: enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, version: {id: newVer, label: newVer}} + })); } }; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductConstants.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductConstants.js index 2c094ac36a..7df46589c3 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductConstants.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductConstants.js @@ -14,7 +14,6 @@ * permissions and limitations under the License. */ import keyMirror from 'nfvo-utils/KeyMirror.js'; -import {enums} from 'sdc-app/onboarding/OnboardingConstants.js'; export const actionTypes = keyMirror({ SOFTWARE_PRODUCT_LOADED: null, @@ -23,7 +22,7 @@ export const actionTypes = keyMirror({ SOFTWARE_PRODUCT_LIST_EDIT: null, SOFTWARE_PRODUCT_CATEGORIES_LOADED: null, SOFTWARE_PRODUCT_QUESTIONNAIRE_UPDATE: null, - ADD_SOFTWARE_PRODUCT: null, + LOAD_LICENSING_VERSIONS_LIST: null, TOGGLE_NAVIGATION_ITEM: null, softwareProductEditor: { @@ -34,23 +33,7 @@ export const actionTypes = keyMirror({ } }); -export const navigationItems = keyMirror({ - VENDOR_SOFTWARE_PRODUCT: 'vendor-software-product', - GENERAL: 'general', - PROCESS_DETAILS: 'process-details', - DEPLOYMENT_FLAVORS: 'deployment-flavor', - NETWORKS: 'networks', - IMAGES: 'images', - ATTACHMENTS: 'attachments', - ACTIVITY_LOG: 'activity-log', - COMPONENTS: 'components', - DEPENDENCIES: 'dependencies', - COMPUTE: 'compute', - LOAD_BALANCING: 'load-balancing', - STORAGE: 'storage', - MONITORING: 'monitoring' -}); export const onboardingMethod = { MANUAL: 'Manual', @@ -69,22 +52,3 @@ export const forms = keyMirror({ export const PRODUCT_QUESTIONNAIRE = 'product'; -export const mapScreenToNavigationItem = { - [enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE]: navigationItems.VENDOR_SOFTWARE_PRODUCT, - [enums.SCREEN.SOFTWARE_PRODUCT_DETAILS]: navigationItems.GENERAL, - [enums.SCREEN.SOFTWARE_PRODUCT_ATTACHMENTS]: navigationItems.ATTACHMENTS, - [enums.SCREEN.SOFTWARE_PRODUCT_PROCESSES]: navigationItems.PROCESS_DETAILS, - [enums.SCREEN.SOFTWARE_PRODUCT_DEPLOYMENT]: navigationItems.DEPLOYMENT_FLAVORS, - [enums.SCREEN.SOFTWARE_PRODUCT_NETWORKS]: navigationItems.NETWORKS, - [enums.SCREEN.SOFTWARE_PRODUCT_ACTIVITY_LOG]: navigationItems.ACTIVITY_LOG, - [enums.SCREEN.SOFTWARE_PRODUCT_DEPENDENCIES]: navigationItems.DEPENDENCIES, - [enums.SCREEN.SOFTWARE_PRODUCT_COMPONENTS]: navigationItems.COMPONENTS, - [enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_GENERAL]: navigationItems.GENERAL, - [enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_COMPUTE]: navigationItems.COMPUTE, - [enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_LOAD_BALANCING]: navigationItems.LOAD_BALANCING, - [enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_NETWORK]: navigationItems.NETWORKS, - [enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_IMAGES]: navigationItems.IMAGES, - [enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_STORAGE]: navigationItems.STORAGE, - [enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_PROCESSES]: navigationItems.PROCESS_DETAILS, - [enums.SCREEN.SOFTWARE_PRODUCT_COMPONENT_MONITORING]: navigationItems.MONITORING, -}; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductListReducer.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductListReducer.js index 2fde8c2216..31be338ff5 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductListReducer.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductListReducer.js @@ -22,8 +22,6 @@ export default (state = [], action) => { case actionTypes.SOFTWARE_PRODUCT_LIST_EDIT: const indexForEdit = state.findIndex(vsp => vsp.id === action.payload.softwareProduct.id); return [...state.slice(0, indexForEdit), action.payload.softwareProduct, ...state.slice(indexForEdit + 1)]; - case actionTypes.ADD_SOFTWARE_PRODUCT: - return [...state, action.softwareProduct]; default: return state; } diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachments.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachments.js index f14c988866..234953ec3b 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachments.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachments.js @@ -20,13 +20,12 @@ import SoftwareProductActionHelper from 'sdc-app/onboarding/softwareProduct/Soft import HeatSetupActionHelper from './setup/HeatSetupActionHelper.js'; import SoftwareProductAttachmentsView from './SoftwareProductAttachmentsView.jsx'; import {errorLevels} from 'sdc-app/onboarding/softwareProduct/attachments/validation/HeatValidationConstants.js'; -import OnboardingActionHelper from 'sdc-app/onboarding/OnboardingActionHelper.js'; import HeatSetup from './setup/HeatSetup.js'; import {doesHeatDataExist} from './SoftwareProductAttachmentsUtils.js'; +import ScreensHelper from 'sdc-app/common/helpers/ScreensHelper.js'; +import {enums, screenTypes} from 'sdc-app/onboarding/OnboardingConstants.js'; import SoftwareProductAttachmentsActionHelper from './SoftwareProductAttachmentsActionHelper.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; - export const mapStateToProps = (state) => { let { softwareProduct: { @@ -46,8 +45,6 @@ export const mapStateToProps = (state) => { } let heatDataExist = doesHeatDataExist(heatSetup); - let isReadOnlyMode = currentSoftwareProduct && currentSoftwareProduct.version ? - VersionControllerUtils.isReadOnly(currentSoftwareProduct) : false; let {version, onboardingOrigin} = currentSoftwareProduct; return { isValidationAvailable: unassigned.length === 0 && modules.length > 0, @@ -56,17 +53,16 @@ export const mapStateToProps = (state) => { heatDataExist, goToOverview, HeatSetupComponent: HeatSetup, - isReadOnlyMode, version, onboardingOrigin, activeTab }; }; -export const mapActionsToProps = (dispatch, {softwareProductId}) => { +export const mapActionsToProps = (dispatch, {softwareProductId, version}) => { return { - onDownload: ({heatCandidate, isReadOnlyMode, version}) => SoftwareProductActionHelper.downloadHeatFile(dispatch, {softwareProductId, heatCandidate, isReadOnlyMode, version}), - onUpload: (formData, version) => dispatch({ + onDownload: ({heatCandidate, isReadOnlyMode}) => SoftwareProductActionHelper.downloadHeatFile(dispatch, {softwareProductId, heatCandidate, isReadOnlyMode, version}), + onUpload: (formData) => dispatch({ type: modalActionTypes.GLOBAL_MODAL_WARNING, data:{ msg: i18n('Upload will erase existing data. Do you want to continue?'), @@ -79,15 +75,25 @@ export const mapActionsToProps = (dispatch, {softwareProductId}) => { }) } }), - onSave: (heatCandidate, version) => SoftwareProductActionHelper.updateSoftwareProductHeatCandidate(dispatch, {softwareProductId, heatCandidate, version}), - onGoToOverview: ({version}) => { - OnboardingActionHelper.navigateToSoftwareProductLandingPage(dispatch, {softwareProductId, version}); - }, - onProcessAndValidate: ({heatData, heatDataCache, isReadOnlyMode, version}) => { + onInvalidFileUpload: () => dispatch({ + type: modalActionTypes.GLOBAL_MODAL_ERROR, + data: { + title: i18n('Upload Failed'), + confirmationButtonText: i18n('Continue'), + msg: i18n('no zip or csar file was uploaded or expected file doesn\'t exist') + } + }), + onSave: (heatCandidate) => SoftwareProductActionHelper.updateSoftwareProductHeatCandidate(dispatch, {softwareProductId, heatCandidate, version}), + onGoToOverview: () => ScreensHelper.loadScreen(dispatch, { + screen: enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, version} + }), + onProcessAndValidate: ({heatData, heatDataCache, isReadOnlyMode}) => { return HeatSetupActionHelper.processAndValidateHeat(dispatch, {softwareProductId, heatData, heatDataCache, isReadOnlyMode, version}); }, setActiveTab: ({activeTab}) => SoftwareProductAttachmentsActionHelper.setActiveTab(dispatch, {activeTab}) + }; }; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachmentsView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachmentsView.jsx index 8c59b2b1cc..a23015732b 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachmentsView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachmentsView.jsx @@ -13,12 +13,12 @@ * or implied. See the License for the specific language governing * permissions and limitations under the License. */ -import React, {Component, PropTypes} from 'react'; -import Tabs from 'react-bootstrap/lib/Tabs.js'; -import Tab from 'react-bootstrap/lib/Tab.js'; +import React, {Component} from 'react'; +import PropTypes from 'prop-types'; +import accept from 'attr-accept'; +import {SVGIcon, Tab, Tabs} from 'sdc-ui/lib/react'; import {tabsMapping} from './SoftwareProductAttachmentsConstants.js'; import i18n from 'nfvo-utils/i18n/i18n.js'; -import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; import HeatValidation from './validation/HeatValidation.js'; import {onboardingOriginTypes} from 'sdc-app/onboarding/softwareProduct/SoftwareProductConstants.js'; @@ -27,7 +27,7 @@ class HeatScreenView extends Component { static propTypes = { isValidationAvailable: PropTypes.bool, goToOverview: PropTypes.bool, - setActiveTab: PropTypes.function + setActiveTab: PropTypes.func }; render() { @@ -64,7 +64,7 @@ class HeatScreenView extends Component { labelPosition='right' color='secondary' disabled={isReadOnlyMode} - onClick={evt => {this.refs.hiddenImportFileInput.click(evt);}} + onClick={isReadOnlyMode ? undefined : evt => this.refs.hiddenImportFileInput.click(evt)} data-test-id='upload-heat'/> this.handleImport(evt)}/>
    - this.handleTabPress(key)}> - + this.handleTabPress(key)}> + setActiveTab({activeTab: tab})} @@ -83,7 +87,7 @@ class HeatScreenView extends Component { isReadOnlyMode={isReadOnlyMode} version={version}/> - + @@ -107,9 +111,14 @@ class HeatScreenView extends Component { handleImport(evt) { evt.preventDefault(); + let file = this.refs.hiddenImportFileInput.files[0]; + if(! (file && file.size && accept(file, ['.zip', '.csar'])) ) { + this.props.onInvalidFileUpload(); + return; + } let {version} = this.props; let formData = new FormData(); - formData.append('upload', this.refs.hiddenImportFileInput.files[0]); + formData.append('upload', file); this.refs.hiddenImportFileInput.value = ''; this.props.onUpload(formData, version); } diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/validation/HeatValidationView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/validation/HeatValidationView.jsx index 2308527220..3fdaa9c591 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/validation/HeatValidationView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/validation/HeatValidationView.jsx @@ -13,7 +13,8 @@ * or implied. See the License for the specific language governing * permissions and limitations under the License. */ -import React, {Component, PropTypes} from 'react'; +import React, {Component} from 'react'; +import PropTypes from 'prop-types'; import classNames from 'classnames'; import Collapse from 'react-bootstrap/lib/Collapse.js'; import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; @@ -95,7 +96,7 @@ function HeatFileTreeHeader(props) {
    {/**/} {i18n(`${props.headerTitle} ${hasErrors ? '(Draft)' : ''}`)} + 'tree-header-title-selected' : props.selectedNode === nodeFilters.ALL})}>{i18n('{title} {hasErrors}', {title: props.headerTitle, hasErrors: hasErrors ? '(Draft)' : ''})}
    ); @@ -199,7 +200,6 @@ class HeatMessageBoard extends Component { } renderError(error) { let rand = Math.random() * (3000 - 1) + 1; - console.log(this.props.selectedNode ); return (
    { - return i18n(`Are you sure you want to delete ${name}?`); + return i18n('Are you sure you want to delete {name}?', {name: name}); }; -const mapStateToProps = ({softwareProduct}) => { - let {softwareProductEditor: {data: currentSoftwareProduct}, softwareProductComponents} = softwareProduct; +const mapStateToProps = ({softwareProduct, currentScreen: {props: {version}}}) => { + let {softwareProductEditor: {data: currentSoftwareProduct = {}}, softwareProductComponents} = softwareProduct; let {componentsList} = softwareProductComponents; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); - + let {onboardingMethod = onboardingMethodTypes.HEAT} = currentSoftwareProduct; return { currentSoftwareProduct, - isReadOnlyMode, componentsList, - isManual: currentSoftwareProduct.onboardingMethod === onboardingMethod.MANUAL - + isManual: onboardingMethod === onboardingMethodTypes.MANUAL, + version }; }; -class SoftwareProductComponentsView extends React.Component { - render() { - let {currentSoftwareProduct, isReadOnlyMode, componentsList, isManual, onDeleteComponent} = this.props; - return ( - ); - } - -} - const mapActionToProps = (dispatch) => { return { - onComponentSelect: ({id: softwareProductId, componentId, version}) => { - OnboardingActionHelper.navigateToSoftwareProductComponentGeneralAndUpdateLeftPanel(dispatch, {softwareProductId, componentId, version }); - }, - onAddComponent: (softwareProductId) => SoftwareProductComponentsActionHelper.addComponent(dispatch, {softwareProductId}), + onComponentSelect: ({id: softwareProductId, componentId, version}) => + ScreensHelper.loadScreen(dispatch, { + screen: screenTypes.SOFTWARE_PRODUCT_COMPONENT_DEFAULT_GENERAL, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, version, componentId} + }), + onAddComponent: (softwareProductId, version) => SoftwareProductActionHelper.addComponent(dispatch, {softwareProductId, version, modalClassName: 'create-vfc-modal'}), onDeleteComponent: (component, softwareProductId, version) => dispatch({ type: ConfirmationModalConstants.GLOBAL_MODAL_WARNING, data:{ msg: generateMessage(component.displayName), - onConfirmed: ()=>SoftwareProductComponentsActionHelper.deleteComponent(dispatch, - { - softwareProductId, - componentId: component.id, - version - }) + onConfirmed: ()=>SoftwareProductComponentsActionHelper.deleteComponent(dispatch, { + softwareProductId, + componentId: component.id, + version + }) } }) }; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js index 8085c875f4..cf63ad79d0 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js @@ -74,6 +74,7 @@ const SoftwareProductComponentsActionHelper = { type: actionTypes.COMPONENTS_LIST_UPDATE, componentsList: response.results }); + return response; }); }, diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsList.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsList.js deleted file mode 100644 index bd4c2fa884..0000000000 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsList.js +++ /dev/null @@ -1,51 +0,0 @@ -/*! - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - */ -import {connect} from 'react-redux'; -import i18n from 'nfvo-utils/i18n/i18n.js'; - -import SoftwareProductComponentsListView from './SoftwareProductComponentsListView.jsx'; -import OnboardingActionHelper from 'sdc-app/onboarding/OnboardingActionHelper.js'; -import SoftwareProductActionHelper from 'sdc-app/onboarding/softwareProduct/SoftwareProductActionHelper.js'; -import SoftwareProductComponentsActionHelper from '../components/SoftwareProductComponentsActionHelper.js'; -import {actionTypes as globalModalActions} from 'nfvo-components/modal/GlobalModalConstants.js'; - -const generateMessage = (name) => { - return i18n(`Are you sure you want to delete ${name}?`); -}; - - -const mapActionToProps = (dispatch) => { - return { - onComponentSelect: ({id: softwareProductId, componentId, version}) => { - OnboardingActionHelper.navigateToSoftwareProductComponentGeneralAndUpdateLeftPanel(dispatch, {softwareProductId, componentId, version }); - }, - onAddComponent: (softwareProductId) => SoftwareProductActionHelper.addComponent(dispatch, {softwareProductId, modalClassName: 'create-vfc-modal'}), - onDeleteComponent: (component, softwareProductId, version) => dispatch({ - type: globalModalActions.GLOBAL_MODAL_WARNING, - data:{ - msg: generateMessage(component.displayName), - onConfirmed: ()=>SoftwareProductComponentsActionHelper.deleteComponent(dispatch, - { - softwareProductId, - componentId: component.id, - version - }) - } - }) - }; -}; - -export default connect(null, mapActionToProps, null, {withRef: true})(SoftwareProductComponentsListView); diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsListView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsListView.jsx index 88a01becfc..0bf32df1a3 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsListView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsListView.jsx @@ -14,17 +14,18 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import ListEditorView from 'nfvo-components/listEditor/ListEditorView.jsx'; import ListEditorItemView from 'nfvo-components/listEditor/ListEditorItemView.jsx'; import ListEditorItemViewField from 'nfvo-components/listEditor/ListEditorItemViewField.jsx'; -const ComponentPropType = React.PropTypes.shape({ - id: React.PropTypes.string, - name: React.PropTypes.string, - displayName: React.PropTypes.string, - description: React.PropTypes.string +const ComponentPropType = PropTypes.shape({ + id: PropTypes.string, + name: PropTypes.string, + displayName: PropTypes.string, + description: PropTypes.string }); class SoftwareProductComponentsListView extends React.Component { @@ -34,9 +35,9 @@ class SoftwareProductComponentsListView extends React.Component { }; static propTypes = { - isReadOnlyMode: React.PropTypes.bool, - componentsList: React.PropTypes.arrayOf(ComponentPropType), - onComponentSelect: React.PropTypes.func + isReadOnlyMode: PropTypes.bool, + componentsList: PropTypes.arrayOf(ComponentPropType), + onComponentSelect: PropTypes.func }; render() { @@ -52,7 +53,7 @@ class SoftwareProductComponentsListView extends React.Component { renderComponents() { const {localFilter} = this.state; - const {isManual, onAddComponent, isReadOnlyMode, currentSoftwareProduct: {id: softwareProductId}, componentsList } = this.props; + const {isManual, onAddComponent, isReadOnlyMode, version, currentSoftwareProduct: {id: softwareProductId}, componentsList } = this.props; return ( this.setState({localFilter: value})} isReadOnlyMode={isReadOnlyMode || !!this.filterList().length} plusButtonTitle={i18n('Add Component')} - onAdd={isManual && componentsList.length === 0 ? () => onAddComponent(softwareProductId) : false} + onAdd={isManual && componentsList.length === 0 ? () => onAddComponent(softwareProductId, version) : false} twoColumns> {this.filterList().map(component => this.renderComponentsListItem(component))} @@ -70,7 +71,7 @@ class SoftwareProductComponentsListView extends React.Component { renderComponentsListItem(component) { let {id: componentId, name, displayName, description = ''} = component; - let {currentSoftwareProduct: {id, version}, onComponentSelect} = this.props; + let {currentSoftwareProduct: {id}, onComponentSelect, version} = this.props; return ( { +const mapStateToProps = ({softwareProduct}) => { let {softwareProductEditor: {data: currentVSP}, softwareProductComponents} = softwareProduct; let {componentEditor: {qdata, dataMap, qgenericFieldInfo}, computeFlavor: {computesList: computeFlavorsList}} = softwareProductComponents; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentVSP); return { qdata, dataMap, qgenericFieldInfo, - isReadOnlyMode, - softwareProductId, - componentId, computeFlavorsList, isManual: currentVSP.onboardingMethod === onboardingMethod.MANUAL }; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/SoftwareProductComponentComputeView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/SoftwareProductComponentComputeView.jsx index dd524a35f3..55e5e2b30b 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/SoftwareProductComponentComputeView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/SoftwareProductComponentComputeView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import Form from 'nfvo-components/input/validation/Form.jsx'; import NumberOfVms from './computeComponents/NumberOfVms.jsx'; import GuestOs from './computeComponents/GuestOs.jsx'; @@ -23,13 +24,13 @@ import Validator from 'nfvo-utils/Validator.js'; class SoftwareProductComponentComputeView extends React.Component { static propTypes = { - dataMap: React.PropTypes.object, - qgenericFieldInfo: React.PropTypes.object, - isReadOnlyMode: React.PropTypes.bool, - isManual: React.PropTypes.bool, - onQDataChanged: React.PropTypes.func.isRequired, - qValidateData: React.PropTypes.func.isRequired, - onSubmit: React.PropTypes.func.isRequired + dataMap: PropTypes.object, + qgenericFieldInfo: PropTypes.object, + isReadOnlyMode: PropTypes.bool, + isManual: PropTypes.bool, + onQDataChanged: PropTypes.func.isRequired, + qValidateData: PropTypes.func.isRequired, + onSubmit: PropTypes.func.isRequired }; render() { diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/computeComponents/ComputeFlavors.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/computeComponents/ComputeFlavors.js index c72d42c11f..2b6d84f381 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/computeComponents/ComputeFlavors.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/computeComponents/ComputeFlavors.js @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import i18n from 'nfvo-utils/i18n/i18n.js'; import ListEditorView from 'nfvo-components/listEditor/ListEditorView.jsx'; @@ -28,26 +29,26 @@ const mapActionsToProps = (dispatch, {softwareProductId, componentId, version}) onDeleteCompute: ({id, name}) => dispatch({ type: modalActionTypes.GLOBAL_MODAL_WARNING, data:{ - msg: i18n(`Are you sure you want to delete "${name}"?`), + msg: i18n('Are you sure you want to delete "{name}"?', {name: name}), onConfirmed: () => ComputeFlavorActionHelper.deleteCompute(dispatch, {softwareProductId, componentId, computeId: id, version}) } }) }; }; -const computeItemPropType = React.PropTypes.shape({ - id: React.PropTypes.string, - name: React.PropTypes.string, - description: React.PropTypes.string +const computeItemPropType = PropTypes.shape({ + id: PropTypes.string, + name: PropTypes.string, + description: PropTypes.string }); class ComputeFlavors extends React.Component { static propTypes = { - isReadOnlyMode: React.PropTypes.bool, - isManual: React.PropTypes.bool, - onAddComputeClick: React.PropTypes.func, - computeFlavorsList: React.PropTypes.arrayOf(computeItemPropType) + isReadOnlyMode: PropTypes.bool, + isManual: PropTypes.bool, + onAddComputeClick: PropTypes.func, + computeFlavorsList: PropTypes.arrayOf(computeItemPropType) }; state = { diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/computeComponents/GuestOs.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/computeComponents/GuestOs.jsx index 16bf599834..8ae9961859 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/computeComponents/GuestOs.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/computeComponents/GuestOs.jsx @@ -23,7 +23,7 @@ import GridItem from 'nfvo-components/grid/GridItem.jsx'; const GuestOs = ({qgenericFieldInfo, dataMap, onQDataChanged}) => { return(
    - +
    @@ -55,7 +55,7 @@ const GuestOs = ({qgenericFieldInfo, dataMap, onQDataChanged}) => { errorText={qgenericFieldInfo['compute/guestOS/name'].errorText} value={dataMap['compute/guestOS/name']} /> - + { +export const mapStateToProps = ({ + softwareProduct: { + softwareProductEditor, + softwareProductComponents: {computeFlavor: {computeEditor = {}}} + }, + currentScreen: { + props: {isReadOnlyMode} + } +}) => { const {data: currentSoftwareProduct = {}} = softwareProductEditor; - const isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); let {data , qdata, qgenericFieldInfo, dataMap, genericFieldInfo, formReady} = computeEditor; let isFormValid = ValidationHelper.checkFormValid(genericFieldInfo); diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/computeComponents/computeFlavor/ComputeFlavorEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/computeComponents/computeFlavor/ComputeFlavorEditorView.jsx index 8f8a504629..e542ce1fd1 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/computeComponents/computeFlavor/ComputeFlavorEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/compute/computeComponents/computeFlavor/ComputeFlavorEditorView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import Form from 'nfvo-components/input/validation/Form.jsx'; import Input from 'nfvo-components/input/validation/Input.jsx'; import GridSection from 'nfvo-components/grid/GridSection.jsx'; @@ -24,15 +25,15 @@ import i18n from 'nfvo-utils/i18n/i18n.js'; class ComputeEditorView extends React.Component { static propTypes = { - data: React.PropTypes.object, - qdata: React.PropTypes.object, - qschema: React.PropTypes.object, - isReadOnlyMode: React.PropTypes.bool, - isManual: React.PropTypes.bool, - onDataChanged: React.PropTypes.func.isRequired, - onQDataChanged: React.PropTypes.func.isRequired, - onSubmit: React.PropTypes.func.isRequired, - onCancel: React.PropTypes.func.isRequired + data: PropTypes.object, + qdata: PropTypes.object, + qschema: PropTypes.object, + isReadOnlyMode: PropTypes.bool, + isManual: PropTypes.bool, + onDataChanged: PropTypes.func.isRequired, + onQDataChanged: PropTypes.func.isRequired, + onSubmit: PropTypes.func.isRequired, + onCancel: PropTypes.func.isRequired }; render() { @@ -57,8 +58,8 @@ class ComputeEditorView extends React.Component { onValidateForm={() => onValidateForm() } className='component-questionnaire-validation-form' submitButtonText={edittingComputeMode ? i18n('Save') : i18n('Create')}> - - + + - + { return( - + { errorText={qgenericFieldInfo['vmSizing/persistentStorageVolumeSize'].errorText} value={dataMap['vmSizing/persistentStorageVolumeSize']} /> - + { - let {softwareProductComponents: {componentEditor: {data, genericFieldInfo, formReady}}, softwareProductEditor: {data: {version}}} = softwareProduct; + let {softwareProductComponents: {componentEditor: {data, genericFieldInfo, formReady}}} = softwareProduct; let isFormValid = ValidationHelper.checkFormValid(genericFieldInfo); return { data, genericFieldInfo, formReady, - isFormValid, - version + isFormValid }; }; -const mapActionsToProps = (dispatch, {softwareProductId}) => { +const mapActionsToProps = (dispatch, {softwareProductId, version}) => { return { onDataChanged: (deltaData) => ValidationHelper.dataChanged(dispatch, {deltaData, formName: forms.CREATE_FORM}), //onDataChanged: deltaData => SoftwareProductComponentsActionHelper.componentDataChanged(dispatch, {deltaData}), - onSubmit: (componentData, version) => { + onSubmit: (componentData) => { return SoftwareProductComponentsActionHelper.createSoftwareProductComponent(dispatch, {softwareProductId, componentData, version}); }, diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/creation/SoftwareProductComponentCreationView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/creation/SoftwareProductComponentCreationView.jsx index 55bcc818f5..42804ce5a6 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/creation/SoftwareProductComponentCreationView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/creation/SoftwareProductComponentCreationView.jsx @@ -28,7 +28,7 @@ class ComponentCreationView extends React.Component { let {data = {}, onDataChanged, onCancel, genericFieldInfo} = this.props; let {displayName, description} = data; return( -
    +
    { genericFieldInfo &&
    this.props.onValidateForm(forms.CREATE_FORM) } className='entitlement-pools-form'> - - + + onDataChanged({displayName})} @@ -53,7 +53,7 @@ class ComponentCreationView extends React.Component { value={displayName} type='text'/> - + onDataChanged({description})} @@ -66,13 +66,13 @@ class ComponentCreationView extends React.Component { } -
    +
    ); } submit() { - const {onSubmit, data, version} = this.props; - onSubmit(data, version); + const {onSubmit, data} = this.props; + onSubmit(data); } } diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/general/SoftwareProductComponentsGeneral.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/general/SoftwareProductComponentsGeneral.js index 7b4135028b..8c06fd0ab8 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/general/SoftwareProductComponentsGeneral.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/general/SoftwareProductComponentsGeneral.js @@ -16,25 +16,20 @@ import {connect} from 'react-redux'; import SoftwareProductComponentsGeneralView from './SoftwareProductComponentsGeneralView.jsx'; import SoftwareProductComponentsActionHelper from '../SoftwareProductComponentsActionHelper.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import ValidationHelper from 'sdc-app/common/helpers/ValidationHelper.js'; import SoftwareProductActionHelper from 'sdc-app/onboarding/softwareProduct/SoftwareProductActionHelper.js'; - import {forms, COMPONENTS_QUESTIONNAIRE} from '../SoftwareProductComponentsConstants.js'; import {onboardingMethod} from '../../SoftwareProductConstants.js'; - export const mapStateToProps = ({softwareProduct}) => { let {softwareProductEditor: {data: currentVSP}, softwareProductComponents} = softwareProduct; let {componentEditor: {data: componentData = {} , qdata, qgenericFieldInfo : qGenericFieldInfo, dataMap, genericFieldInfo}} = softwareProductComponents; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentVSP); let isFormValid = ValidationHelper.checkFormValid(genericFieldInfo); return { componentData, qdata, - isReadOnlyMode, isManual: currentVSP.onboardingMethod === onboardingMethod.MANUAL, genericFieldInfo, qGenericFieldInfo, @@ -43,7 +38,6 @@ export const mapStateToProps = ({softwareProduct}) => { }; }; - const mapActionsToProps = (dispatch, {softwareProductId, version, componentId}) => { return { onDataChanged: (deltaData) => ValidationHelper.dataChanged(dispatch, {deltaData, formName: forms.ALL_SPC_FORMS}), diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageActionHelper.js index 34198281b7..8d70d6f14c 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageActionHelper.js @@ -87,7 +87,7 @@ const SoftwareProductComponentImagesActionHelper = { return fetchImage({softwareProductId, componentId, imageId, version}); }, - openEditImageEditor(dispatch, {image, softwareProductId, componentId, version, isReadOnlyMode, modalClassName}) { + openEditImageEditor(dispatch, {image, softwareProductId, componentId, version, isReadOnlyMode}) { return SoftwareProductComponentImagesActionHelper.loadImageData({softwareProductId, componentId, imageId: image.id, version}).then(({data}) => { SoftwareProductComponentImagesActionHelper.loadImageQuestionnaire(dispatch, { softwareProductId, @@ -100,7 +100,6 @@ const SoftwareProductComponentImagesActionHelper = { componentId, version, isReadOnlyMode, - modalClassName, image, data }); @@ -110,12 +109,13 @@ const SoftwareProductComponentImagesActionHelper = { openImageEditor(dispatch, {image = {}, data = {}, softwareProductId, componentId, version, isReadOnlyMode}) { - let title = (image && image.id) ? i18n('Edit Image') : i18n('Create New Image'); - let className = (image && image.id) ? 'image-edit-editor-model' : 'image-new-editor-modal'; + let {id} = image; + let title = id ? i18n('Edit Image') : i18n('Create New Image'); + let className = id ? 'image-modal-edit' : 'image-modal-new'; dispatch({ type: actionTypes.ImageEditor.OPEN, - image: {...data, id: image.id} + image: {...data, id} }); dispatch({ @@ -123,9 +123,11 @@ const SoftwareProductComponentImagesActionHelper = { data: { modalComponentName: modalContentMapper.SOFTWARE_PRODUCT_COMPONENT_IMAGE_EDITOR, title: title, - modalComponentProps: {softwareProductId, componentId, version, isReadOnlyMode, dialogClassName:className} + modalClassName: className, + modalComponentProps: {softwareProductId, componentId, version, isReadOnlyMode} } }); + }, closeImageEditor(dispatch) { @@ -137,6 +139,7 @@ const SoftwareProductComponentImagesActionHelper = { dispatch({ type: actionTypes.ImageEditor.CLOSE }); + }, loadImageQuestionnaire(dispatch, {softwareProductId, componentId, imageId, version}) { @@ -166,4 +169,5 @@ const SoftwareProductComponentImagesActionHelper = { } } }; + export default SoftwareProductComponentImagesActionHelper; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageEditor.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageEditor.js index 5c81f05e80..c5f23e7681 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageEditor.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageEditor.js @@ -17,18 +17,19 @@ import {connect} from 'react-redux'; import ValidationHelper from 'sdc-app/common/helpers/ValidationHelper.js'; import SoftwareProductComponentsImageActionHelper from './SoftwareProductComponentsImageActionHelper.js'; import SoftwareProductComponentsImageEditorView from './SoftwareProductComponentsImageEditorView.jsx'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import {onboardingMethod as onboardingMethodTypes} from '../../SoftwareProductConstants.js'; import {forms} from 'sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsConstants.js'; import {IMAGE_QUESTIONNAIRE} from './SoftwareProductComponentsImageConstants.js'; -export const mapStateToProps = ({softwareProduct}) => { +export const mapStateToProps = ({ + softwareProduct, + currentScreen: {props: {isReadOnlyMode}} +}) => { let {softwareProductEditor: {data:currentSoftwareProduct = {}, isValidityData = true}, softwareProductComponents} = softwareProduct; let {images: {imageEditor = {}}} = softwareProductComponents; let {data, qdata, genericFieldInfo, qgenericFieldInfo, dataMap, formReady} = imageEditor; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); let {version, onboardingMethod} = currentSoftwareProduct; let isManual = onboardingMethod === onboardingMethodTypes.MANUAL; let isFormValid = ValidationHelper.checkFormValid(genericFieldInfo) && ValidationHelper.checkFormValid(qgenericFieldInfo); @@ -47,6 +48,7 @@ export const mapStateToProps = ({softwareProduct}) => { isReadOnlyMode, isManual: isManual }; + }; const mapActionsToProps = (dispatch, {softwareProductId, componentId, version}) => { diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageEditorView.jsx index 7c1a3f5b55..a5ef152e01 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageEditorView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Form from 'nfvo-components/input/validation/Form.jsx'; @@ -24,9 +25,9 @@ import {imageCustomValidations} from './ImageValidations.js'; class SoftwareProductComponentsImageEditorView extends React.Component { static propTypes = { - onDataChanged: React.PropTypes.func.isRequired, - onSubmit: React.PropTypes.func.isRequired, - onCancel: React.PropTypes.func.isRequired + onDataChanged: PropTypes.func.isRequired, + onSubmit: PropTypes.func.isRequired, + onCancel: PropTypes.func.isRequired }; render() { diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageList.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageList.js index fb3bd35eb2..d071647058 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageList.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageList.js @@ -16,7 +16,6 @@ import {connect} from 'react-redux'; import i18n from 'nfvo-utils/i18n/i18n.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; import SoftwareProductComponentsImageListView from './SoftwareProductComponentsImageListView.jsx'; import ImageHelper from './SoftwareProductComponentsImageActionHelper.js'; @@ -31,38 +30,35 @@ export const mapStateToProps = ({softwareProduct}) => { let {softwareProductEditor: {data: currentSoftwareProduct = {}, isValidityData = true}, softwareProductComponents} = softwareProduct; let {images: {imagesList = []}, componentEditor: {data: componentData, qdata, dataMap, qgenericFieldInfo}} = softwareProductComponents; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); - let {version, onboardingMethod} = currentSoftwareProduct; + let {onboardingMethod} = currentSoftwareProduct; let isManual = onboardingMethod === onboardingMethodTypes.MANUAL; return { - version, componentData, qdata, dataMap, qgenericFieldInfo, isValidityData, imagesList, - isReadOnlyMode, isManual : isManual }; }; -const mapActionsToProps = (dispatch, {softwareProductId, componentId}) => { +const mapActionsToProps = (dispatch, {softwareProductId, componentId, version}) => { return { onQDataChanged: (deltaData) => ValidationHelper.qDataChanged(dispatch, {deltaData, qName: COMPONENTS_QUESTIONNAIRE}), - onAddImage: (version, isReadOnlyMode) => { + onAddImage: (isReadOnlyMode) => { SoftwareProductComponentsImagesActionHelper.openImageEditor(dispatch, {isReadOnlyMode, softwareProductId, componentId, version} );}, - onDeleteImage: ((image, version) => { + onDeleteImage: (image) => { let shortenedFileName = (image.fileName.length > 40) ? image.fileName.substr(0,40) + '...' : image.fileName; dispatch({ type: modalActionTypes.GLOBAL_MODAL_WARNING, data: { - msg: i18n(`Are you sure you want to delete "${shortenedFileName}"?`), + msg: i18n('Are you sure you want to delete "{shortenedFileName}"?', {shortenedFileName: shortenedFileName}), onConfirmed: () => ImageHelper.deleteImage(dispatch, { softwareProductId, componentId, @@ -71,13 +67,13 @@ const mapActionsToProps = (dispatch, {softwareProductId, componentId}) => { }) } }); - }), - onEditImageClick: (image, version, isReadOnlyMode) => { + }, + onEditImageClick: (image, isReadOnlyMode) => { SoftwareProductComponentsImagesActionHelper.openEditImageEditor(dispatch, { image, isReadOnlyMode, softwareProductId, componentId, version, modalClassName: 'image-modal-edit'} ); }, - onSubmit: (version, qdata) => { return SoftwareProductComponentsActionHelper.updateSoftwareProductComponentQuestionnaire(dispatch, + onSubmit: (qdata) => { return SoftwareProductComponentsActionHelper.updateSoftwareProductComponentQuestionnaire(dispatch, {softwareProductId, vspComponentId: componentId, version, diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageListView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageListView.jsx index 54def08fc1..004cbebe5d 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageListView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/SoftwareProductComponentsImageListView.jsx @@ -75,7 +75,7 @@ class SoftwareProductComponentsImageListView extends React.Component { renderImagesList() { const {localFilter} = this.state; - let {isReadOnlyMode, onAddImage, isManual, version} = this.props; + let {isReadOnlyMode, onAddImage, isManual} = this.props; return ( this.setState({localFilter: value})} - onAdd={isManual ? () => onAddImage(version, isReadOnlyMode) : null} + onAdd={isManual ? () => onAddImage(isReadOnlyMode) : null} plusButtonTitle={i18n('Add Image')} twoColumns> {this.filterList().map(image => this.renderImagesListItem(image, isReadOnlyMode))} @@ -95,13 +95,13 @@ class SoftwareProductComponentsImageListView extends React.Component { renderImagesListItem(image, isReadOnlyMode) { let {id, fileName} = image; - let {onEditImageClick, version, isManual, onDeleteImage} = this.props; + let {onEditImageClick, isManual, onDeleteImage} = this.props; return ( onEditImageClick(image, version, isReadOnlyMode)} - onDelete={isManual ? () => onDeleteImage(image, version) : null}> + onSelect={() => onEditImageClick(image, isReadOnlyMode)} + onDelete={isManual ? () => onDeleteImage(image) : null}>
    {fileName}
    @@ -125,8 +125,8 @@ class SoftwareProductComponentsImageListView extends React.Component { } save() { - let {onSubmit, qdata, version} = this.props; - return onSubmit(version, qdata); + let {onSubmit, qdata} = this.props; + return onSubmit(qdata); } } export default SoftwareProductComponentsImageListView; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/imagesEditorComponents/FileDetails.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/imagesEditorComponents/FileDetails.jsx index 2e9ab417d8..64367c00f2 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/imagesEditorComponents/FileDetails.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/imagesEditorComponents/FileDetails.jsx @@ -26,8 +26,8 @@ import Version from './Version.jsx'; const FileDetails = ({editingMode, fileName, onDataChanged, isManual, dataMap, onQDataChanged, genericFieldInfo, qgenericFieldInfo}) => { let fileNameCols = (editingMode) ? 3 : 4; return( - - + + onDataChanged({fileName}, forms.IMAGE_EDIT_FORM)} diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/imagesEditorComponents/Version.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/imagesEditorComponents/Version.jsx index 7dd577b8c9..bd55c5ba91 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/imagesEditorComponents/Version.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/images/imagesEditorComponents/Version.jsx @@ -22,7 +22,7 @@ import {imageCustomValidations} from '../ImageValidations.js'; const Version = ({isManual, dataMap, qgenericFieldInfo, onQDataChanged}) => { return( - + { - let {softwareProductEditor: {data: currentVSP}, softwareProductComponents} = softwareProduct; - let {componentEditor: {qdata, qgenericFieldInfo : genericFieldInfo, dataMap}} = softwareProductComponents; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentVSP); +export const mapStateToProps = ({softwareProduct: {softwareProductComponents}}) => { + + let {componentEditor: {qdata, qgenericFieldInfo: genericFieldInfo, dataMap}} = softwareProductComponents; return { qdata, genericFieldInfo, - dataMap, - isReadOnlyMode + dataMap }; -}; +}; const mapActionsToProps = (dispatch, {softwareProductId, version, componentId}) => { return { onQDataChanged: (deltaData) => ValidationHelper.qDataChanged(dispatch, {deltaData, qName: COMPONENTS_QUESTIONNAIRE}), onSubmit: ({qdata}) =>{ return SoftwareProductComponentsActionHelper.updateSoftwareProductComponentQuestionnaire(dispatch, {softwareProductId, version, vspComponentId: componentId, qdata});} }; - }; export default connect(mapStateToProps, mapActionsToProps, null, {withRef: true})(SoftwareProductComponentLoadBalancingView); diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/loadBalancing/SoftwareProductComponentLoadBalancingRefView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/loadBalancing/SoftwareProductComponentLoadBalancingRefView.jsx index 8a82f54901..1cbb9afc5d 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/loadBalancing/SoftwareProductComponentLoadBalancingRefView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/loadBalancing/SoftwareProductComponentLoadBalancingRefView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; import i18n from 'nfvo-utils/i18n/i18n.js'; @@ -79,11 +80,11 @@ const TextAreaItem = ({item, toggle, expanded, genericFieldInfo, dataMap, onQDat class SoftwareProductComponentLoadBalancingView extends React.Component { static propTypes = { - componentId: React.PropTypes.string.isRequired, - softwareProductId: React.PropTypes.string.isRequired, - qdata: React.PropTypes.object, - qschema: React.PropTypes.object, - currentSoftwareProduct: React.PropTypes.object + componentId: PropTypes.string.isRequired, + softwareProductId: PropTypes.string.isRequired, + qdata: PropTypes.object, + qschema: PropTypes.object, + currentSoftwareProduct: PropTypes.object }; state = { diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoring.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoring.js index 730beba545..8871aabbb5 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoring.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoring.js @@ -14,7 +14,6 @@ * permissions and limitations under the License. */ import {connect} from 'react-redux'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import SoftwareProductComponentsMonitoringView from './SoftwareProductComponentsMonitoringView.jsx'; import SoftwareProductComponentsMonitoringAction from './SoftwareProductComponentsMonitoringActionHelper.js'; import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; @@ -24,17 +23,15 @@ import i18n from 'nfvo-utils/i18n/i18n.js'; export const mapStateToProps = ({softwareProduct}) => { - let {softwareProductEditor: {data:currentVSP = {}}, softwareProductComponents: {monitoring}} = softwareProduct; - let filenames = monitoring; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentVSP); - + let {softwareProductComponents: {monitoring}} = softwareProduct; return { - isReadOnlyMode, - filenames + filenames: monitoring }; + }; const mapActionsToProps = (dispatch, {softwareProductId, version, componentId}) => { + return { onDropMibFileToUpload: (formData, type) => SoftwareProductComponentsMonitoringAction.uploadFile(dispatch, { @@ -58,9 +55,9 @@ const mapActionsToProps = (dispatch, {softwareProductId, version, componentId}) title: i18n('Upload Failed'), msg: i18n('Expected "zip" file. Please check the provided file type.') } - }), - + }) }; + }; export default connect(mapStateToProps, mapActionsToProps, null, {withRef: true})(SoftwareProductComponentsMonitoringView); diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoringView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoringView.jsx index 2d5a965c40..41acee43ca 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoringView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoringView.jsx @@ -13,7 +13,8 @@ * or implied. See the License for the specific language governing * permissions and limitations under the License. */ -import React, {Component, PropTypes} from 'react'; +import React, {Component} from 'react'; +import PropTypes from 'prop-types'; import Dropzone from 'react-dropzone'; import Button from 'sdc-ui/lib/react/Button.js'; import DraggableUploadFileBox from 'nfvo-components/fileupload/DraggableUploadFileBox.jsx'; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/NICCreation/NICCreation.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/NICCreation/NICCreation.js index 865367a734..d4aaf7cc7e 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/NICCreation/NICCreation.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/NICCreation/NICCreation.js @@ -36,13 +36,13 @@ export const mapStateToProps = ({softwareProduct}) => { }; }; -const mapActionsToProps = (dispatch) => { +const mapActionsToProps = (dispatch, {softwareProductId, version}) => { return { onDataChanged: deltaData => ValidationHelper.dataChanged(dispatch, {deltaData, formName: NIC_CREATION_FORM_NAME}), onCancel: () => NICCreationActionHelper.close(dispatch), - onSubmit: ({nic, softwareProductId, componentId, version}) => { - NICCreationActionHelper.close(dispatch); + onSubmit: ({nic, componentId}) => { SoftwareProductComponentsNetworkActionHelper.createNIC(dispatch, {nic, softwareProductId, componentId, version}); + NICCreationActionHelper.close(dispatch); }, onValidateForm: () => ValidationHelper.validateForm(dispatch, NIC_CREATION_FORM_NAME) }; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/NICCreation/NICCreationActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/NICCreation/NICCreationActionHelper.js index ad28c86b81..a40b32d51a 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/NICCreation/NICCreationActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/NICCreation/NICCreationActionHelper.js @@ -20,7 +20,7 @@ import {modalContentMapper} from 'sdc-app/common/modal/ModalContentMapper.js'; export default { - open(dispatch, {softwareProductId, componentId, modalClassName}) { + open(dispatch, {softwareProductId, componentId, modalClassName, version}) { dispatch({ type: actionTypes.NICCreation.OPEN }); @@ -31,7 +31,7 @@ export default { modalComponentName: modalContentMapper.NIC_CREATION, title: i18n('Create NEW NIC'), modalClassName, - modalComponentProps: {softwareProductId, componentId} + modalComponentProps: {softwareProductId, componentId, version} } }); }, diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/NICCreation/NICCreationView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/NICCreation/NICCreationView.jsx index 3cb731a421..258876844a 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/NICCreation/NICCreationView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/NICCreation/NICCreationView.jsx @@ -14,26 +14,27 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Input from 'nfvo-components/input/validation/Input.jsx'; import Form from 'nfvo-components/input/validation/Form.jsx'; import GridSection from 'nfvo-components/grid/GridSection.jsx'; import GridItem from 'nfvo-components/grid/GridItem.jsx'; -const NICPropType = React.PropTypes.shape({ - id: React.PropTypes.string, - name: React.PropTypes.string, - description: React.PropTypes.string, - networkId: React.PropTypes.string +const NICPropType = PropTypes.shape({ + id: PropTypes.string, + name: PropTypes.string, + description: PropTypes.string, + networkId: PropTypes.string }); class NICCreationView extends React.Component { static propTypes = { data: NICPropType, - onDataChanged: React.PropTypes.func.isRequired, - onSubmit: React.PropTypes.func.isRequired, - onCancel: React.PropTypes.func.isRequired + onDataChanged: PropTypes.func.isRequired, + onSubmit: PropTypes.func.isRequired, + onCancel: PropTypes.func.isRequired }; render() { @@ -51,8 +52,8 @@ class NICCreationView extends React.Component { isValid={isFormValid} onValidateForm={() => onValidateForm()} formReady={formReady} > - - + + - +
    @@ -96,7 +97,7 @@ class NICCreationView extends React.Component {
    - + { +export const mapStateToProps = ({softwareProduct, currentScreen}) => { let {softwareProductEditor: {data:currentSoftwareProduct = {}, isValidityData = true}, softwareProductComponents} = softwareProduct; - let {network: {nicEditor = {}}} = softwareProductComponents; let {data, qdata, genericFieldInfo, qgenericFieldInfo, dataMap, formReady} = nicEditor; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); + let {props: {isReadOnlyMode}} = currentScreen; let {onboardingMethod} = currentSoftwareProduct; let protocols = []; if(qdata && qdata.protocols && qdata.protocols.protocols && qdata.protocols.protocols.length){ @@ -55,11 +53,11 @@ export const mapStateToProps = ({softwareProduct}) => { }; -const mapActionsToProps = (dispatch, {softwareProductId, componentId}) => { +const mapActionsToProps = (dispatch, {softwareProductId, componentId, version}) => { return { onDataChanged: (deltaData) => ValidationHelper.dataChanged(dispatch, {deltaData, formName: forms.NIC_EDIT_FORM}), - onSubmit: ({data, qdata, version}) => SoftwareProductComponentsNetworkActionHelper.saveNICDataAndQuestionnaire(dispatch, {softwareProductId, version, componentId, data, qdata}), + onSubmit: ({data, qdata}) => SoftwareProductComponentsNetworkActionHelper.saveNICDataAndQuestionnaire(dispatch, {softwareProductId, version, componentId, data, qdata}), onCancel: () => SoftwareProductComponentsNetworkActionHelper.closeNICEditor(dispatch), onValidateForm: () => ValidationHelper.validateForm(dispatch, forms.NIC_EDIT_FORM), onQDataChanged: (deltaData) => ValidationHelper.qDataChanged(dispatch, {deltaData, diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNICEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNICEditorView.jsx index 8a4c55a411..fbb3d53033 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNICEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNICEditorView.jsx @@ -65,8 +65,8 @@ class SoftwareProductComponentsNetworkEditorView extends React.Component { } submit() { - let {data, qdata, onSubmit, version} = this.props; - onSubmit({data, qdata, version}); + let {data, qdata, onSubmit} = this.props; + onSubmit({data, qdata}); } } diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNetworkActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNetworkActionHelper.js index a3cfe65128..1ffbc5919f 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNetworkActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNetworkActionHelper.js @@ -78,7 +78,7 @@ const SoftwareProductComponentNetworkActionHelper = { }); }, - openNICEditor(dispatch, {nic = {}, data = {}, softwareProductId, componentId, isReadOnlyMode, modalClassName}) { + openNICEditor(dispatch, {nic = {}, data = {}, softwareProductId, componentId, isReadOnlyMode, modalClassName, version}) { dispatch({ type: actionTypes.NICEditor.FILL_DATA, nic: {...data, id: nic.id} @@ -87,7 +87,7 @@ const SoftwareProductComponentNetworkActionHelper = { type: GlobalModalActions.GLOBAL_MODAL_SHOW, data: { modalClassName, - modalComponentProps: {softwareProductId, componentId, isReadOnlyMode}, + modalComponentProps: {softwareProductId, componentId, isReadOnlyMode, version}, modalComponentName: modalPagesMapper.NIC_EDITOR, title: i18n('Edit NIC') } diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNetworkList.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNetworkList.js index 0fa877e90f..bb256d5d41 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNetworkList.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNetworkList.js @@ -15,7 +15,6 @@ */ import {connect} from 'react-redux'; import i18n from 'nfvo-utils/i18n/i18n.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import SoftwareProductComponentsActionHelper from 'sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js'; import SoftwareProductComponentsNetworkListView from './SoftwareProductComponentsNetworkListView.jsx'; @@ -31,8 +30,8 @@ export const mapStateToProps = ({softwareProduct}) => { let {softwareProductEditor: {data: currentSoftwareProduct = {}, isValidityData = true}, softwareProductComponents} = softwareProduct; let {network: {nicList = []}, componentEditor: {data: componentData, qdata, dataMap, qgenericFieldInfo}} = softwareProductComponents; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); let {version, onboardingMethod} = currentSoftwareProduct; + let isManual = onboardingMethod === onboardingMethodTypes.MANUAL; return { version, @@ -42,26 +41,25 @@ export const mapStateToProps = ({softwareProduct}) => { qgenericFieldInfo, isValidityData, nicList, - isReadOnlyMode, - isManual: onboardingMethod === onboardingMethodTypes.MANUAL + isManual }; }; -const mapActionsToProps = (dispatch, {softwareProductId, componentId}) => { +const mapActionsToProps = (dispatch, {softwareProductId, componentId, version}) => { return { onQDataChanged: (deltaData) => ValidationHelper.qDataChanged(dispatch, {deltaData, qName: COMPONENTS_QUESTIONNAIRE}), - onAddNic: () => NICCreationActionHelper.open(dispatch, {softwareProductId, componentId, modalClassName: 'network-nic-modal-create'}), - onDeleteNic: (nic, version) => dispatch({ + onAddNic: () => NICCreationActionHelper.open(dispatch, {softwareProductId, componentId, modalClassName: 'network-nic-modal-create', version}), + onDeleteNic: (nic) => dispatch({ type: GlobalModalActions.GLOBAL_MODAL_WARNING, data:{ - msg: i18n(`Are you sure you want to delete "${nic.name}"?`), + msg: i18n('Are you sure you want to delete "{name}"?', {name: nic.name}), onConfirmed: () => SoftwareProductComponentsNetworkActionHelper.deleteNIC(dispatch, {softwareProductId, componentId, nicId: nic.id, version}) } }), - onEditNicClick: (nic, version, isReadOnlyMode) => { + onEditNicClick: (nic, isReadOnlyMode) => { Promise.all([ SoftwareProductComponentsNetworkActionHelper.loadNICData({ softwareProductId, @@ -77,10 +75,10 @@ const mapActionsToProps = (dispatch, {softwareProductId, componentId}) => { }) ]).then( ([{data}]) => SoftwareProductComponentsNetworkActionHelper.openNICEditor(dispatch, {nic, data, - isReadOnlyMode, softwareProductId, componentId, modalClassName: 'network-nic-modal-edit'}) + isReadOnlyMode, softwareProductId, componentId, modalClassName: 'network-nic-modal-edit', version}) ); }, - onSubmit: ({qdata, version}) => { return SoftwareProductComponentsActionHelper.updateSoftwareProductComponentQuestionnaire(dispatch, + onSubmit: ({qdata}) => { return SoftwareProductComponentsActionHelper.updateSoftwareProductComponentQuestionnaire(dispatch, {softwareProductId, version, vspComponentId: componentId, qdata}); diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Acceptable.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Acceptable.jsx index 524b95c3ad..0fc7404c56 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Acceptable.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Acceptable.jsx @@ -21,53 +21,53 @@ import GridItem from 'nfvo-components/grid/GridItem.jsx'; const Acceptable = ({qgenericFieldInfo, dataMap, onQDataChanged}) => { return( - - -
    {i18n('Acceptable Jitter')}
    -
    - -
    {i18n('Allow Packet Loss')}
    -
    - - onQDataChanged({'sizing/acceptableJitter/mean' : val})} /> - - - onQDataChanged({'sizing/acceptableJitter/max' : val})} /> - - - onQDataChanged({'sizing/acceptableJitter/variable' : val})} /> - - - onQDataChanged({'sizing/acceptablePacketLoss' : val})} /> - + + +
    {i18n('Acceptable Jitter')}
    +
    + +
    {i18n('Allow Packet Loss')}
    +
    + + onQDataChanged({'sizing/acceptableJitter/mean' : val})} /> + + + onQDataChanged({'sizing/acceptableJitter/max' : val})} /> + + + onQDataChanged({'sizing/acceptableJitter/variable' : val})} /> + + + onQDataChanged({'sizing/acceptablePacketLoss' : val})} /> +
    ); }; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/NameAndPurpose.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/NameAndPurpose.jsx index bc692e753c..06a2bb445c 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/NameAndPurpose.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/NameAndPurpose.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Input from 'nfvo-components/input/validation/Input.jsx'; import GridSection from 'nfvo-components/grid/GridSection.jsx'; @@ -22,7 +23,7 @@ import GridItem from 'nfvo-components/grid/GridItem.jsx'; const NameAndPurpose = ({onDataChanged, genericFieldInfo, isReadOnlyMode, name, description, isManual}) => { return ( - + - + onDataChanged({description})} disabled={isReadOnlyMode} - type='textarea'/> + type='textarea' /> ); }; NameAndPurpose.PropTypes = { - name: React.PropTypes.string, - description: React.PropTypes.array, - onDataChanged: React.PropTypes.func, - isReadOnlyMode: React.PropTypes.bool, + name: PropTypes.string, + description: PropTypes.array, + onDataChanged: PropTypes.func, + isReadOnlyMode: PropTypes.bool, }; export default NameAndPurpose; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Network.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Network.jsx index 8d9b79e67f..7e6712cb5e 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Network.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Network.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Input from 'nfvo-components/input/validation/Input.jsx'; import GridSection from 'nfvo-components/grid/GridSection.jsx'; @@ -23,51 +24,53 @@ import { networkTypes } from '../SoftwareProductComponentsNetworkConstants.js'; const Network = ({networkValues, networkType, networkDescription, onDataChanged, isReadOnlyMode}) => { const isExternal = networkType === networkTypes.EXTERNAL; return ( - - - - - - - - - {isExternal ? + + + + + + + + + { + isExternal ? onDataChanged({networkDescription})} disabled={isReadOnlyMode} - type='text'/> - : + type='text' /> + : - {networkValues.map(val => )} - } - + disabled={true}> + {networkValues.map(val => )} + + } + ); }; Network.PropTypes = { - networkValues: React.PropTypes.array + networkValues: PropTypes.array }; export default Network; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/PacketsBytes.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/PacketsBytes.jsx index d7ee91bd15..f5f28aea59 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/PacketsBytes.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/PacketsBytes.jsx @@ -14,14 +14,15 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Input from 'nfvo-components/input/validation/Input.jsx'; import GridSection from 'nfvo-components/grid/GridSection.jsx'; import GridItem from 'nfvo-components/grid/GridItem.jsx'; -const PointerInput = ({label, value, onQDataChanged, qgenericFieldInfo, dataMap}) => { +const PointerInput = ({label, value, onQDataChanged, qgenericFieldInfo, dataMap, lastColInRow}) => { return ( - + { return( - +
    {i18n('Packets')}
    - +
    {i18n('Bytes')}
    - {pointers.map(pointer => {return ();})} + {pointers.map((pointer, i) => {return ();})}
    ); }; PacketsBytes.PropTypes = { - title: React.PropTypes.string, - pointers: React.PropTypes.array, - onQDataChanged: React.PropTypes.function, - dataMap: React.PropTypes.object, - qgenericFieldInfo: React.PropTypes.object + title: PropTypes.string, + pointers: PropTypes.array, + onQDataChanged: PropTypes.function, + dataMap: PropTypes.object, + qgenericFieldInfo: PropTypes.object }; export default PacketsBytes; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Protocols.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Protocols.jsx index 3e8a9f4e77..be4093da59 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Protocols.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Protocols.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Input from 'nfvo-components/input/validation/Input.jsx'; import InputOptions from 'nfvo-components/input/validation/InputOptions.jsx'; @@ -22,7 +23,7 @@ import GridItem from 'nfvo-components/grid/GridItem.jsx'; const Protocols = ({protocols, qgenericFieldInfo, dataMap, onQDataChanged}) => { return ( - + { clearable={false} values={qgenericFieldInfo['protocols/protocols'].enum}/> - + { }; Protocols.PropTypes = { - protocols: React.PropTypes.array, - onQDataChanged: React.PropTypes.function, - dataMap: React.PropTypes.object, - qgenericFieldInfo: React.PropTypes.object + protocols: PropTypes.array, + onQDataChanged: PropTypes.function, + dataMap: PropTypes.object, + qgenericFieldInfo: PropTypes.object }; export default Protocols; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Sizing.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Sizing.jsx index 1dd0045f7b..202d458f25 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Sizing.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/network/nicEditorComponents/Sizing.jsx @@ -21,8 +21,8 @@ import GridItem from 'nfvo-components/grid/GridItem.jsx'; const Sizing = ({qgenericFieldInfo, dataMap, onQDataChanged}) => { return( - - + + - { genericFieldInfo &&
    this.submit() } - onReset={ () => onCancel() } - isValid={this.props.isFormValid} - formReady={this.props.formReady} - onValidateForm={() => this.props.onValidateForm() } - className='vsp-processes-editor'> -
    - this.handleImportSubmit(acceptedFiles, rejectedFiles)} - onDragEnter={() => this.setState({dragging:true})} - onDragLeave={() => this.setState({dragging:false})} - multiple={false} - disableClick={true} - ref='processEditorFileInput' - name='processEditorFileInput'> - - - onDataChanged({name})} - isValid={genericFieldInfo.name.isValid} - isRequired={true} - data-test-id='name' - errorText={genericFieldInfo.name.errorText} - label={i18n('Name')} - value={name} - type='text'/> - - - this.refs.processEditorFileInput.open()} /> - - - - - onDataChanged({description})} - isValid={genericFieldInfo.description.isValid} - errorText={genericFieldInfo.description.errorText} - label={i18n('Notes')} - value={description} - data-test-id='vsp-process-description' - type='textarea'/> - - - - { - // setting the unit to the correct value - const selectedIndex = e.target.selectedIndex; - const val = e.target.options[selectedIndex].value; - onDataChanged({type: val});} - } - value={type} - label={i18n('Process Type')} - data-test-id='process-type' - isValid={genericFieldInfo.type.isValid} - errorText={genericFieldInfo.type.errorText} - type='select' - className='input-options-select' - groupClassName='bootstrap-input-options' > - {ComponentProcessesOptionsInputValues.PROCESS_TYPE.map(mtype => - )} - - - - -
    -
    } -
    + ); } - - submit() { - const {data: process, previousData: previousProcess} = this.props; - let {files} = this.state; - let formData = new FormData(); - if (files.length) { - let file = files[0]; - formData.append('upload', file); - } - - let updatedProcess = { - ...process, - formData: files.length ? formData : false - }; - this.props.onSubmit({process: updatedProcess, previousProcess}); - } - - - handleImportSubmit(files, rejectedFiles) { - if (files.length > 0) { - let {onDataChanged} = this.props; - this.setState({ - dragging: false, - complete: '0', - files - }); - onDataChanged({artifactName: files[0].name}); - } - else if (rejectedFiles.length > 0) { - this.setState({ - dragging: false - }); - if (DEBUG) { - console.log('file was rejected ' + rejectedFiles[0].name); - } - } - - } } export default SoftwareProductProcessesEditorView; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/processes/SoftwareProductComponentProcessesList.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/processes/SoftwareProductComponentProcessesList.js index 8c359db869..2a7152ef8b 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/processes/SoftwareProductComponentProcessesList.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/processes/SoftwareProductComponentProcessesList.js @@ -16,7 +16,6 @@ import {connect} from 'react-redux'; import i18n from 'nfvo-utils/i18n/i18n.js'; import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import SoftwareProductComponentProcessesActionHelper from './SoftwareProductComponentProcessesActionHelper.js'; import SoftwareProductComponentsProcessesListView from './SoftwareProductComponentsProcessesListView.jsx'; @@ -26,28 +25,26 @@ export const mapStateToProps = ({softwareProduct}) => { let {softwareProductEditor: {data:currentSoftwareProduct = {}, isValidityData = true}, softwareProductComponents: {componentProcesses = {}}} = softwareProduct; let{processesList = [], processesEditor = {}} = componentProcesses; let {data} = processesEditor; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); return { currentSoftwareProduct, isValidityData, processesList, isDisplayModal: Boolean(data), - isModalInEditMode: Boolean(data && data.id), - isReadOnlyMode + isModalInEditMode: Boolean(data && data.id) }; }; -const mapActionsToProps = (dispatch, {componentId, softwareProductId}) => { +const mapActionsToProps = (dispatch, {componentId, softwareProductId, version}) => { return { onAddProcess: () => SoftwareProductComponentProcessesActionHelper.openEditor(dispatch), - onEditProcessClick: (process) => SoftwareProductComponentProcessesActionHelper.openEditor(dispatch, process), - onDeleteProcessClick: (process, version) => dispatch({ + onEditProcess: (process) => SoftwareProductComponentProcessesActionHelper.openEditor(dispatch, process), + onDeleteProcess: (process) => dispatch({ type: modalActionTypes.GLOBAL_MODAL_WARNING, data:{ - msg: i18n(`Are you sure you want to delete "${process.name}"?`), + msg: i18n('Are you sure you want to delete "{name}"?', {name: process.name}), confirmationButtonText: i18n('Delete'), title: i18n('Delete'), onConfirmed: ()=> SoftwareProductComponentProcessesActionHelper.deleteProcess(dispatch, diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/processes/SoftwareProductComponentsProcessesListView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/processes/SoftwareProductComponentsProcessesListView.jsx index 93d5ce886a..27c4b9f429 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/processes/SoftwareProductComponentsProcessesListView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/processes/SoftwareProductComponentsProcessesListView.jsx @@ -14,13 +14,11 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Modal from 'nfvo-components/modal/Modal.jsx'; - -import ListEditorView from 'nfvo-components/listEditor/ListEditorView.jsx'; -import ListEditorItemView from 'nfvo-components/listEditor/ListEditorItemView.jsx'; - import SoftwareProductProcessesEditor from './SoftwareProductComponentProcessesEditor.js'; +import SoftwareProductProcessListView from 'sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessListView.jsx'; class SoftwareProductProcessesView extends React.Component { @@ -29,15 +27,15 @@ class SoftwareProductProcessesView extends React.Component { }; static propTypes = { - onAddProcess: React.PropTypes.func, - onEditProcessClick: React.PropTypes.func, - onDeleteProcessClick: React.PropTypes.func, - isDisplayModal: React.PropTypes.bool, - isModalInEditMode: React.PropTypes.bool, - onStorageSelect: React.PropTypes.func, - componentId: React.PropTypes.string, - softwareProductId: React.PropTypes.string, - currentSoftwareProduct: React.PropTypes.object + onAddProcess: PropTypes.func, + onEditProcess: PropTypes.func, + onDeleteProcess: PropTypes.func, + isDisplayModal: PropTypes.bool, + isModalInEditMode: PropTypes.bool, + onStorageSelect: PropTypes.func, + componentId: PropTypes.string, + softwareProductId: PropTypes.string, + currentSoftwareProduct: PropTypes.object }; render() { @@ -46,7 +44,7 @@ class SoftwareProductProcessesView extends React.Component {
    {this.renderEditor()} - {this.renderProcessList()} +
    @@ -54,7 +52,7 @@ class SoftwareProductProcessesView extends React.Component { } renderEditor() { - let {softwareProductId, currentSoftwareProduct: {version}, componentId, isReadOnlyMode, isDisplayModal, isModalInEditMode} = this.props; + let {softwareProductId, version, componentId, isReadOnlyMode, isDisplayModal, isModalInEditMode} = this.props; return ( @@ -72,66 +70,6 @@ class SoftwareProductProcessesView extends React.Component { ); } - renderProcessList() { - const {localFilter} = this.state; - let {onAddProcess, isReadOnlyMode} = this.props; - return ( -
    - this.setState({localFilter: value})}> - {this.filterList().map(processes => this.renderProcessListItem(processes, isReadOnlyMode))} - -
    - ); - } - - renderProcessListItem(process, isReadOnlyMode) { - let {id, name, description, artifactName = ''} = process; - let {currentSoftwareProduct: {version}, onEditProcessClick, onDeleteProcessClick} = this.props; - return ( - onEditProcessClick(process)} - onDelete={() => onDeleteProcessClick(process, version)}> - -
    -
    {i18n('Name')}
    -
    {name}
    -
    -
    -
    {i18n('Artifact name')}
    -
    {artifactName}
    -
    -
    -
    {i18n('Notes')}
    -
    {description}
    -
    -
    - ); - } - - - filterList() { - let {processesList} = this.props; - let {localFilter} = this.state; - if (localFilter.trim()) { - const filter = new RegExp(escape(localFilter), 'i'); - return processesList.filter(({name = '', description = ''}) => { - return escape(name).match(filter) || escape(description).match(filter); - }); - } - else { - return processesList; - } - } } export default SoftwareProductProcessesView; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/storage/SoftwareProductComponentStorage.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/storage/SoftwareProductComponentStorage.js index 7149adbbfb..ca27a76a18 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/storage/SoftwareProductComponentStorage.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/storage/SoftwareProductComponentStorage.js @@ -15,7 +15,6 @@ */ import {connect} from 'react-redux'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import ValidationHelper from 'sdc-app/common/helpers/ValidationHelper.js'; import SoftwareProductComponentsActionHelper from 'sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js'; @@ -23,26 +22,21 @@ import SoftwareProductComponentStorageView from './SoftwareProductComponentStora import {COMPONENTS_QUESTIONNAIRE} from '../SoftwareProductComponentsConstants.js'; -const mapStateToProps = ({softwareProduct}) => { - let {softwareProductEditor: {data: currentVSP}, softwareProductComponents} = softwareProduct; - let {componentEditor: {data: componentData , qdata, qgenericFieldInfo : qGenericFieldInfo, dataMap}} = softwareProductComponents; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentVSP); +const mapStateToProps = ({softwareProduct: {softwareProductComponents}}) => { + let {componentEditor: {qdata, qgenericFieldInfo : qGenericFieldInfo, dataMap}} = softwareProductComponents; return { - componentData, qdata, - isReadOnlyMode, qGenericFieldInfo, - dataMap, - version: currentVSP.version + dataMap }; }; -const mapActionToProps = (dispatch, {softwareProductId, componentId}) => { +const mapActionToProps = (dispatch, {softwareProductId, version, componentId}) => { return { onQDataChanged: (deltaData) => ValidationHelper.qDataChanged(dispatch, {deltaData, qName: COMPONENTS_QUESTIONNAIRE}), - onSubmit: ({componentData, qdata, version}) => { return SoftwareProductComponentsActionHelper.updateSoftwareProductComponent(dispatch, - {softwareProductId, version, vspComponentId: componentId, componentData, qdata}); + onSubmit: ({qdata}) => { + return SoftwareProductComponentsActionHelper.updateSoftwareProductComponentQuestionnaire(dispatch, {softwareProductId, version, vspComponentId: componentId, qdata}); } }; }; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/storage/SoftwareProductComponentStorageView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/storage/SoftwareProductComponentStorageView.jsx index 00df21bb59..8538dab6bc 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/storage/SoftwareProductComponentStorageView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/storage/SoftwareProductComponentStorageView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Input from 'nfvo-components/input/validation/Input.jsx'; import Form from 'nfvo-components/input/validation/Form.jsx'; @@ -155,14 +156,14 @@ const LogBackupSection = ({dataMap, onQDataChanged, qgenericFieldInfo}) => ( class SoftwareProductComponentStorageView extends React.Component { static propTypes = { - componentId: React.PropTypes.string, - onQDataChanged: React.PropTypes.func, - onSubmit: React.PropTypes.func, - isReadOnlyMode: React.PropTypes.bool + componentId: PropTypes.string, + onQDataChanged: PropTypes.func, + onSubmit: PropTypes.func, + isReadOnlyMode: PropTypes.bool }; render() { - let {onQDataChanged, dataMap, qGenericFieldInfo, isReadOnlyMode, onSubmit, qdata, version} = this.props; + let {onQDataChanged, dataMap, qGenericFieldInfo, isReadOnlyMode, onSubmit, qdata} = this.props; return(
    @@ -170,7 +171,7 @@ class SoftwareProductComponentStorageView extends React.Component { ref={form => this.form = form } isValid={true} formReady={null} - onSubmit={() => onSubmit({qdata, version})} + onSubmit={() => onSubmit({qdata})} className='component-questionnaire-validation-form' isReadOnlyMode={isReadOnlyMode} hasButtons={false}> @@ -183,8 +184,8 @@ class SoftwareProductComponentStorageView extends React.Component { } save(){ - const {componentData, qdata, onSubmit, version} = this.props; - return onSubmit({componentData, qdata, version}); + const {qdata, onSubmit} = this.props; + return onSubmit({qdata}); } } diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreation.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreation.js index 3b973c65cd..0136048bf7 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreation.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreation.js @@ -15,13 +15,17 @@ */ import {connect} from 'react-redux'; -import OnboardingActionHelper from 'sdc-app/onboarding/OnboardingActionHelper.js'; import SoftwareProductCreationActionHelper from './SoftwareProductCreationActionHelper.js'; import SoftwareProductCreationView from './SoftwareProductCreationView.jsx'; import ValidationHelper from 'sdc-app/common/helpers/ValidationHelper.js'; import SoftwareProductActionHelper from '../SoftwareProductActionHelper.js'; +import VersionsPageActionHelper from 'sdc-app/onboarding/versionsPage/VersionsPageActionHelper.js'; +import {itemTypes as versionItemTypes} from 'sdc-app/onboarding/versionsPage/VersionsPageConstants.js'; +import ScreensHelper from 'sdc-app/common/helpers/ScreensHelper.js'; +import {enums, screenTypes} from 'sdc-app/onboarding/OnboardingConstants.js'; +import PermissionsActionHelper from 'sdc-app/onboarding/permissions/PermissionsActionHelper.js'; -export const mapStateToProps = ({finalizedLicenseModelList, softwareProductList, softwareProduct: {softwareProductCreation, softwareProductCategories} }) => { +export const mapStateToProps = ({finalizedLicenseModelList, users: {usersList}, softwareProductList, softwareProduct: {softwareProductCreation, softwareProductCategories} }) => { let {genericFieldInfo} = softwareProductCreation; let isFormValid = ValidationHelper.checkFormValid(genericFieldInfo); @@ -39,7 +43,8 @@ export const mapStateToProps = ({finalizedLicenseModelList, softwareProductList, isFormValid, formReady: softwareProductCreation.formReady, genericFieldInfo, - VSPNames + VSPNames, + usersList }; }; @@ -47,13 +52,18 @@ export const mapActionsToProps = (dispatch) => { return { onDataChanged: (deltaData, formName, customValidations) => ValidationHelper.dataChanged(dispatch, {deltaData, formName, customValidations}), onCancel: () => SoftwareProductCreationActionHelper.resetData(dispatch), - onSubmit: (softwareProduct) => { + onSubmit: (softwareProduct, usersList) => { SoftwareProductCreationActionHelper.resetData(dispatch); SoftwareProductCreationActionHelper.createSoftwareProduct(dispatch, {softwareProduct}).then(response => { - SoftwareProductActionHelper.fetchSoftwareProductList(dispatch).then(() => { - let {vendorId: licenseModelId, licensingVersion} = softwareProduct; - OnboardingActionHelper.navigateToSoftwareProductLandingPage(dispatch, {softwareProductId: response.vspId, licenseModelId, licensingVersion}); - }); + let {itemId, version} = response; + SoftwareProductActionHelper.fetchSoftwareProductList(dispatch).then(() => + PermissionsActionHelper.fetchItemUsers(dispatch, {itemId, allUsers: usersList}).then(() => + VersionsPageActionHelper.fetchVersions(dispatch, {itemType: versionItemTypes.SOFTWARE_PRODUCT, itemId}).then(() => + ScreensHelper.loadScreen(dispatch, {screen: enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId: itemId, version}}) + ) + ) + ); }); }, onValidateForm: (formName) => ValidationHelper.validateForm(dispatch, formName) diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreationActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreationActionHelper.js index a22b517fa0..b19e460497 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreationActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreationActionHelper.js @@ -48,10 +48,10 @@ const SoftwareProductCreationActionHelper = { type: modalActionTypes.GLOBAL_MODAL_SHOW, data: { modalComponentName: modalContentMapper.SOFTWARE_PRODUCT_CREATION, - title: i18n('New Software Product'), + title: i18n('New Software Product'), modalComponentProps: { vendorId, - size: modalSizes.LARGE + size: modalSizes.LARGE } } }); @@ -70,7 +70,13 @@ const SoftwareProductCreationActionHelper = { }, createSoftwareProduct(dispatch, {softwareProduct}) { - return createSoftwareProduct(softwareProduct); + return createSoftwareProduct(softwareProduct).then(result => { + dispatch({ + type: actionTypes.SOFTWARE_PRODUCT_CREATED, + result + }); + return result; + }); } }; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreationConstants.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreationConstants.js index 241d7985b1..b941c849cb 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreationConstants.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreationConstants.js @@ -17,7 +17,8 @@ import keyMirror from 'nfvo-utils/KeyMirror.js'; export const actionTypes = keyMirror({ OPEN: null, - RESET_DATA: null + RESET_DATA: null, + SOFTWARE_PRODUCT_CREATED: null }); export const SP_CREATION_FORM_NAME = 'SPCREATIONFORM'; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreationView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreationView.jsx index c7ab3e644c..e491491f4d 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreationView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/creation/SoftwareProductCreationView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Validator from 'nfvo-utils/Validator.js'; import Input from 'nfvo-components/input/validation/Input.jsx'; @@ -27,25 +28,26 @@ import sortByStringProperty from 'nfvo-utils/sortByStringProperty.js'; import SoftwareProductCategoriesHelper from 'sdc-app/onboarding/softwareProduct/SoftwareProductCategoriesHelper.js'; import {onboardingMethod as onboardingMethodConst} from '../SoftwareProductConstants.js'; -const SoftwareProductPropType = React.PropTypes.shape({ - id: React.PropTypes.string, - name: React.PropTypes.string, - description: React.PropTypes.string, - category: React.PropTypes.string, - subCategory: React.PropTypes.string, - vendorId: React.PropTypes.string +const SoftwareProductPropType = PropTypes.shape({ + id: PropTypes.string, + name: PropTypes.string, + description: PropTypes.string, + category: PropTypes.string, + subCategory: PropTypes.string, + vendorId: PropTypes.string }); class SoftwareProductCreationView extends React.Component { static propTypes = { data: SoftwareProductPropType, - finalizedLicenseModelList: React.PropTypes.array, - softwareProductCategories: React.PropTypes.array, - VSPNames: React.PropTypes.object, - onDataChanged: React.PropTypes.func.isRequired, - onSubmit: React.PropTypes.func.isRequired, - onCancel: React.PropTypes.func.isRequired + finalizedLicenseModelList: PropTypes.array, + softwareProductCategories: PropTypes.array, + VSPNames: PropTypes.object, + usersList: PropTypes.array, + onDataChanged: PropTypes.func.isRequired, + onSubmit: PropTypes.func.isRequired, + onCancel: PropTypes.func.isRequired }; render() { @@ -65,7 +67,7 @@ class SoftwareProductCreationView extends React.Component { submitButtonText={i18n('Create')} formReady={this.props.formReady} onValidateForm={() => this.validate() }> - + - + { + sortByStringProperty(finalizedLicenseModelList, 'name').map(vendor => { return { enum: vendor.id, - title: vendor.vendorName + title: vendor.name }; }) ); @@ -163,9 +165,9 @@ class SoftwareProductCreationView extends React.Component { } submit() { - let {data:softwareProduct, finalizedLicenseModelList} = this.props; - softwareProduct.vendorName = finalizedLicenseModelList.find(vendor => vendor.id === softwareProduct.vendorId).vendorName; - this.props.onSubmit(softwareProduct); + let {data:softwareProduct, finalizedLicenseModelList, usersList} = this.props; + softwareProduct.vendorName = finalizedLicenseModelList.find(vendor => vendor.id === softwareProduct.vendorId).name; + this.props.onSubmit(softwareProduct, usersList); } validateName(value) { diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependencies.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependencies.js index 05a1fc7797..9888087800 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependencies.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependencies.js @@ -16,24 +16,21 @@ import {connect} from 'react-redux'; import SoftwareProductDependenciesView from './SoftwareProductDependenciesView.jsx'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import SoftwareProductDependenciesActionHelper from './SoftwareProductDependenciesActionHelper.js'; export const mapStateToProps = ({softwareProduct}) => { - let {softwareProductEditor: {data: currentSoftwareProduct = {}}, softwareProductDependencies, softwareProductComponents: {componentsList}} = softwareProduct; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); + let {softwareProductDependencies, softwareProductComponents: {componentsList}} = softwareProduct; return { - isReadOnlyMode, - softwareProductDependencies: softwareProductDependencies.length ? softwareProductDependencies : [{sourceId: '', targetId: '', relationType: 'dependsOn', id: 'fake'}], + softwareProductDependencies: softwareProductDependencies, componentsOptions: componentsList.map(component => ({value: component.id, label: component.displayName})) }; }; const mapActionsToProps = (dispatch, {softwareProductId, version}) => { return { - onDataChanged: dependenciesList => SoftwareProductDependenciesActionHelper.updateDependencyList(dispatch, {dependenciesList}), - onAddDependency: () => SoftwareProductDependenciesActionHelper.addDependency(dispatch), - onSubmit: (dependenciesList) => SoftwareProductDependenciesActionHelper.saveDependencies(dispatch, {softwareProductId, version, dependenciesList}) + onDataChanged: (item) => SoftwareProductDependenciesActionHelper.updateDependency(dispatch, {softwareProductId, version, item}), + onDeleteDependency: (item) => SoftwareProductDependenciesActionHelper.removeDependency(dispatch, {softwareProductId, version, item}), + onAddDependency: (item) => SoftwareProductDependenciesActionHelper.createDependency(dispatch, {softwareProductId, version, item}) }; }; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesActionHelper.js index e47b33a577..f04f8faf56 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesActionHelper.js @@ -15,44 +15,83 @@ */ import RestAPIUtil from 'nfvo-utils/RestAPIUtil.js'; import Configuration from 'sdc-app/config/Configuration.js'; -import {actionTypes} from './SoftwareProductDependenciesConstants.js'; -import uuid from 'uuid-js'; +import {actionTypes, NEW_RULE_TEMP_ID} from './SoftwareProductDependenciesConstants.js'; function baseUrl(softwareProductId, version) { const versionId = version.id; const restPrefix = Configuration.get('restPrefix'); - return `${restPrefix}/v1.0/vendor-software-products/${softwareProductId}/versions/${versionId}/component-dependency-model`; + return `${restPrefix}/v1.0/vendor-software-products/${softwareProductId}/versions/${versionId}/component-dependencies`; } -function fetchDependency(softwareProductId, version) { +function fetchDependencies(softwareProductId, version) { return RestAPIUtil.fetch(`${baseUrl(softwareProductId, version)}`); } -function postDependency(softwareProductId, version, dependenciesList) { - let modifedDependencyList = dependenciesList ? dependenciesList.filter(item => item.sourceId && item.targetId) - .map(item => ({sourceId: item.sourceId, targetId: item.targetId, relationType: item.relationType})) : []; - return RestAPIUtil.post(`${baseUrl(softwareProductId, version)}`, {componentDependencyModels:modifedDependencyList}); +function addDepencency(softwareProductId, version, item) { + return RestAPIUtil.post(`${baseUrl(softwareProductId, version)}`, { + sourceId: item.sourceId, + targetId: item.targetId, + relationType: item.relationType + }); } + +function updateDepencency(softwareProductId, version, item) { + return RestAPIUtil.put(`${baseUrl(softwareProductId, version)}/${item.id}`, + { + sourceId: item.sourceId, + targetId: item.targetId, + relationType: item.relationType + }); +} + +function removeDependency(softwareProductId, version, item) { + return RestAPIUtil.destroy(`${baseUrl(softwareProductId, version)}/${item.id}`); +} + + const SoftwareProductDependenciesActionHelper = { - updateDependencyList(dispatch, {dependenciesList}) { - dispatch({type: actionTypes.SOFTWARE_PRODUCT_DEPENDENCIES_LIST_UPDATE, dependenciesList}); + updateDependency(dispatch, {softwareProductId, version, item}) { + // if change was made on existing item - we will update the server and refresh the list + // if change was made on the 'new' row - we will only fire the event + if (item.id !== NEW_RULE_TEMP_ID) { + return updateDepencency(softwareProductId, version, item).then(() => { + return this.fetchDependencies(dispatch, {softwareProductId, version}); + }); + } else { + dispatch({ + type: actionTypes.UPDATE_NEW_SOFTWARE_PRODUCT_DEPENDENCY, + item: item + }); + } }, - addDependency(dispatch) { - dispatch({type: actionTypes.ADD_SOFTWARE_PRODUCT_DEPENDENCY}); + + createDependency(dispatch, {softwareProductId, version, item}) { + // removing the temp id + delete item.id; + // creating the new dependency + return addDepencency(softwareProductId, version, item).then(() => { + dispatch({ + type: actionTypes.ADD_SOFTWARE_PRODUCT_DEPENDENCY + }); + return this.fetchDependencies(dispatch, {softwareProductId, version}); + }); }, + + removeDependency(dispatch, {softwareProductId, version, item}) { + return removeDependency(softwareProductId, version, item).then( () => { + return this.fetchDependencies(dispatch, {softwareProductId, version}); + }); + }, + fetchDependencies(dispatch, {softwareProductId, version}) { - return fetchDependency(softwareProductId, version).then( response => { - const dependenciesList = response.results ? response.results.map(item => {return {...item, id: uuid.create().toString()};}) : []; + return fetchDependencies(softwareProductId, version).then( response => { dispatch({ type: actionTypes.SOFTWARE_PRODUCT_DEPENDENCIES_LIST_UPDATE, - dependenciesList + dependenciesList : response.results }); }); - }, - saveDependencies(dispatch, {softwareProductId, version, dependenciesList}) { - return postDependency(softwareProductId, version, dependenciesList); - } + } }; export default SoftwareProductDependenciesActionHelper; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesConstants.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesConstants.js index 1f27ed8311..c25561da17 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesConstants.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesConstants.js @@ -17,7 +17,8 @@ import keyMirror from 'nfvo-utils/KeyMirror.js'; export const actionTypes = keyMirror({ SOFTWARE_PRODUCT_DEPENDENCIES_LIST_UPDATE: null, - ADD_SOFTWARE_PRODUCT_DEPENDENCY: null + ADD_SOFTWARE_PRODUCT_DEPENDENCY: null, + UPDATE_NEW_SOFTWARE_PRODUCT_DEPENDENCY: null }); export const relationTypes = { @@ -27,3 +28,5 @@ export const relationTypes = { export const relationTypesOptions = [ {value: relationTypes.DEPENDS_ON, label: 'Depends On'} ]; + +export const NEW_RULE_TEMP_ID = 'newRuleTempId'; \ No newline at end of file diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesReducer.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesReducer.js index 3fb479eedc..3edd3b899a 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesReducer.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesReducer.js @@ -15,21 +15,31 @@ * permissions and limitations under the License. */ -import {actionTypes, relationTypes} from './SoftwareProductDependenciesConstants.js'; +import {actionTypes, relationTypes, NEW_RULE_TEMP_ID} from './SoftwareProductDependenciesConstants.js'; import {checkCyclesAndMarkDependencies} from './SoftwareProductDependenciesUtils.js'; -import uuid from 'uuid-js'; -export default (state = [], action) => { +let newRowObject = {id: NEW_RULE_TEMP_ID, targetId: null, sourceId: null, relationType: relationTypes.DEPENDS_ON}; + +export default (state = [Object.assign({}, newRowObject) ], action) => { switch (action.type) { case actionTypes.SOFTWARE_PRODUCT_DEPENDENCIES_LIST_UPDATE: + // copying the entity with the data for the row that is in the 'add' mode + let newDependency = state.find(dependency => dependency.id === NEW_RULE_TEMP_ID); + action.dependenciesList.push(newDependency); + // returning list from the server with our 'new entity' row return checkCyclesAndMarkDependencies(action.dependenciesList); - case actionTypes.ADD_SOFTWARE_PRODUCT_DEPENDENCY: - return [...state, { - sourceId: null, - relationType: relationTypes.DEPENDS_ON, - targetId: null, - id: uuid.create() - }]; + case actionTypes.ADD_SOFTWARE_PRODUCT_DEPENDENCY : + // resetting the entity with the data for the 'add' mode for a new entity + let newArray = state.filter(dependency => dependency.id !== NEW_RULE_TEMP_ID); + newArray.push(Object.assign({}, newRowObject)); + return newArray; + case actionTypes.UPDATE_NEW_SOFTWARE_PRODUCT_DEPENDENCY : + // we really only need this for the 'new' row since we need to change the state to get + // everything updated + let updateArrayIndex = state.findIndex(dependency => dependency.id === NEW_RULE_TEMP_ID); + let updateArray = state.slice(); + updateArray.splice(updateArrayIndex, 1, action.item); + return checkCyclesAndMarkDependencies(updateArray); default: return state; } diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesView.jsx index a427470a4f..ed92de7bb1 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesView.jsx @@ -20,7 +20,42 @@ import i18n from 'nfvo-utils/i18n/i18n.js'; import SelectActionTable from 'nfvo-components/table/SelectActionTable.jsx'; import SelectActionTableRow from 'nfvo-components/table/SelectActionTableRow.jsx'; import SelectActionTableCell from 'nfvo-components/table/SelectActionTableCell.jsx'; -import {relationTypesOptions} from './SoftwareProductDependenciesConstants.js'; +import {relationTypesOptions, NEW_RULE_TEMP_ID} from './SoftwareProductDependenciesConstants.js'; + + +const TableActionRow = ({onAction, actionIcon, showAction, dependency, sourceOptions, targetOptions, onDataChanged}) => { + return ( + + { + dependency.sourceId = newVal; + onDataChanged(dependency); + }} /> + + { + dependency.targetId = newVal; + onDataChanged(dependency); + }} /> + + ); +}; + export default class SoftwareProductDependenciesView extends React.Component { filterTargets({componentsOptions, sourceToTargetMapping, selectedSourceId, selectedTargetId}) { @@ -46,8 +81,7 @@ export default class SoftwareProductDependenciesView extends React.Component { } render() { - let {componentsOptions, softwareProductDependencies, onDataChanged, onAddDependency, isReadOnlyMode} = this.props; - let canAdd = softwareProductDependencies.length < componentsOptions.length * (componentsOptions.length - 1); + let {componentsOptions, softwareProductDependencies, onDataChanged, onAddDependency, onDeleteDependency, isReadOnlyMode} = this.props; let sourceToTargetMapping = {}; softwareProductDependencies.map(dependency => { let isInMap = sourceToTargetMapping.hasOwnProperty(dependency.sourceId); @@ -55,47 +89,42 @@ export default class SoftwareProductDependenciesView extends React.Component { sourceToTargetMapping[dependency.sourceId] = isInMap ? [...sourceToTargetMapping[dependency.sourceId], dependency.targetId] : [dependency.targetId]; } }); + let depList = softwareProductDependencies.filter(dependency => dependency.id !== NEW_RULE_TEMP_ID); + let newDependency = softwareProductDependencies.find(dependency => dependency.id === NEW_RULE_TEMP_ID); return (
    -
    {i18n('Dependencies')}
    +
    {i18n('Dependencies')}
    - {softwareProductDependencies.map(dependency => ( - + {!isReadOnlyMode && onAddDependency(newDependency)} + dependency={newDependency} + componentsOptions={componentsOptions} + sourceToTargetMapping={sourceToTargetMapping} + onDataChanged={onDataChanged} + sourceOptions={this.filterSources({componentsOptions, sourceToTargetMapping, selectedSourceId: newDependency.sourceId, selectedTargetId: newDependency.targetId})} + targetOptions={this.filterTargets({componentsOptions, sourceToTargetMapping, selectedSourceId: newDependency.sourceId, selectedTargetId: newDependency.targetId})} + showAction={newDependency.targetId !== null && newDependency.relationType !== null && newDependency.sourceId !== null}/> } + {depList.map(dependency => ( + onDataChanged(softwareProductDependencies.filter(currentDependency => currentDependency.id !== dependency.id))} - overlayMsg={i18n('There is a loop between selections')} - hasError={dependency.hasCycle} - hasErrorIndication - showDelete={dependency.id !== 'fake' || dependency.hasCycle !== undefined}> - onDataChanged(softwareProductDependencies.map(currentDependency => - ({...currentDependency, sourceId: currentDependency.id === dependency.id ? newSourceId : currentDependency.sourceId}) - ))} /> - - onDataChanged(softwareProductDependencies.map(currentDependency => - ({...currentDependency, targetId: currentDependency.id === dependency.id ? newTargetId : currentDependency.targetId}) - ))} /> - + actionIcon='trashO' + onAction={() => onDeleteDependency(dependency)} + dependency={dependency} + componentsOptions={componentsOptions} + sourceToTargetMapping={sourceToTargetMapping} + sourceOptions={this.filterSources({componentsOptions, sourceToTargetMapping, selectedSourceId: dependency.sourceId, selectedTargetId: dependency.targetId})} + targetOptions={this.filterTargets({componentsOptions, sourceToTargetMapping, selectedSourceId: dependency.sourceId, selectedTargetId: dependency.targetId})} + onDataChanged={onDataChanged} + showAction={true}/> ))}
    ); } - save() { - let {onSubmit, softwareProductDependencies} = this.props; - return onSubmit(softwareProductDependencies); - } } diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/SoftwareProductDeployment.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/SoftwareProductDeployment.js index 98f773b465..a5c70068b0 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/SoftwareProductDeployment.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/SoftwareProductDeployment.js @@ -18,13 +18,10 @@ import SoftwareProductDeploymentView from './SoftwareProductDeploymentView.jsx'; import SoftwareProductDeploymentActionHelper from './SoftwareProductDeploymentActionHelper.js'; import i18n from 'nfvo-utils/i18n/i18n.js'; import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; export function mapStateToProps({softwareProduct}) { - let {softwareProductEditor: {data: currentSoftwareProduct = {}},softwareProductComponents: {componentsList}, softwareProductDeployment: {deploymentFlavors}} = softwareProduct; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); + let {softwareProductComponents: {componentsList}, softwareProductDeployment: {deploymentFlavors}} = softwareProduct; return { - isReadOnlyMode, deploymentFlavors, componentsList }; @@ -37,7 +34,7 @@ function mapActionToProps(dispatch, {softwareProductId, version}) { onDeleteDeployment: ({id, model}) => dispatch({ type: modalActionTypes.GLOBAL_MODAL_WARNING, data:{ - msg: i18n(`Are you sure you want to delete "${model}"?`), + msg: i18n('Are you sure you want to delete "{model}"?', {model: model}), onConfirmed: () => SoftwareProductDeploymentActionHelper.deleteDeploymentFlavor(dispatch, {softwareProductId, deploymentFlavorId: id, version}) } }), diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/SoftwareProductDeploymentView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/SoftwareProductDeploymentView.jsx index 81477ecff7..860d02c343 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/SoftwareProductDeploymentView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/SoftwareProductDeploymentView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import ListEditorView from 'nfvo-components/listEditor/ListEditorView.jsx'; @@ -26,10 +27,10 @@ export default class SoftwareProductDeployment extends React.Component { }; static propTypes = { - onAddDeployment: React.PropTypes.func.isRequired, - onDeleteDeployment: React.PropTypes.func.isRequired, - onEditDeployment: React.PropTypes.func.isRequired, - isReadOnlyMode: React.PropTypes.bool.isRequired + onAddDeployment: PropTypes.func.isRequired, + onDeleteDeployment: PropTypes.func.isRequired, + onEditDeployment: PropTypes.func.isRequired, + isReadOnlyMode: PropTypes.bool.isRequired }; render() { diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/editor/SoftwareProductDeploymentEditor.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/editor/SoftwareProductDeploymentEditor.js index ba00d4e56e..c24548b7b9 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/editor/SoftwareProductDeploymentEditor.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/editor/SoftwareProductDeploymentEditor.js @@ -16,12 +16,14 @@ import {connect} from 'react-redux'; import SoftwareProductDeploymentEditorView from './SoftwareProductDeploymentEditorView.jsx'; import SoftwareProdcutDeploymentActionHelper from '../SoftwareProductDeploymentActionHelper.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import ValidationHelper from 'sdc-app/common/helpers/ValidationHelper.js'; - import {DEPLOYMENT_FLAVORS_FORM_NAME} from '../SoftwareProductDeploymentConstants.js'; -export function mapStateToProps({licenseModel, softwareProduct}) { +export function mapStateToProps({ + licenseModel, + softwareProduct, + currentScreen: {props: {isReadOnlyMode}} +}) { let { softwareProductEditor: { data: currentSoftwareProduct = {} @@ -48,7 +50,6 @@ export function mapStateToProps({licenseModel, softwareProduct}) { } } = licenseModel; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); let isFormValid = ValidationHelper.checkFormValid(genericFieldInfo); let selectedFeatureGroupsIds = currentSoftwareProduct.licensingData ? currentSoftwareProduct.licensingData.featureGroups || [] : []; let selectedFeatureGroupsList = featureGroupsList diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/editor/SoftwareProductDeploymentEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/editor/SoftwareProductDeploymentEditorView.jsx index 2d621cd2f5..7c9ae438d9 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/editor/SoftwareProductDeploymentEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/deployment/editor/SoftwareProductDeploymentEditorView.jsx @@ -29,7 +29,7 @@ export default class SoftwareProductDeploymentEditorView extends React.Component isValid={this.props.isFormValid} formReady={this.props.formReady} className='vsp-deployment-editor'> - + onDataChanged({model}, {model: model => this.validateName(model)})} @@ -41,7 +41,7 @@ export default class SoftwareProductDeploymentEditorView extends React.Component isRequired={true} type='text'/> - + onDataChanged({description})} label={i18n('Description')} @@ -52,7 +52,7 @@ export default class SoftwareProductDeploymentEditorView extends React.Component type='text'/> - + {i18n('Please assign Feature Groups in VSP General')} } - - + + diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/details/SoftwareProductDetails.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/details/SoftwareProductDetails.js index ac0282e593..b7ddf134bb 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/details/SoftwareProductDetails.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/details/SoftwareProductDetails.js @@ -15,19 +15,24 @@ */ import {connect} from 'react-redux'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import SoftwareProductActionHelper from 'sdc-app/onboarding/softwareProduct/SoftwareProductActionHelper.js'; import SoftwareProductDetailsView from './SoftwareProductDetailsView.jsx'; import ValidationHelper from 'sdc-app/common/helpers/ValidationHelper.js'; import {PRODUCT_QUESTIONNAIRE} from 'sdc-app/onboarding/softwareProduct/SoftwareProductConstants.js'; -export const mapStateToProps = ({finalizedLicenseModelList, softwareProduct, licenseModel: {licenseAgreement, featureGroup}}) => { - let {softwareProductEditor: {data: currentSoftwareProduct, genericFieldInfo}, softwareProductCategories, softwareProductQuestionnaire} = softwareProduct; +export const mapStateToProps = ({ + finalizedLicenseModelList, + softwareProduct, + licenseModel: {licenseAgreement, featureGroup} +}) => { + + let {softwareProductEditor: {data: currentSoftwareProduct, licensingVersionsList = [], genericFieldInfo}, softwareProductCategories, softwareProductQuestionnaire} = softwareProduct; let {licensingData = {}, licensingVersion} = currentSoftwareProduct; let licenseAgreementList = [], filteredFeatureGroupsList = []; - licenseAgreementList = licenseAgreement.licenseAgreementList; - if(licensingVersion && licensingVersion !== '' && licensingData && licensingData.licenseAgreement) { + licenseAgreementList = licensingVersion ? + licenseAgreement.licenseAgreementList : []; + if(licensingVersion && licensingData && licensingData.licenseAgreement) { let selectedLicenseAgreement = licenseAgreementList.find(la => la.id === licensingData.licenseAgreement); if (selectedLicenseAgreement) { let featureGroupsList = featureGroup.featureGroupsList.filter(({referencingLicenseAgreements}) => referencingLicenseAgreements.includes(selectedLicenseAgreement.id)); @@ -37,7 +42,6 @@ export const mapStateToProps = ({finalizedLicenseModelList, softwareProduct, lic } } let {qdata, qgenericFieldInfo : qGenericFieldInfo, dataMap} = softwareProductQuestionnaire; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); let isFormValid = ValidationHelper.checkFormValid(genericFieldInfo); @@ -45,24 +49,25 @@ export const mapStateToProps = ({finalizedLicenseModelList, softwareProduct, lic currentSoftwareProduct, softwareProductCategories, licenseAgreementList, + licensingVersionsList, featureGroupsList: filteredFeatureGroupsList, finalizedLicenseModelList, qdata, - isReadOnlyMode, isFormValid, genericFieldInfo, qGenericFieldInfo, dataMap }; + }; -export const mapActionsToProps = (dispatch) => { +export const mapActionsToProps = (dispatch, {version}) => { return { onDataChanged: (deltaData, formName) => ValidationHelper.dataChanged(dispatch, {deltaData, formName}), onVendorParamChanged: (deltaData, formName) => SoftwareProductActionHelper.softwareProductEditorVendorChanged(dispatch, {deltaData, formName}), onQDataChanged: (deltaData) => ValidationHelper.qDataChanged(dispatch, {deltaData, qName: PRODUCT_QUESTIONNAIRE}), onValidityChanged: isValidityData => SoftwareProductActionHelper.setIsValidityData(dispatch, {isValidityData}), - onSubmit: (softwareProduct, qdata) =>{ return SoftwareProductActionHelper.updateSoftwareProduct(dispatch, {softwareProduct, qdata});} + onSubmit: (softwareProduct, qdata) => SoftwareProductActionHelper.updateSoftwareProduct(dispatch, {softwareProduct, qdata, version}) }; }; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/details/SoftwareProductDetailsReducer.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/details/SoftwareProductDetailsReducer.js index d62207ff9f..54dc1a4d37 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/details/SoftwareProductDetailsReducer.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/details/SoftwareProductDetailsReducer.js @@ -45,6 +45,11 @@ export default (state = {}, action) => { ...state, mapOfExpandedIds: action.mapOfExpandedIds }; + case actionTypes.LOAD_LICENSING_VERSIONS_LIST: + return { + ...state, + licensingVersionsList: action.licensingVersionsList + }; default: return state; } diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/details/SoftwareProductDetailsView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/details/SoftwareProductDetailsView.jsx index e4caf92c21..f6199ec83e 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/details/SoftwareProductDetailsView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/details/SoftwareProductDetailsView.jsx @@ -13,7 +13,8 @@ * or implied. See the License for the specific language governing * permissions and limitations under the License. */ -import React, {Component, PropTypes} from 'react'; +import React, {Component} from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import sortByStringProperty from 'nfvo-utils/sortByStringProperty.js'; @@ -55,7 +56,7 @@ class GeneralSection extends React.Component { let {genericFieldInfo} = this.props; return (
    - {genericFieldInfo && + {genericFieldInfo && this.onVendorParamChanged(e)}> {sortByStringProperty( this.props.finalizedLicenseModelList, - 'vendorName' - ).map(lm => ) + 'name' + ).map(lm => ) } this.onVendorParamChanged(e)} - value={this.props.licensingVersion ? this.props.licensingVersion.id : ''} + value={this.props.licensingVersion || ''} label={i18n('Licensing Version')} type='select'> {this.props.licensingVersionsList.map(version => @@ -196,6 +197,7 @@ const AvailabilitySection = (props) => ( data-test-id='vsp-use-availability-zone' label={i18n('Use Availability Zones for High Availability')} type='checkbox' + checked={props.dataMap['general/availability/useAvailabilityZonesForHighAvailability']} value={props.dataMap['general/availability/useAvailabilityZonesForHighAvailability']} onChange={(aZone) => props.onQDataChanged({'general/availability/useAvailabilityZonesForHighAvailability' : aZone})} /> @@ -274,7 +276,7 @@ class SoftwareProductDetails extends Component { subCategory: PropTypes.string, vendorId: PropTypes.string, vendorName: PropTypes.string, - licensingVersion: PropTypes.object, + licensingVersion: PropTypes.string, licensingData: PropTypes.shape({ licenceAgreement: PropTypes.string, featureGroups: PropTypes.array @@ -292,10 +294,6 @@ class SoftwareProductDetails extends Component { onVendorParamChanged: PropTypes.func.isRequired }; - state = { - licensingVersionsList: [] - }; - prepareDataForGeneralSection(){ let {softwareProductCategories, finalizedLicenseModelList, onDataChanged, currentSoftwareProduct, genericFieldInfo} = this.props; let {name, description, vendorId, subCategory} = currentSoftwareProduct; @@ -317,12 +315,11 @@ class SoftwareProductDetails extends Component { prepareDataForLicensesSection(){ let { featureGroupsList, licenseAgreementList, currentSoftwareProduct } = this.props; let {vendorId, licensingVersion, licensingData = {}} = currentSoftwareProduct; - let licensingVersionsList = this.state.licensingVersionsList.length > 0 ? this.state.licensingVersionsList : this.refreshVendorVersionsList(vendorId); return { onVendorParamChanged: args => this.onVendorParamChanged(args), vendorId, licensingVersion, - licensingVersionsList, + licensingVersionsList: this.buildLicensingVersionsListItems(), licensingData, onFeatureGroupsChanged: args => this.onFeatureGroupsChanged(args), onLicensingDataChanged: args => this.onLicensingDataChanged(args), @@ -361,10 +358,10 @@ class SoftwareProductDetails extends Component { onVendorParamChanged({vendorId, licensingVersion}) { let {finalizedLicenseModelList, onVendorParamChanged} = this.props; if(!licensingVersion) { - const licensingVersionsList = this.refreshVendorVersionsList(vendorId); - licensingVersion = licensingVersionsList.length > 0 ? licensingVersionsList[0].enum : ''; + const licensingVersionsList = this.buildLicensingVersionsListItems(); + licensingVersion = licensingVersionsList[0].enum; } - let vendorName = finalizedLicenseModelList.find(licenseModelItem => licenseModelItem.id === vendorId).vendorName || ''; + let vendorName = finalizedLicenseModelList.find(licenseModelItem => licenseModelItem.id === vendorId).name || ''; let deltaData = { vendorId, vendorName, @@ -376,25 +373,15 @@ class SoftwareProductDetails extends Component { } - refreshVendorVersionsList(vendorId) { - if(!vendorId) { - return []; - } + buildLicensingVersionsListItems() { + let {licensingVersionsList} = this.props; - let {finalVersions} = this.props.finalizedLicenseModelList.find(vendor => vendor.id === vendorId); - - let licensingVersionsList = [{ + let licensingVersionsListItems = [{ enum: '', title: i18n('Select...') }]; - if(finalVersions) { - finalVersions.forEach(version => licensingVersionsList.push({ - enum: version.id, - title: version.label - })); - } - return licensingVersionsList; + return licensingVersionsListItems.concat(licensingVersionsList.map(version => ({enum: version.id, title: version.name}))); } onFeatureGroupsChanged({featureGroups}) { diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPage.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPage.js index a13e742006..90ea182dfa 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPage.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPage.js @@ -15,14 +15,18 @@ */ import {connect} from 'react-redux'; import i18n from 'nfvo-utils/i18n/i18n.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; -import OnboardingActionHelper from 'sdc-app/onboarding/OnboardingActionHelper.js'; import SoftwareProductActionHelper from 'sdc-app/onboarding/softwareProduct/SoftwareProductActionHelper.js'; import LandingPageView from './SoftwareProductLandingPageView.jsx'; import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; import {onboardingMethod} from '../SoftwareProductConstants.js'; +import ScreensHelper from 'sdc-app/common/helpers/ScreensHelper.js'; +import {enums, screenTypes} from 'sdc-app/onboarding/OnboardingConstants.js'; -export const mapStateToProps = ({softwareProduct, licenseModel: {licenseAgreement}}) => { + +export const mapStateToProps = ({ + softwareProduct, + licenseModel: {licenseAgreement}, +}) => { let {softwareProductEditor: {data:currentSoftwareProduct = {}}, softwareProductComponents, softwareProductCategories = []} = softwareProduct; let {licensingData = {}} = currentSoftwareProduct; let {licenseAgreementList} = licenseAgreement; @@ -44,7 +48,6 @@ export const mapStateToProps = ({softwareProduct, licenseModel: {licenseAgreemen } fullCategoryDisplayName = `${subCategoryName} (${categoryName})`; - const isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); return { currentSoftwareProduct: { @@ -52,7 +55,6 @@ export const mapStateToProps = ({softwareProduct, licenseModel: {licenseAgreemen licenseAgreementName, fullCategoryDisplayName }, - isReadOnlyMode, componentsList, isManual: currentSoftwareProduct.onboardingMethod === onboardingMethod.MANUAL }; @@ -60,11 +62,12 @@ export const mapStateToProps = ({softwareProduct, licenseModel: {licenseAgreemen const mapActionsToProps = (dispatch, {version}) => { return { - onDetailsSelect: ({id: softwareProductId, vendorId: licenseModelId, version}) => OnboardingActionHelper.navigateToSoftwareProductDetails(dispatch, { - softwareProductId, - licenseModelId, - version - }), + onDetailsSelect: ({id: softwareProductId}) => + ScreensHelper.loadScreen(dispatch, { + screen: enums.SCREEN.SOFTWARE_PRODUCT_DETAILS, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, version} + }), + onUpload: (softwareProductId, formData) => SoftwareProductActionHelper.uploadFile(dispatch, { softwareProductId, @@ -100,9 +103,10 @@ const mapActionsToProps = (dispatch, {version}) => { msg: i18n('no zip or csar file was uploaded or expected file doesn\'t exist') } }), - onComponentSelect: ({id: softwareProductId, componentId}) => { - OnboardingActionHelper.navigateToSoftwareProductComponentGeneralAndUpdateLeftPanel(dispatch, {softwareProductId, componentId, version }); - }, + onComponentSelect: ({id: softwareProductId, componentId}) => ScreensHelper.loadScreen(dispatch, { + screen: screenTypes.SOFTWARE_PRODUCT_COMPONENT_DEFAULT_GENERAL, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId, version, componentId} + }), /** for the next version */ onAddComponent: () => SoftwareProductActionHelper.addComponent(dispatch) }; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPageView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPageView.jsx index 72a416473c..56402b4417 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPageView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPageView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import classnames from 'classnames'; import Dropzone from 'react-dropzone'; @@ -22,25 +23,25 @@ import i18n from 'nfvo-utils/i18n/i18n.js'; import DraggableUploadFileBox from 'nfvo-components/fileupload/DraggableUploadFileBox.jsx'; import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; -import SoftwareProductComponentsList from '../components/SoftwareProductComponentsList.js'; - -const SoftwareProductPropType = React.PropTypes.shape({ - name: React.PropTypes.string, - description: React.PropTypes.string, - version: React.PropTypes.object, - id: React.PropTypes.string, - categoryId: React.PropTypes.string, - vendorId: React.PropTypes.string, - status: React.PropTypes.string, - licensingData: React.PropTypes.object, - validationData: React.PropTypes.object +import SoftwareProductComponentsList from 'sdc-app/onboarding/softwareProduct/components/SoftwareProductComponents.js'; + +const SoftwareProductPropType = PropTypes.shape({ + name: PropTypes.string, + description: PropTypes.string, + version: PropTypes.object, + id: PropTypes.string, + categoryId: PropTypes.string, + vendorId: PropTypes.string, + status: PropTypes.string, + licensingData: PropTypes.object, + validationData: PropTypes.object }); -const ComponentPropType = React.PropTypes.shape({ - id: React.PropTypes.string, - name: React.PropTypes.string, - displayName: React.PropTypes.string, - description: React.PropTypes.string +const ComponentPropType = PropTypes.shape({ + id: PropTypes.string, + name: PropTypes.string, + displayName: PropTypes.string, + description: PropTypes.string }); class SoftwareProductLandingPageView extends React.Component { @@ -54,18 +55,19 @@ class SoftwareProductLandingPageView extends React.Component { static propTypes = { currentSoftwareProduct: SoftwareProductPropType, - isReadOnlyMode: React.PropTypes.bool, - componentsList: React.PropTypes.arrayOf(ComponentPropType), - onDetailsSelect: React.PropTypes.func, - onUpload: React.PropTypes.func, - onUploadConfirmation: React.PropTypes.func, - onInvalidFileSizeUpload: React.PropTypes.func, - onComponentSelect: React.PropTypes.func, - onAddComponent: React.PropTypes.func + isReadOnlyMode: PropTypes.bool, + componentsList: PropTypes.arrayOf(ComponentPropType), + version: PropTypes.object, + onDetailsSelect: PropTypes.func, + onUpload: PropTypes.func, + onUploadConfirmation: PropTypes.func, + onInvalidFileSizeUpload: PropTypes.func, + onComponentSelect: PropTypes.func, + onAddComponent: PropTypes.func }; render() { - let {currentSoftwareProduct, isReadOnlyMode, isManual, onDetailsSelect, componentsList} = this.props; + let {currentSoftwareProduct, isReadOnlyMode, isManual, onDetailsSelect} = this.props; return (
    - +
    ); } diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/networks/SoftwareProductNetworksView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/networks/SoftwareProductNetworksView.jsx index 024c5cc44c..e8c365f124 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/networks/SoftwareProductNetworksView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/networks/SoftwareProductNetworksView.jsx @@ -14,6 +14,7 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import ListEditorView from 'nfvo-components/listEditor/ListEditorView.jsx'; @@ -23,11 +24,12 @@ import ListEditorItemViewField from 'nfvo-components/listEditor/ListEditorItemVi class SoftwareProductNetworksView extends React.Component { static propTypes = { - networksList: React.PropTypes.arrayOf(React.PropTypes.shape({ - id: React.PropTypes.string.isRequired, - name: React.PropTypes.string.isRequired, - dhcp: React.PropTypes.bool.isRequired - })).isRequired + networksList: PropTypes.arrayOf(PropTypes.shape({ + id: PropTypes.string.isRequired, + name: PropTypes.string.isRequired, + dhcp: PropTypes.bool.isRequired + })).isRequired, + isReadOnlyMode: PropTypes.bool.isRequired }; state = { @@ -36,6 +38,7 @@ class SoftwareProductNetworksView extends React.Component { render() { const {localFilter} = this.state; + const {isReadOnlyMode} = this.props; return (
    @@ -45,19 +48,19 @@ class SoftwareProductNetworksView extends React.Component { placeholder={i18n('Filter Networks')} onFilter={value => this.setState({localFilter: value})} twoColumns> - {this.filterList().map(network => this.renderNetworksListItem(network))} + {this.filterList().map(network => this.renderNetworksListItem({network, isReadOnlyMode}))}
    ); } - renderNetworksListItem(network) { + renderNetworksListItem({network, isReadOnlyMode}) { let {id, name, dhcp} = network; return ( + isReadOnlyMode={isReadOnlyMode}>
    {name}
    diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessListView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessListView.jsx new file mode 100644 index 0000000000..aa39c87dd0 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessListView.jsx @@ -0,0 +1,99 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import React from 'react'; +import PropTypes from 'prop-types'; +import i18n from 'nfvo-utils/i18n/i18n.js'; + +import ListEditorView from 'nfvo-components/listEditor/ListEditorView.jsx'; +import ListEditorItemView from 'nfvo-components/listEditor/ListEditorItemView.jsx'; + + +class SoftwareProductProcessesListView extends React.Component { + + state = { + localFilter: '' + }; + + static propTypes = { + onAddProcess: PropTypes.func.isRequired, + onEditProcess: PropTypes.func.isRequired, + onDeleteProcess: PropTypes.func.isRequired, + isReadOnlyMode: PropTypes.bool.isRequired, + currentSoftwareProduct:PropTypes.object, + addButtonTitle: PropTypes.string + }; + + render() { + const {localFilter} = this.state; + let {onAddProcess, isReadOnlyMode, addButtonTitle} = this.props; + + return ( + this.setState({localFilter: value})}> + {this.filterList().map(processes => this.renderProcessListItem(processes, isReadOnlyMode))} + ); + } + + renderProcessListItem(process, isReadOnlyMode) { + let {id, name, description, artifactName = ''} = process; + let {currentSoftwareProduct: {version}, onEditProcess, onDeleteProcess} = this.props; + return ( + onEditProcess(process)} + onDelete={() => onDeleteProcess(process, version)}> + +
    +
    {i18n('Name')}
    +
    {name}
    +
    +
    +
    {i18n('Artifact name')}
    +
    {artifactName}
    +
    +
    +
    {i18n('Notes')}
    +
    {description}
    +
    +
    + ); + } + + filterList() { + let {processesList} = this.props; + let {localFilter} = this.state; + + if (localFilter.trim()) { + const filter = new RegExp(escape(localFilter), 'i'); + return processesList.filter(({name = '', description = ''}) => { + return escape(name).match(filter) || escape(description).match(filter); + }); + } + else { + return processesList; + } + } +} + +export default SoftwareProductProcessesListView; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcesses.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcesses.js index c70452919b..b0403abde5 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcesses.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcesses.js @@ -16,33 +16,30 @@ import {connect} from 'react-redux'; import i18n from 'nfvo-utils/i18n/i18n.js'; import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; import SoftwareProductProcessesActionHelper from './SoftwareProductProcessesActionHelper.js'; import SoftwareProductProcessesView from './SoftwareProductProcessesView.jsx'; export const mapStateToProps = ({softwareProduct}) => { let {softwareProductEditor: {data: currentSoftwareProduct = {}}, softwareProductProcesses: {processesList, processesEditor}} = softwareProduct; - let isReadOnlyMode = VersionControllerUtils.isReadOnly(currentSoftwareProduct); let {data} = processesEditor; return { currentSoftwareProduct, processesList, isDisplayEditor: Boolean(data), - isModalInEditMode: Boolean(data && data.id), - isReadOnlyMode + isModalInEditMode: Boolean(data && data.id) }; }; -const mapActionsToProps = (dispatch, {softwareProductId}) => { +const mapActionsToProps = (dispatch, {softwareProductId, version}) => { return { onAddProcess: () => SoftwareProductProcessesActionHelper.openEditor(dispatch), onEditProcess: (process) => SoftwareProductProcessesActionHelper.openEditor(dispatch, process), - onDeleteProcess: (process, version) => dispatch({ + onDeleteProcess: (process) => dispatch({ type: modalActionTypes.GLOBAL_MODAL_WARNING, data:{ - msg: i18n(`Are you sure you want to delete "${process.name}"?`), + msg: i18n('Are you sure you want to delete "{name}"?', {name: process.name}), confirmationButtonText: i18n('Delete'), title: i18n('Delete'), onConfirmed: ()=> SoftwareProductProcessesActionHelper.deleteProcess(dispatch, diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesEditor.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesEditor.js index ff787c357e..fc194fac13 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesEditor.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesEditor.js @@ -45,7 +45,7 @@ const mapActionsToProps = (dispatch, {softwareProductId, version}) => { SoftwareProductProcessesActionHelper.closeEditor(dispatch); SoftwareProductProcessesActionHelper.saveProcess(dispatch, {softwareProductId, version, previousProcess, process}); }, - onClose: () => SoftwareProductProcessesActionHelper.closeEditor(dispatch), + onCancel: () => SoftwareProductProcessesActionHelper.closeEditor(dispatch), onValidateForm: () => ValidationHelper.validateForm(dispatch, VSP_PROCESS_FORM) }; }; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesEditorForm.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesEditorForm.jsx new file mode 100644 index 0000000000..72b2f8cb38 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesEditorForm.jsx @@ -0,0 +1,181 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import React from 'react'; +import PropTypes from 'prop-types'; +import Dropzone from 'react-dropzone'; + +import DraggableUploadFileBox from 'nfvo-components/fileupload/DraggableUploadFileBox.jsx'; +import i18n from 'nfvo-utils/i18n/i18n.js'; +import Form from 'nfvo-components/input/validation/Form.jsx'; +import Input from 'nfvo-components/input/validation/Input.jsx'; +import GridSection from 'nfvo-components/grid/GridSection.jsx'; +import GridItem from 'nfvo-components/grid/GridItem.jsx'; + +const SoftwareProductProcessEditorPropType = React.PropTypes.shape({ + id: PropTypes.string, + name: PropTypes.string, + description: PropTypes.string, + artifactName: PropTypes.string, + type: PropTypes.string +}); + + + +class SoftwareProductProcessesEditorForm extends React.Component { + + + static propTypes = { + data: SoftwareProductProcessEditorPropType, + previousData: SoftwareProductProcessEditorPropType, + isReadOnlyMode: React.PropTypes.bool, + onDataChanged: React.PropTypes.func, + onSubmit: React.PropTypes.func, + onCancel: React.PropTypes.func + }; + state = { + dragging: false, + files: [] + }; + + render() { + let {data = {}, isReadOnlyMode, onDataChanged, onCancel, genericFieldInfo, optionsInputValues} = this.props; + let {name, description, artifactName, type} = data; + + return ( +
    + {genericFieldInfo &&
    this.submit() } + onReset={ () => onCancel() } + isValid={this.props.isFormValid} + formReady={this.props.formReady} + onValidateForm={() => this.props.onValidateForm() } + className='vsp-processes-editor'> +
    + this.handleImportSubmit(acceptedFiles, rejectedFiles)} + onDragEnter={() => this.setState({dragging: true})} + onDragLeave={() => this.setState({dragging: false})} + multiple={false} + disableClick={true} + ref='processEditorFileInput' + name='processEditorFileInput'> + + + onDataChanged({name})} + isValid={genericFieldInfo.name.isValid} + isRequired={true} + data-test-id='name' + errorText={genericFieldInfo.name.errorText} + label={i18n('Name')} + value={name} + type='text'/> + + + + this.refs.processEditorFileInput.open()}/> + + + + + onDataChanged({description})} + isValid={genericFieldInfo.description.isValid} + errorText={genericFieldInfo.description.errorText} + label={i18n('Notes')} + value={description} + data-test-id='vsp-process-description' + type='textarea'/> + + + + { + // setting the unit to the correct value + const selectedIndex = e.target.selectedIndex; + const val = e.target.options[selectedIndex].value; + onDataChanged({type: val});} + } + value={type} + label={i18n('Process Type')} + className='process-type' + data-test-id='process-type' + isValid={genericFieldInfo.type.isValid} + errorText={genericFieldInfo.type.errorText} + type='select'> + {optionsInputValues.PROCESS_TYPE.map(mtype => + )} + + + + +
    +
    } +
    + ); + } + + submit() { + const {data: process, previousData: previousProcess} = this.props; + let {files} = this.state; + let formData = false; + if (files.length) { + let file = files[0]; + formData = new FormData(); + formData.append('upload', file); + } + + let updatedProcess = { + ...process, + formData + }; + this.props.onSubmit({process: updatedProcess, previousProcess}); + } + + + handleImportSubmit(files, rejectedFiles) { + if (files.length > 0) { + let {onDataChanged} = this.props; + this.setState({ + dragging: false, + complete: '0', + files + }); + onDataChanged({artifactName: files[0].name}); + } + else if (rejectedFiles.length > 0) { + this.setState({ + dragging: false + }); + if (DEBUG) { + console.log('file was rejected.' + rejectedFiles[0].name); + } + } + } +} + +export default SoftwareProductProcessesEditorForm; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesEditorView.jsx index 0df36cf65d..9ce690a1ca 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesEditorView.jsx @@ -14,167 +14,17 @@ * permissions and limitations under the License. */ import React from 'react'; -import Dropzone from 'react-dropzone'; -import classnames from 'classnames'; -import DraggableUploadFileBox from 'nfvo-components/fileupload/DraggableUploadFileBox.jsx'; -import i18n from 'nfvo-utils/i18n/i18n.js'; import {optionsInputValues as ProcessesOptionsInputValues} from './SoftwareProductProcessesConstants.js'; -import Form from 'nfvo-components/input/validation/Form.jsx'; -import Input from 'nfvo-components/input/validation/Input.jsx'; -import GridSection from 'nfvo-components/grid/GridSection.jsx'; -import GridItem from 'nfvo-components/grid/GridItem.jsx'; - -const SoftwareProductProcessEditorPropType = React.PropTypes.shape({ - id: React.PropTypes.string, - name: React.PropTypes.string, - description: React.PropTypes.string, - artifactName: React.PropTypes.string, - type: React.PropTypes.string -}); - +import SoftwareProductProcessesEditorForm from './SoftwareProductProcessesEditorForm.jsx'; class SoftwareProductProcessesEditorView extends React.Component { - - state = { - dragging: false, - files: [] - }; - - static propTypes = { - data: SoftwareProductProcessEditorPropType, - previousData: SoftwareProductProcessEditorPropType, - isReadOnlyMode: React.PropTypes.bool, - onDataChanged: React.PropTypes.func, - onSubmit: React.PropTypes.func, - onClose: React.PropTypes.func - }; - render() { - let {data = {}, isReadOnlyMode, onDataChanged, onClose, genericFieldInfo} = this.props; - let {name, description, artifactName, type} = data; - return ( -
    - {genericFieldInfo &&
    this.submit() } - onReset={ () => onClose() } - isValid={this.props.isFormValid} - formReady={this.props.formReady} - onValidateForm={() => this.props.onValidateForm() } - className='vsp-processes-editor'> -
    - this.handleImportSubmit(acceptedFiles, rejectedFiles)} - onDragEnter={() => this.setState({dragging: true})} - onDragLeave={() => this.setState({dragging: false})} - multiple={false} - disableClick={true} - ref='processEditorFileInput' - name='processEditorFileInput'> - - - onDataChanged({name})} - isValid={genericFieldInfo.name.isValid} - isRequired={true} - data-test-id='name' - errorText={genericFieldInfo.name.errorText} - label={i18n('Name')} - value={name} - type='text'/> - - - this.refs.processEditorFileInput.open()}/> - - - - - onDataChanged({description})} - isValid={genericFieldInfo.description.isValid} - errorText={genericFieldInfo.description.errorText} - label={i18n('Notes')} - value={description} - data-test-id='vsp-process-description' - type='textarea'/> - - - - { - // setting the unit to the correct value - const selectedIndex = e.target.selectedIndex; - const val = e.target.options[selectedIndex].value; - onDataChanged({type: val});} - } - value={type} - label={i18n('Process Type')} - data-test-id='process-type' - isValid={genericFieldInfo.type.isValid} - errorText={genericFieldInfo.type.errorText} - type='select'> - {ProcessesOptionsInputValues.PROCESS_TYPE.map(mtype => - )} - - - - -
    -
    } -
    + ); } - - submit() { - const {data: process, previousData: previousProcess} = this.props; - let {files} = this.state; - let formData = false; - if (files.length) { - let file = files[0]; - formData = new FormData(); - formData.append('upload', file); - } - - let updatedProcess = { - ...process, - formData - }; - this.props.onSubmit({process: updatedProcess, previousProcess}); - } - - - handleImportSubmit(files, rejectedFiles) { - if (files.length > 0) { - let {onDataChanged} = this.props; - this.setState({ - dragging: false, - complete: '0', - files - }); - onDataChanged({artifactName: files[0].name}); - } - else if (rejectedFiles.length > 0) { - this.setState({ - dragging: false - }); - if (DEBUG) { - console.log('file was rejected.' + rejectedFiles[0].name); - } - } - } } export default SoftwareProductProcessesEditorView; diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesView.jsx index 8f52434042..e2cb4edf74 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/processes/SoftwareProductProcessesView.jsx @@ -14,14 +14,12 @@ * permissions and limitations under the License. */ import React from 'react'; +import PropTypes from 'prop-types'; import i18n from 'nfvo-utils/i18n/i18n.js'; import Modal from 'nfvo-components/modal/Modal.jsx'; -import ListEditorView from 'nfvo-components/listEditor/ListEditorView.jsx'; -import ListEditorItemView from 'nfvo-components/listEditor/ListEditorItemView.jsx'; - import SoftwareProductProcessesEditor from './SoftwareProductProcessesEditor.js'; - +import SoftwareProductProcessListView from './SoftwareProductProcessListView.jsx'; class SoftwareProductProcessesView extends React.Component { @@ -31,25 +29,25 @@ class SoftwareProductProcessesView extends React.Component { }; static propTypes = { - onAddProcess: React.PropTypes.func.isRequired, - onEditProcess: React.PropTypes.func.isRequired, - onDeleteProcess: React.PropTypes.func.isRequired, - isDisplayEditor: React.PropTypes.bool.isRequired, - isReadOnlyMode: React.PropTypes.bool.isRequired, - currentSoftwareProduct:React.PropTypes.object + onAddProcess: PropTypes.func.isRequired, + onEditProcess: PropTypes.func.isRequired, + onDeleteProcess: PropTypes.func.isRequired, + isDisplayEditor: PropTypes.bool.isRequired, + isReadOnlyMode: PropTypes.bool.isRequired, + currentSoftwareProduct:PropTypes.object }; render() { return (
    {this.renderEditor()} - {this.renderProcessList()} +
    ); } renderEditor() { - let {currentSoftwareProduct: {id, version}, isModalInEditMode, isReadOnlyMode, isDisplayEditor} = this.props; + let {currentSoftwareProduct: {id}, version, isModalInEditMode, isReadOnlyMode, isDisplayEditor} = this.props; return ( @@ -62,66 +60,6 @@ class SoftwareProductProcessesView extends React.Component { ); } - - renderProcessList() { - const {localFilter} = this.state; - let {onAddProcess, isReadOnlyMode} = this.props; - - return ( - this.setState({localFilter: value})}> - {this.filterList().map(processes => this.renderProcessListItem(processes, isReadOnlyMode))} - - ); - } - - renderProcessListItem(process, isReadOnlyMode) { - let {id, name, description, artifactName = ''} = process; - let {currentSoftwareProduct: {version}, onEditProcess, onDeleteProcess} = this.props; - return ( - onEditProcess(process)} - onDelete={() => onDeleteProcess(process, version)}> - -
    -
    {i18n('Name')}
    -
    {name}
    -
    -
    -
    {i18n('Artifact name')}
    -
    {artifactName}
    -
    -
    -
    {i18n('Notes')}
    -
    {description}
    -
    -
    - ); - } - - filterList() { - let {processesList} = this.props; - let {localFilter} = this.state; - - if (localFilter.trim()) { - const filter = new RegExp(escape(localFilter), 'i'); - return processesList.filter(({name = '', description = ''}) => { - return escape(name).match(filter) || escape(description).match(filter); - }); - } - else { - return processesList; - } - } } export default SoftwareProductProcessesView; diff --git a/openecomp-ui/src/sdc-app/onboarding/userNotifications/NotificationsReducer.js b/openecomp-ui/src/sdc-app/onboarding/userNotifications/NotificationsReducer.js new file mode 100644 index 0000000000..2c3442ee68 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/userNotifications/NotificationsReducer.js @@ -0,0 +1,72 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import {actionTypes} from './UserNotificationsConstants.js'; + +export default (state = {}, action) => { + switch (action.type) { + case actionTypes.NOTIFICATION: + let list = (state.notificationsList) ? state.notificationsList : []; + const {notifications, lastScanned} = action.data; + return { + ...state, + lastScanned, + notificationsList: [...notifications, ...list], + numOfNotSeenNotifications: state.numOfNotSeenNotifications + notifications.length + }; + case actionTypes.LOAD_NOTIFICATIONS: + return { + ...state, + ...action.result, + notificationsList: action.result.notifications, + notifications: undefined + }; + case actionTypes.LOAD_PREV_NOTIFICATIONS: + const {notifications: prevNotifications, endOfPage: newEndOfPage} = action.result; + return { + ...state, + notificationsList: [ + ...state.notificationsList, + ...prevNotifications + ], + endOfPage: newEndOfPage + }; + case actionTypes.UPDATE_READ_NOTIFICATION: + let {notificationForUpdate} = action; + notificationForUpdate = {...notificationForUpdate, read: true}; + const indexForEdit = state.notificationsList.findIndex(notification => notification.eventId === notificationForUpdate.eventId); + return { + ...state, + notificationsList: [ + ...state.notificationsList.slice(0, indexForEdit), + notificationForUpdate, + ...state.notificationsList.slice(indexForEdit + 1) + ] + }; + case actionTypes.RESET_NEW_NOTIFICATIONS: + return { + ...state, + numOfNotSeenNotifications: 0 + }; + case actionTypes.TOGGLE_OVERLAY: + return { + ...state, + showNotificationsOverlay: action.showNotificationsOverlay + }; + default: + return state; + } +}; diff --git a/openecomp-ui/src/sdc-app/onboarding/userNotifications/NotificationsView.jsx b/openecomp-ui/src/sdc-app/onboarding/userNotifications/NotificationsView.jsx new file mode 100644 index 0000000000..de105d23a7 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/userNotifications/NotificationsView.jsx @@ -0,0 +1,106 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import React from 'react'; +import PropTypes from 'prop-types'; +import enhanceWithClickOutside from 'react-click-outside'; +import classnames from 'classnames'; +import {connect} from 'react-redux'; +import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; +import Overlay from 'nfvo-components/overlay/Overlay.jsx'; +import UserNotifications from 'sdc-app/onboarding/userNotifications/UserNotifications.jsx'; +import UserNotificationsActionHelper from 'sdc-app/onboarding/userNotifications/UserNotificationsActionHelper.js'; +import {actionTypes} from './UserNotificationsConstants.js'; +import OnboardingActionHelper from 'sdc-app/onboarding/OnboardingActionHelper.js'; + +const mapStateToProps = ({currentScreen, notifications, users: {usersList}}) => { + return {currentScreen, notifications, usersList}; +}; + +const mapActionToProps = (dispatch) => { + return { + resetNewNotifications: notificationId => UserNotificationsActionHelper.updateLastSeenNotification(dispatch, {notificationId}), + toggleOverlay: ({showNotificationsOverlay}) => dispatch({type: actionTypes.TOGGLE_OVERLAY, showNotificationsOverlay}), + onLoadPrevNotifications: (lastScanned, endOfPage) => UserNotificationsActionHelper.loadPreviousNotifications(dispatch, {lastScanned, endOfPage}), + onSync: ({itemId, itemName, versionId, versionName, currentScreen}) => UserNotificationsActionHelper.syncItem(dispatch, {itemId, itemName, versionId, versionName, currentScreen}), + updateNotification: notificationForUpdate => UserNotificationsActionHelper.updateNotification(dispatch, {notificationForUpdate}), + onLoadItemsLists: () => OnboardingActionHelper.loadItemsLists(dispatch) + }; +}; + + +class NotificationsView extends React.Component { + + static propTypes = { + currentScreen: PropTypes.object, + notifications: PropTypes.object, + resetNewNotifications: PropTypes.func, + toggleOverlay: PropTypes.func, + onLoadPrevNotifications: PropTypes.func, + onSync: PropTypes.func, + updateNotification: PropTypes.func, + onLoadItemsLists: PropTypes.func + }; + + render() { + const {usersList, notifications, onLoadPrevNotifications, onSync, updateNotification, onLoadItemsLists, currentScreen} = this.props; + const {notificationsList, numOfNotSeenNotifications, showNotificationsOverlay, lastScanned, endOfPage} = notifications; + + return ( +
    +
    this.onNotificationIconClick()}> + 0 ? 'notificationFullBell' : 'notificationBell'} color={numOfNotSeenNotifications > 0 ? 'primary' : ''}/> +
    + {numOfNotSeenNotifications} +
    +
    + {showNotificationsOverlay && + + + + } +
    + ); + } + + handleClickOutside() { + const {notifications: {showNotificationsOverlay}} = this.props; + if(showNotificationsOverlay) { + this.onCloseOverlay(); + } + } + + onNotificationIconClick() { + const {notifications: {showNotificationsOverlay}, toggleOverlay} = this.props; + if (showNotificationsOverlay) { + this.onCloseOverlay(); + } else { + toggleOverlay({showNotificationsOverlay: true}); + } + } + + onCloseOverlay() { + const {notifications: {numOfNotSeenNotifications, lastScanned}, resetNewNotifications, toggleOverlay} = this.props; + if (numOfNotSeenNotifications) { + resetNewNotifications(lastScanned); + } + toggleOverlay({showNotificationsOverlay: false}); + } +} + +export default connect(mapStateToProps, mapActionToProps)(enhanceWithClickOutside(NotificationsView)); diff --git a/openecomp-ui/src/sdc-app/onboarding/userNotifications/UserNotifications.jsx b/openecomp-ui/src/sdc-app/onboarding/userNotifications/UserNotifications.jsx new file mode 100644 index 0000000000..c01424ee1b --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/userNotifications/UserNotifications.jsx @@ -0,0 +1,131 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import React from 'react'; +import PropTypes from 'prop-types'; +import ReactDOM from 'react-dom'; +import classnames from 'classnames'; +import i18n from 'nfvo-utils/i18n/i18n.js'; +import {notificationType} from './UserNotificationsConstants.js'; +import ShowMore from 'react-show-more'; + +const Notification = ({notification, users, onActionClicked, getNotificationTypeDesc}) => { + const {eventType, read, eventAttributes, dateTime} = notification; + const {itemName, userId, description, versionName, permission, granted} = eventAttributes; + const {fullName: userName} = users.find(user => user.userId === userId); + return ( +
    +
    +
    + {itemName} + {versionName &&    v{versionName}} + {!read &&
    } +
    +
    +
    {getNotificationTypeDesc(eventType, permission, granted)}
    +
    +
    {`${i18n('By')} ${userName}`}
    +
    + {(description || versionName) &&
    + {description && + {description} + } + {eventType === notificationType.ITEM_CHANGED.SUBMIT && +
    +
    {i18n('Version {versionName} was submitted.', {versionName: versionName})}
    +
    + } +
    + } +
    {dateTime}
    +
    +
    +
    onActionClicked(notification)}> + {eventType === notificationType.PERMISSION_CHANGED ? i18n('Accept') : i18n('Sync')} +
    +
    +
    + ); +}; + +function getNotificationTypeDesc(eventType, permission, granted) { + switch (eventType) { + case notificationType.PERMISSION_CHANGED: + return i18n('Permission {granted}: {permission}', {granted: granted ? 'Granted' : 'Taken', permission: permission}); + case notificationType.ITEM_CHANGED.COMMIT: + return i18n('Your Copy Is Out Of Sync'); + case notificationType.ITEM_CHANGED.SUBMIT: + return i18n('Version Submitted'); + } +} + +class UserNotifications extends React.Component { + + static propTypes = { + currentScreen: PropTypes.object, + notificationsList: PropTypes.array, + usersList: PropTypes.array, + lastScanned: PropTypes.string, + endOfPage:PropTypes.string, + onLoadPrevNotifications: PropTypes.func, + onSync: PropTypes.func, + updateNotification: PropTypes.func, + onLoadItemsLists: PropTypes.func + }; + + render() { + const {notificationsList = [], usersList, lastScanned, endOfPage} = this.props; + + return ( +
    +
    {i18n('Notifications')}
    +
    this.loadPrevNotifications(lastScanned, endOfPage)}> + { + notificationsList.map(notification => ( + this.onActionClicked(notification)} + getNotificationTypeDesc={getNotificationTypeDesc}/>)) + } +
    +
    + ); + } + + onActionClicked(notification) { + const {onSync, updateNotification, currentScreen, onLoadItemsLists} = this.props; + const {eventType, eventAttributes: {itemId, itemName, versionId, versionName}} = notification; + if(eventType !== notificationType.PERMISSION_CHANGED) { + onSync({itemId, itemName, versionId, versionName, currentScreen}); + } + else { + onLoadItemsLists(); + } + updateNotification(notification); + } + + loadPrevNotifications(lastScanned, endOfPage) { + if(endOfPage && lastScanned) { + let element = ReactDOM.findDOMNode(this.refs['notificationList']); + const {onLoadPrevNotifications} = this.props; + + if (element && element.clientHeight + element.scrollTop === element.scrollHeight) { + onLoadPrevNotifications(lastScanned, endOfPage); + } + } + } +} + +export default UserNotifications; diff --git a/openecomp-ui/src/sdc-app/onboarding/userNotifications/UserNotificationsActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/userNotifications/UserNotificationsActionHelper.js new file mode 100644 index 0000000000..574aa0f3fc --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/userNotifications/UserNotificationsActionHelper.js @@ -0,0 +1,123 @@ +import {actionTypes} from './UserNotificationsConstants.js'; +import i18n from 'nfvo-utils/i18n/i18n.js'; +import Configuration from 'sdc-app/config/Configuration.js'; +import RestAPIUtil from 'nfvo-utils/RestAPIUtil.js'; +import WebSocketUtil, {websocketUrl} from 'nfvo-utils/WebSocketUtil.js'; +import {actionsEnum as VersionControllerActionsEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; +import ItemsHelper from 'sdc-app/common/helpers/ItemsHelper.js'; +import ScreensHelper from 'sdc-app/common/helpers/ScreensHelper.js'; +import MergeEditorActionHelper from 'sdc-app/common/merge/MergeEditorActionHelper.js'; +import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; +import {SyncStates} from 'sdc-app/common/merge/MergeEditorConstants.js'; + +function baseUrl() { + const restPrefix = Configuration.get('restPrefix'); + return `${restPrefix}/v1.0/notifications`; +} + +function fetch() { + return RestAPIUtil.fetch(baseUrl()); +} + +function updateNotification(notificationId) { + return RestAPIUtil.put(`${baseUrl()}/${notificationId}`); +} + +function updateLastSeenNotification(notificationId) { + return RestAPIUtil.put(`${baseUrl()}/last-seen/${notificationId}`); +} + +function loadPrevNotifications(lastScanned, endOfPage) { + return RestAPIUtil.fetch(`${baseUrl()}?LAST_DELIVERED_EVENT_ID=${lastScanned}&END_OF_PAGE_EVENT_ID=${endOfPage}`); +} + +const INITIAL_LAST_SCANNED = '00000000-0000-1000-8080-808080808080'; + +const UserNotificationsActionHelper = { + notificationsFirstHandling(dispatch) { + console.log('Websocket Url: ', websocketUrl); + UserNotificationsActionHelper.fetchUserNotificationsList(dispatch).then(({lastScanned}) => { + WebSocketUtil.open(websocketUrl, {lastScanned: lastScanned || INITIAL_LAST_SCANNED}); + }); + }, + + fetchUserNotificationsList(dispatch) { + return fetch().then(result => { + dispatch({ + type: actionTypes.LOAD_NOTIFICATIONS, + result + }); + return Promise.resolve({lastScanned: result.lastScanned}); + }); + }, + + loadPreviousNotifications(dispatch, {lastScanned, endOfPage}) { + loadPrevNotifications(lastScanned, endOfPage).then(result => dispatch({ + type: actionTypes.LOAD_PREV_NOTIFICATIONS, + result + })); + }, + + notifyAboutConflicts(dispatch, {itemId, itemName, version, currentScreen}) { + let {props} = currentScreen; + let currentItemId = props.softwareProductId || props.licenseModelId; + let currentVersion = props.version; + if(currentItemId === itemId && currentVersion.id === version.id) { + MergeEditorActionHelper.analyzeSyncResult(dispatch, {itemId, version}).then(() => ScreensHelper.loadScreen(dispatch, currentScreen)); + } + else { + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_WARNING, + data: { + title: i18n('Conflicts'), + msg: i18n('There are conflicts in {itemName} version {versionName} that you have to resolve', {itemName: itemName.toUpperCase(), versionName: version.versionName}), + cancelButtonText: i18n('OK') + } + }); + } + }, + + syncItem(dispatch, {itemId, itemName, versionId, versionName, currentScreen}) { + let version = {id: versionId, versionName}; + ItemsHelper.fetchVersion({itemId, versionId}).then(response => { + let inMerge = response && response.state && response.state.synchronizationState === SyncStates.MERGE; + if (!inMerge) { + ItemsHelper.performVCAction({itemId, version, action: VersionControllerActionsEnum.SYNC}).then(() => { + return ItemsHelper.fetchVersion({itemId, versionId}).then(response => { + let inMerge = response && response.state && response.state.synchronizationState === SyncStates.MERGE; + if (!inMerge) { + return ScreensHelper.loadScreen(dispatch, currentScreen); + } + else { + return this.notifyAboutConflicts(dispatch, {itemId, itemName, version, currentScreen}); + } + }); + }); + } + else { + this.notifyAboutConflicts(dispatch, {itemId, itemName, version, currentScreen}); + } + }); + }, + + updateNotification(dispatch, {notificationForUpdate}) { + updateNotification(notificationForUpdate.eventId).then(response => { + if(response.status === 'Success' && Object.keys(response.errors).length === 0) { + dispatch({ + type: actionTypes.UPDATE_READ_NOTIFICATION, + notificationForUpdate + }); + } + }); + }, + + updateLastSeenNotification(dispatch, {notificationId}) { + updateLastSeenNotification(notificationId).then(response => { + if (response.status === 'Success' && Object.keys(response.errors).length === 0) { + dispatch({type: actionTypes.RESET_NEW_NOTIFICATIONS}); + } + }); + } +}; + +export default UserNotificationsActionHelper; diff --git a/openecomp-ui/src/sdc-app/onboarding/userNotifications/UserNotificationsConstants.js b/openecomp-ui/src/sdc-app/onboarding/userNotifications/UserNotificationsConstants.js new file mode 100644 index 0000000000..f006b5ae1b --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/userNotifications/UserNotificationsConstants.js @@ -0,0 +1,19 @@ + +import keyMirror from 'nfvo-utils/KeyMirror.js'; + +export const actionTypes = keyMirror({ + NOTIFICATION: null, + LOAD_NOTIFICATIONS: null, + LOAD_PREV_NOTIFICATIONS: null, + UPDATE_READ_NOTIFICATION: null, + RESET_NEW_NOTIFICATIONS: null, + TOGGLE_OVERLAY: null +}); + +export const notificationType = keyMirror({ + PERMISSION_CHANGED: 'PermissionChanged', + ITEM_CHANGED: { + COMMIT: 'commit', + SUBMIT: 'submit' + } +}); \ No newline at end of file diff --git a/openecomp-ui/src/sdc-app/onboarding/users/UsersActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/users/UsersActionHelper.js new file mode 100644 index 0000000000..8a9ff42238 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/users/UsersActionHelper.js @@ -0,0 +1,61 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import RestAPIUtil from 'nfvo-utils/RestAPIUtil.js'; +import Configuration from 'sdc-app/config/Configuration.js'; +import {actionTypes} from './UsersConstants.js'; + +function getUserId() { + let attApiHeaders = Configuration.get('ATTApiHeaders'); + let User = attApiHeaders && attApiHeaders.userId; + let userId = User && User.value ? User.value : ''; + return userId; +} + +function baseUrl() { + const restATTPrefix = Configuration.get('restATTPrefix'); + return `${restATTPrefix}`; +} + + +function fetchUsersList() { + const url = '/v1/user/users'; + return RestAPIUtil.fetch(`${baseUrl()}${url}`); +} + + + +const UsersActionHelper = { + fetchUsersList(dispatch) { + fetchUsersList().then(response => { + dispatch({ + type: actionTypes.USERS_LIST_LOADED, + usersList: response + }); + + let userId = getUserId(); + let userInfo = response.find(user => user.userId === userId); + dispatch({ + type: actionTypes.GOT_USER_INFO, + userInfo + }); + + }); + + } +}; + +export default UsersActionHelper; diff --git a/openecomp-ui/src/sdc-app/onboarding/users/UsersConstants.js b/openecomp-ui/src/sdc-app/onboarding/users/UsersConstants.js new file mode 100644 index 0000000000..fdcf4b179b --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/users/UsersConstants.js @@ -0,0 +1,22 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import keyMirror from 'nfvo-utils/KeyMirror.js'; + +export const actionTypes = keyMirror({ + USERS_LIST_LOADED: null, + GOT_USER_INFO: null +}); diff --git a/openecomp-ui/src/sdc-app/onboarding/users/UsersReducers.js b/openecomp-ui/src/sdc-app/onboarding/users/UsersReducers.js new file mode 100644 index 0000000000..6bd72e3b3c --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/users/UsersReducers.js @@ -0,0 +1,42 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import {actionTypes} from './UsersConstants.js'; +import {combineReducers} from 'redux'; + +function usersList (state = [], action) { + switch (action.type) { + case (actionTypes.USERS_LIST_LOADED): + return [...action.usersList]; + default: + return state; + } +}; + +function userInfo (state = {}, action) { + switch (action.type) { + case (actionTypes.GOT_USER_INFO): + return action.userInfo; + default: + return state; + } +} + + +export default combineReducers({ + usersList: usersList, + userInfo: userInfo +}); \ No newline at end of file diff --git a/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPage.js b/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPage.js new file mode 100644 index 0000000000..7b6f27307d --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPage.js @@ -0,0 +1,87 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import {connect} from 'react-redux'; +import VersionsPageActionHelper from './VersionsPageActionHelper.js'; +import VersionsPageCreationActionHelper from './creation/VersionsPageCreationActionHelper.js'; +import PermissionsActionHelper from '../permissions/PermissionsActionHelper.js'; +import {onboardingMethod as onboardingMethodType} from 'sdc-app/onboarding/softwareProduct/SoftwareProductConstants.js'; +import VersionsPageView from './VersionsPage.jsx'; + +export const mapStateToProps = ({ + users: {userInfo}, + versionsPage: {permissions, versionsList}, + currentScreen: {itemPermission: {isCollaborator}, props: {itemId}}, + softwareProductList = [] +}) => { + + let {versions, selectedVersion} = versionsList; + let {owner, contributors, viewers} = permissions; + + // sorting the version list + versions.sort((a,b) => { + let statusCompare = b.status.localeCompare(a.status); + if (statusCompare === 0) { + return b.modificationTime - a.modificationTime; + } else { + return statusCompare; + } + + }); + + const curentSoftwareProduct = softwareProductList.find(item => item.id === itemId); + return { + versions, + contributors, + viewers, + owner, + currentUser: userInfo, + selectedVersion, + isCollaborator, + isManual: curentSoftwareProduct && curentSoftwareProduct.onboardingMethod === onboardingMethodType.MANUAL + }; + +}; + +export const mapActionsToProps = (dispatch, {itemType, itemId, additionalProps}) => { + return { + onNavigateToVersion({version}) { + VersionsPageActionHelper.onNavigateToVersion(dispatch, {version, itemId, itemType, additionalProps}); + }, + + onSelectVersion({version}) { + VersionsPageActionHelper.selectVersion(dispatch, {version}); + }, + + onCreateVersion({version}) { + VersionsPageCreationActionHelper.open(dispatch, {baseVersion: version, itemId, itemType, additionalProps}); + }, + + onManagePermissions() { + PermissionsActionHelper.openPermissonsManager(dispatch, {itemId, askForRights: false}); + }, + + onTreeFullScreen(treeProps) { + VersionsPageActionHelper.openTree(dispatch, treeProps); + }, + + onModalNodeClick({version}) { + VersionsPageActionHelper.selectVersionFromModal(dispatch, {version}); + } + }; +}; + +export default connect(mapStateToProps, mapActionsToProps)(VersionsPageView); diff --git a/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPage.jsx b/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPage.jsx new file mode 100644 index 0000000000..69a34e0a1c --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPage.jsx @@ -0,0 +1,77 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import React from 'react'; +import VersionList from './components/VersionList.jsx'; +import PermissionsView from './components/PermissionsView.jsx'; +import Tree from 'nfvo-components/tree/Tree.jsx'; +import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; +import i18n from 'nfvo-utils/i18n/i18n.js'; + +class VersionsPage extends React.Component { + state = { + showExpanded : false + } + render() { + let { versions, owner, contributors, currentUser, isCollaborator, itemName = '', viewers, onSelectVersion, onNavigateToVersion, + onTreeFullScreen, onManagePermissions, onCreateVersion, selectedVersion, onModalNodeClick, isManual} = this.props; + return ( +
    +
    {i18n('Available Versions - {itemName}', {itemName: itemName})}
    + +
    +
    +
    +
    {i18n('Version Tree')}
    + {this.state.showExpanded && onTreeFullScreen({ + name: 'versions-tree-popup', + width: 798, + height: 500, + nodes: versions.map(version => ({id: version.id, name: version.name, parent: version.baseId || ''})), + onNodeClick: (version) => onModalNodeClick({version}), + selectedNodeId: selectedVersion, + scrollable: true, + toWiden: true + })} />} +
    + ({id: version.id, name: version.name, parent: version.baseId || ''}))} + onNodeClick={version => onSelectVersion({version})} + onRenderedBeyondWidth={() => {this.setState({showExpanded : true});}} + selectedNodeId={selectedVersion}/> +
    + +
    +
    + ); + } +} + +export default VersionsPage; diff --git a/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPageActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPageActionHelper.js new file mode 100644 index 0000000000..52868293e2 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPageActionHelper.js @@ -0,0 +1,90 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import ItemsHelper from '../../common/helpers/ItemsHelper.js'; +import {actionTypes} from './VersionsPageConstants.js'; +import {itemTypes} from './VersionsPageConstants.js'; +import {modalContentMapper} from 'sdc-app/common/modal/ModalContentMapper.js'; +import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; +import i18n from 'nfvo-utils/i18n/i18n.js'; +import ScreensHelper from 'sdc-app/common/helpers/ScreensHelper.js'; +import {enums, screenTypes} from 'sdc-app/onboarding/OnboardingConstants.js'; + + +const VersionsPageActionHelper = { + fetchVersions(dispatch, {itemType, itemId}) { + return ItemsHelper.fetchVersions({itemId}).then(response => { + dispatch({ + type: actionTypes.VERSIONS_LOADED, + versions: response.results, + itemType, + itemId + }); + }); + }, + + selectVersion(dispatch, {version}) { + dispatch({ + type: actionTypes.SELECT_VERSION, + versionId: version.id + }); + }, + + selectNone(dispatch) { + dispatch({ type: actionTypes.SELECT_NONE }); + }, + + onNavigateToVersion(dispatch, {version, itemId, itemType}) { + switch (itemType) { + case itemTypes.LICENSE_MODEL: + ScreensHelper.loadScreen(dispatch, { + screen: enums.SCREEN.LICENSE_MODEL_OVERVIEW, screenType: screenTypes.LICENSE_MODEL, + props: {licenseModelId: itemId, version} + }); + break; + case itemTypes.SOFTWARE_PRODUCT: + ScreensHelper.loadScreen(dispatch, { + screen: enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, screenType: screenTypes.SOFTWARE_PRODUCT, + props: {softwareProductId: itemId, version} + }); + break; + } + }, + + openTree(dispatch, treeProps) { + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_SHOW, + data: { + modalComponentName: modalContentMapper.VERSION_TREE, + modalComponentProps: treeProps, + onDeclined: () => dispatch({ + type: modalActionTypes.GLOBAL_MODAL_CLOSE + }), + modalClassName: 'versions-tree-modal', + cancelButtonText: i18n('Close'), + title: i18n('Version Tree') + } + }); + }, + + selectVersionFromModal(dispatch, {version}) { + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_CLOSE + }); + this.selectVersion(dispatch, {version}); + } +}; + +export default VersionsPageActionHelper; diff --git a/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPageConstants.js b/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPageConstants.js new file mode 100644 index 0000000000..983ab79a14 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPageConstants.js @@ -0,0 +1,27 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import keyMirror from 'nfvo-utils/KeyMirror.js'; + +export const actionTypes = keyMirror({ + VERSIONS_LOADED: null, + SELECT_VERSION: null, + SELECT_NONE: null +}); + +export const itemTypes = { + LICENSE_MODEL: 'vendor-license-models', + SOFTWARE_PRODUCT: 'vendor-software-products' +}; diff --git a/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPageReducer.js b/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPageReducer.js new file mode 100644 index 0000000000..9b6fa9f803 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/versionsPage/VersionsPageReducer.js @@ -0,0 +1,42 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import {actionTypes} from './VersionsPageConstants.js'; +import {combineReducers} from 'redux'; +import VersionsPageCreationReducer from './creation/VersionsPageCreationReducer.js'; +import PermissionsReducer from '../permissions/PermissionsReducer.js'; +import {createPlainDataReducer} from 'sdc-app/common/reducers/PlainDataReducer.js'; + +function VersionsListReducer(state = {}, action) { + switch (action.type) { + case actionTypes.VERSIONS_LOADED: + let {versions, itemType = state.itemType, itemId} = action; + return {...state, versions, itemType, itemId}; + case actionTypes.SELECT_VERSION: + return {...state, selectedVersion: action.versionId === state.selectedVersion ? null : action.versionId}; + case actionTypes.SELECT_NONE: + return {...state, selectedVersion: null}; + default: + return state; + } +}; + + + +export default combineReducers({ + versionCreation: createPlainDataReducer(VersionsPageCreationReducer), + versionsList: VersionsListReducer, + permissions: PermissionsReducer +}); diff --git a/openecomp-ui/src/sdc-app/onboarding/versionsPage/components/PermissionsView.jsx b/openecomp-ui/src/sdc-app/onboarding/versionsPage/components/PermissionsView.jsx new file mode 100644 index 0000000000..26f8450f4c --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/versionsPage/components/PermissionsView.jsx @@ -0,0 +1,82 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import React from 'react'; +import i18n from 'nfvo-utils/i18n/i18n.js'; +import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; +import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger.js'; +import Tooltip from 'react-bootstrap/lib/Tooltip.js'; + +const maxContributors = 6; + +function extraUsersTooltip (extraUsers) { + return ( + + {extraUsers.map(extraUser =>
    {extraUser.fullName}
    )} +
    + ); +} + +const User = ({user, isCurrentUser, dataTestId}) => ( + +); + +const Owner = ({owner, isCurrentUser}) => ( +
    +
    {i18n('Owner')}
    + +
    +); + +const Contributors = ({contributors, owner, currentUser, onManagePermissions, isManual}) => { + let extraUsers = contributors.length - maxContributors; + return ( +
    +
    {i18n('Contributors')}
    + {contributors.slice(0, maxContributors).map(contributor => + + )} + {extraUsers > 0 && + +
    {`+${extraUsers}`}
    +
    + } + {currentUser.userId === owner.userId && !isManual && + + {i18n('Manage Permissions')} + + } +
    + ); +}; + +const PermissionsView = ({owner, contributors, currentUser = {}, onManagePermissions, isManual}) => ( +
    +
    {i18n('Permissions')}
    +
    +
    + + +
    +
    +
    +); + +export default PermissionsView; diff --git a/openecomp-ui/src/sdc-app/onboarding/versionsPage/components/VersionList.jsx b/openecomp-ui/src/sdc-app/onboarding/versionsPage/components/VersionList.jsx new file mode 100644 index 0000000000..f209d80125 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/versionsPage/components/VersionList.jsx @@ -0,0 +1,129 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import React from 'react'; +import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger.js'; +import Tooltip from 'react-bootstrap/lib/Tooltip.js'; +import i18n from 'nfvo-utils/i18n/i18n.js'; +import SVGIcon from 'sdc-ui/lib/react/SVGIcon.js'; + +const formatTime = (time) => { + if (!time) { return ''; } + + const date = new Date(time); + const options = { + year: 'numeric', + month: 'short', + day: 'numeric', + hour: '2-digit', + minute: '2-digit' + }; + const newDate = date.toLocaleTimeString('en-US', options); + + return newDate; +}; + +const DescriptionField = ({ className, text, useTooltip }) => { + if (useTooltip) { + return ( +
    + {text}}> +
    {text}
    +
    +
    + ); + } + return
    {text}
    ; +}; + +const VersionListItem = ({ data, onSelectVersion, onNavigateToVersion, onCreateVersion, isHeader, isSelected, isCollaborator }) => { + + let {modificationTime, name, status, description, additionalInfo} = data; + const modificationText = !isHeader ? formatTime(modificationTime) : i18n('Last Edited On'); + + return ( +
    { + e.stopPropagation(); + onSelectVersion(); + onNavigateToVersion(); + }}> +
    {name}
    +
    {status}
    +
    {modificationText}
    + + + { + isHeader ? +
    {i18n('Actions')}
    + : +
    +
    + {e.stopPropagation(); onNavigateToVersion();}} + label={i18n('Go to this Version')} + labelPosition='right' /> +
    +
    + {!isHeader && isCollaborator && additionalInfo.OptionalCreationMethods.length > 0 && + { e.stopPropagation(); onCreateVersion(); }} + label={i18n('Create New Version')} + labelPosition='right' + disabled={!isCollaborator} /> + } +
    +
    + } + + +
    + ); + +}; + +const VersionList = ({ versions, onSelectVersion, onNavigateToVersion, onCreateVersion, selectedVersion, isCollaborator }) => ( +
    + +
    + {versions.map(version => + onSelectVersion({version})} + onNavigateToVersion={() => onNavigateToVersion({version})} + onCreateVersion={() => onCreateVersion({version})} + isSelected={selectedVersion === version.id} + isCollaborator={isCollaborator} /> + )} +
    +
    +); + +export default VersionList; diff --git a/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreation.js b/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreation.js new file mode 100644 index 0000000000..66c1c79be5 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreation.js @@ -0,0 +1,44 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import {connect} from 'react-redux'; +import VersionsPageCreationActionHelper from './VersionsPageCreationActionHelper.js'; +import VersionsPageActionHelper from '../VersionsPageActionHelper.js'; +import VersionsPageCreationView from './VersionsPageCreationView.jsx'; +import ValidationHelper from 'sdc-app/common/helpers/ValidationHelper.js'; +import {VERSION_CREATION_FORM_NAME} from './VersionsPageCreationConstants.js'; + +export const mapStateToProps = ({versionsPage: {versionCreation}}) => { + let {genericFieldInfo} = versionCreation; + let isFormValid = ValidationHelper.checkFormValid(genericFieldInfo); + + return {...versionCreation, isFormValid}; +}; + +export const mapActionsToProps = (dispatch, {itemId, itemType, additionalProps}) => { + return { + onDataChanged: (deltaData, customValidations) => ValidationHelper.dataChanged(dispatch, {deltaData, formName: VERSION_CREATION_FORM_NAME, customValidations}), + onCancel: () => VersionsPageCreationActionHelper.close(dispatch), + onSubmit: ({baseVersion, payload}) => { + VersionsPageCreationActionHelper.close(dispatch); + VersionsPageCreationActionHelper.createVersion(dispatch, {baseVersion, itemId, payload}).then(response => { + VersionsPageActionHelper.onNavigateToVersion(dispatch, {version: response, itemId, itemType, additionalProps}); + }); + }, + onValidateForm: () => ValidationHelper.validateForm(dispatch, VERSION_CREATION_FORM_NAME) + }; +}; + +export default connect(mapStateToProps, mapActionsToProps)(VersionsPageCreationView); diff --git a/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationActionHelper.js new file mode 100644 index 0000000000..bc038689a4 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationActionHelper.js @@ -0,0 +1,79 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import RestAPIUtil from 'nfvo-utils/RestAPIUtil.js'; +import Configuration from 'sdc-app/config/Configuration.js'; +import {actionTypes} from './VersionsPageCreationConstants.js'; +import {modalContentMapper} from 'sdc-app/common/modal/ModalContentMapper.js'; +import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js'; +import i18n from 'nfvo-utils/i18n/i18n.js'; +import ItemsHelper from 'sdc-app/common/helpers/ItemsHelper.js'; +import {actionTypes as VersionsPageActionTypes} from '../VersionsPageConstants.js'; + +function baseUrl({itemId, baseVersion}) { + const restPrefix = Configuration.get('restPrefix'); + return `${restPrefix}/v1.0/items/${itemId}/versions/${baseVersion.id}/`; +} + +function createVersion({itemId, baseVersion, payload: {description, creationMethod} }) { + return RestAPIUtil.post(baseUrl({itemId, baseVersion}), {description, creationMethod}); +} + + +export default { + + open(dispatch, {itemType, itemId, additionalProps, baseVersion}) { + dispatch({ + type: actionTypes.OPEN + }); + + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_SHOW, + data: { + modalComponentName: modalContentMapper.VERSION_CREATION, + modalComponentProps: {itemType, itemId, additionalProps, baseVersion}, + title: i18n('New Version - From {name}', {name: baseVersion.name}) + } + }); + }, + + close(dispatch){ + dispatch({ + type: actionTypes.CLOSE + }); + + dispatch({ + type: modalActionTypes.GLOBAL_MODAL_CLOSE + }); + }, + + createVersion(dispatch, {itemId, baseVersion, payload}){ + return createVersion({itemId, baseVersion, payload}).then(result => { + return ItemsHelper.fetchVersions({itemId}).then(response => { + dispatch({ + type: VersionsPageActionTypes.VERSIONS_LOADED, + versions: response.results, + itemId + }); + dispatch({ + type: actionTypes.VERSION_CREATED, + result + }); + return result; + }); + }); + } + +}; diff --git a/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationConstants.js b/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationConstants.js new file mode 100644 index 0000000000..4ce381d4de --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationConstants.js @@ -0,0 +1,28 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import keyMirror from 'nfvo-utils/KeyMirror.js'; + +export const actionTypes = keyMirror({ + OPEN: null, + CLOSE: null, + VERSION_CREATED: null +}); + +export const VERSION_CREATION_FORM_NAME = 'VCREATIONFORM'; + +export const defaultState = { + creationMethod: 'major' +}; \ No newline at end of file diff --git a/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationReducer.js b/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationReducer.js new file mode 100644 index 0000000000..620cf4717f --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationReducer.js @@ -0,0 +1,44 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import {actionTypes, VERSION_CREATION_FORM_NAME, defaultState} from './VersionsPageCreationConstants.js'; + +export default (state = {}, action) => { + switch (action.type) { + case actionTypes.OPEN: + return { + ...state, + formReady: null, + formName: VERSION_CREATION_FORM_NAME, + data: {...defaultState}, + genericFieldInfo: { + description: { + isValid: true, + errorText: '', + validations: [{type: 'required', data: true}, {type: 'maxLength', data: 120}] + }, + creationMethod: { + isValid: true, + errorText: '', + validations: [{type: 'required', data: true}] + } + } + }; + case actionTypes.CLOSE: + return {}; + default: + return state; + } +}; diff --git a/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationView.jsx b/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationView.jsx new file mode 100644 index 0000000000..caa85fe107 --- /dev/null +++ b/openecomp-ui/src/sdc-app/onboarding/versionsPage/creation/VersionsPageCreationView.jsx @@ -0,0 +1,249 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import React from 'react'; +import PropTypes from 'prop-types'; +import i18n from 'nfvo-utils/i18n/i18n.js'; +import Input from 'nfvo-components/input/validation/Input.jsx'; +import Form from 'nfvo-components/input/validation/Form.jsx'; + +const VersionPropType = PropTypes.shape({ + name: PropTypes.string, + description: PropTypes.string, + creationMethod: PropTypes.string +}); + +class VersionsPageCreationView extends React.Component { + + static propTypes = { + data: VersionPropType, + availableMethods: PropTypes.array, + onDataChanged: PropTypes.func.isRequired, + onSubmit: PropTypes.func.isRequired, + onCancel: PropTypes.func.isRequired + }; + + render() { + let {data = {}, genericFieldInfo, baseVersion, onDataChanged, onCancel} = this.props; + let {additionalInfo: {OptionalCreationMethods}} = baseVersion; + let {description, creationMethod} = data; + + return ( +
    + { genericFieldInfo &&
    this.validationForm = validationForm} + hasButtons={true} + onSubmit={() => this.submit()} + submitButtonText={i18n('Create')} + onReset={() => onCancel()} + labledButtons={true} + isValid={this.props.isFormValid} + formReady={this.props.formReady} + onValidateForm={() => this.validate()}> + +
    + this.onSelectMethod(e)} + type='select' + overlayPos='bottom' + data-test-id='new-version-category' + isValid={genericFieldInfo.creationMethod.isValid} + errorText={genericFieldInfo.creationMethod.errorText} + isRequired> + + {OptionalCreationMethods.map(method => )} + +
    + +
    + onDataChanged({description})} + isRequired /> +
    + +
    } +
    + ); + } + + onSelectMethod(e) { + const selectedIndex = e.target.selectedIndex; + const creationMethod = e.target.options[selectedIndex].value; + this.props.onDataChanged({creationMethod}); + } + + submit() { + let {baseVersion, data: {description, creationMethod}} = this.props; + this.props.onSubmit({baseVersion, payload: {description, creationMethod}}); + } + + validate() { + this.props.onValidateForm(); + } + +} + +export default VersionsPageCreationView; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* +
    + onDataChanged({name},V_CREATION_FORM_NAME, {name: name => this.validateName(name)})} + isValid={genericFieldInfo.name.isValid} + errorText={genericFieldInfo.name.errorText} + type='text' + className='field-section' + data-test-id='new-vsp-name' /> + this.onSelectVendor(e)} + isValid={genericFieldInfo.vendorId.isValid} + errorText={genericFieldInfo.vendorId.errorText} + className='input-options-select' + groupClassName='bootstrap-input-options' + data-test-id='new-vsp-vendor' > + {vendorList.map(vendor => + )} + + this.onSelectSubCategory(e)} + isValid={genericFieldInfo.subCategory.isValid} + errorText={genericFieldInfo.subCategory.errorText} + className='input-options-select' + groupClassName='bootstrap-input-options' + data-test-id='new-vsp-category' > + + {softwareProductCategories.map(category => + category.subcategories && + {category.subcategories.map(sub => + )} + ) + } + +
    +
    + onDataChanged({description},V_CREATION_FORM_NAME)} + isValid={genericFieldInfo.description.isValid} + errorText={genericFieldInfo.description.errorText} + type='textarea' + className='field-section' + data-test-id='new-vsp-description' /> +
    +
    + } +
    + ); + } + + getAvailableMethodsList() { + let {availableMethods} = this.props; + return [...availableMethods]; + } + + onSelectVendor(e) { + const selectedIndex = e.target.selectedIndex; + const vendorId = e.target.options[selectedIndex].value; + this.props.onDataChanged({vendorId},V_CREATION_FORM_NAME); + } + + onSelectSubCategory(e) { + const selectedIndex = e.target.selectedIndex; + const subCategory = e.target.options[selectedIndex].value; + let {softwareProductCategories, onDataChanged} = this.props; + let category = SoftwareProductCategoriesHelper.getCurrentCategoryOfSubCategory(subCategory, softwareProductCategories); + onDataChanged({category, subCategory},V_CREATION_FORM_NAME); + } + + submit() { + let {data:softwareProduct, finalizedLicenseModelList} = this.props; + softwareProduct.vendorName = finalizedLicenseModelList.find(vendor => vendor.id === softwareProduct.vendorId).name; + this.props.onSubmit(softwareProduct); + } + + validateName(value) { + const {data: {id}, VSPNames} = this.props; + const isExists = Validator.isItemNameAlreadyExistsInList({itemId: id, itemName: value, list: VSPNames}); + + return !isExists ? {isValid: true, errorText: ''} : + {isValid: false, errorText: i18n('Software product by the name \'' + value + '\' already exists. Software product name must be unique')}; + } + + validate() { + this.props.onValidateForm(SP_CREATION_FORM_NAME); + } +} + +export default SoftwareProductCreationView; +*/ diff --git a/openecomp-ui/test-utils/MockRest.js b/openecomp-ui/test-utils/MockRest.js index c49d53d984..6cc676a2bb 100644 --- a/openecomp-ui/test-utils/MockRest.js +++ b/openecomp-ui/test-utils/MockRest.js @@ -76,5 +76,19 @@ export default { resetQueue() { initQueue(); + }, + + checkEmptyQueue() { + let isEmpty = true; + let message = 'Check following calls: '; + for (let operationType in queue) { + if (queue[operationType].length > 0) { + isEmpty = false; + message += operationType; + } + } + if (!isEmpty) { + throw new Error('Queue is not empty, ' + message); + } } }; diff --git a/openecomp-ui/test-utils/ShowMore.js b/openecomp-ui/test-utils/ShowMore.js new file mode 100644 index 0000000000..a01ae6a5c9 --- /dev/null +++ b/openecomp-ui/test-utils/ShowMore.js @@ -0,0 +1,10 @@ +import React from 'react'; + +const ShowMore = ({children}) => { + if (children.length > 50) { + return (
    Show Message With More Mock
    ); + } else { + return (
    Show Message Mock
    ); + } +}; +export default ShowMore; \ No newline at end of file diff --git a/openecomp-ui/test-utils/factories/common/CurrentScreenFactory.js b/openecomp-ui/test-utils/factories/common/CurrentScreenFactory.js new file mode 100644 index 0000000000..8301a277cf --- /dev/null +++ b/openecomp-ui/test-utils/factories/common/CurrentScreenFactory.js @@ -0,0 +1,100 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import {Factory} from 'rosie'; +import randomstring from 'randomstring'; +import VersionFactory from './VersionFactory.js'; + +export const InitializedItemPermissionFactory = new Factory() + .attrs({ + 'isCertified': false, + 'inMerge': false, + 'isCollaborator': true + }); + +export const ItemPermissionFactory = new Factory() + .extend(InitializedItemPermissionFactory) + .attrs({ + 'isDirty': false, + 'isOutOfSync': false, + 'isUpToDate': true + }); + + +export const CurrentScreenPropsFactory = new Factory() + .option('versionId', () => randomstring.generate()) + .option('versionBaseId', () => randomstring.generate()) + .attrs({ + softwareProductId: () => randomstring.generate(), + licenseModelId: () => randomstring.generate(), + isReadOnlyMode: false + }) + .attr('version', [ + 'versionId', 'versionBaseId' + ], (id, baseId) => + VersionFactory.build({id, baseId}) + ); + + +Factory.define('InitializedCurrentScreenFactory') + .option('isCertified', false) + .option('inMerge', false) + .option('isCollaborator', true) + .option('isReadOnlyMode', ['isCertified', 'inMerge', 'isCollaborator'], (isCertified, inMerge, isCollaborator) => + isCertified || inMerge || !isCollaborator + ) + .attr('itemPermission', ['isCertified', 'inMerge', 'isCollaborator'], (isCertified, inMerge, isCollaborator) => + InitializedItemPermissionFactory.build({isCollaborator, isCertified, inMerge}) + ) + .attr('props', ['isReadOnlyMode'], (isReadOnlyMode) => { + return {isReadOnlyMode}; + }); +export const InitializedCurrentScreenFactory = new Factory().extend('InitializedCurrentScreenFactory'); + + +Factory.define('CurrentScreenFactory') + .extend('InitializedCurrentScreenFactory') + .option('isDirty', false) + .option('isOutOfSync', false) + .option('isUpToDate', true) + .option('version', ['isCertified'], (isCertified) => VersionFactory.build({isCertified})) + .attr('itemPermission', [ + 'isCertified', 'inMerge', 'isCollaborator', 'isDirty', 'isOutOfSync', 'isUpToDate' + ], (isCertified, inMerge, isCollaborator, isDirty, isOutOfSync, isUpToDate) => + ItemPermissionFactory.build({isCollaborator, isCertified, inMerge, isDirty, isOutOfSync, isUpToDate}) + ) + .attr('props', ['isReadOnlyMode', 'version'], (isReadOnlyMode, version) => { + return {isReadOnlyMode, version}; + }); +export default new Factory().extend('CurrentScreenFactory'); + + +export const CurrentScreenFactoryWithProps = new Factory() + .extend('CurrentScreenFactory') + .option('versionId') + .option('versionBaseId') + .option('version') + .attr('props', [ + 'isReadOnlyMode', 'versionId', 'versionBaseId', 'version' + ], (isReadOnlyMode, id, baseId, version) => { + let attrs = {isReadOnlyMode}; + let options = {}; + + if (version !== undefined) { attrs['version'] = version; } + if (id !== undefined) { options['versionId'] = id; } + if (baseId !== undefined) { options['versionBaseId'] = baseId; } + + return CurrentScreenPropsFactory.build(attrs, options); + }); diff --git a/openecomp-ui/test-utils/factories/common/VersionFactory.js b/openecomp-ui/test-utils/factories/common/VersionFactory.js new file mode 100644 index 0000000000..66db6d6075 --- /dev/null +++ b/openecomp-ui/test-utils/factories/common/VersionFactory.js @@ -0,0 +1,31 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import {Factory} from 'rosie'; +import randomstring from 'randomstring'; +import IdMixin from '../mixins/IdMixin.js'; + +export default new Factory() + .extend(IdMixin) + .option('isCertified', false) + .attrs({ + baseId: () => randomstring.generate(), + description: () => randomstring.generate(), + name: () => randomstring.generate(), + creationTime: () => new Date().getTime(), + modificationTime: () => new Date().getTime(), + additionalInfo: () => { return {OptionalCreationMethods: ['major', 'minor']}; } + }) + .attr('status', ['isCertified'], (isCertified) => {return isCertified ? 'Certified' : 'Draft'; }); diff --git a/openecomp-ui/test-utils/factories/licenseModel/LicenseModelFactories.js b/openecomp-ui/test-utils/factories/licenseModel/LicenseModelFactories.js index 716eb15559..7cda105ff7 100644 --- a/openecomp-ui/test-utils/factories/licenseModel/LicenseModelFactories.js +++ b/openecomp-ui/test-utils/factories/licenseModel/LicenseModelFactories.js @@ -17,7 +17,6 @@ import { Factory } from 'rosie'; import { selectedButton } from 'sdc-app/onboarding/licenseModel/overview/LicenseModelOverviewConstants.js'; import IdMixin from 'test-utils/factories/mixins/IdMixin.js'; import randomstring from 'randomstring'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; Factory.define('LicenseModelBaseFactory') .attrs({ @@ -29,7 +28,7 @@ Factory.define('LicenseModelBaseFactory') export const LicenseModelCreationFactory = new Factory() .attrs({ data: { - vendorName: () => randomstring.generate(), + name: () => randomstring.generate(), description: () => randomstring.generate() } }); @@ -48,13 +47,8 @@ export const LicenseModelStoreFactory = new Factory() export const FinalizedLicenseModelFactory = new Factory() .extend(IdMixin) .attrs({ - vendorName: randomstring.generate(), - description: randomstring.generate(), - iconRef: 'iconRef_lBpEgzhuiY1', - version: {id: '1.0', label: '1.0'}, - status: 'Final', - viewableVersion: [{id: '1.0', label: '1.0'}], - finalVersions: [{id: '1.0', label: '1.0'}] + name: randomstring.generate(), + description: randomstring.generate() }); export const LicenseModelOverviewFactory = new Factory() @@ -62,8 +56,10 @@ export const LicenseModelOverviewFactory = new Factory() licenseModelEditor: { data: { ...Factory.attributes('LicenseModelBaseFactory'), - id: () => Math.floor(Math.random() * (1000 - 1) + 1), - ...VersionControllerUtilsFactory.build() + id: () => Math.floor(Math.random() * 1000 + 1), + version: { + id: Math.floor(Math.random() * 1000 + 1) + } } }, entitlementPool: {}, diff --git a/openecomp-ui/test-utils/factories/revisions/RevisionsFactories.js b/openecomp-ui/test-utils/factories/revisions/RevisionsFactories.js new file mode 100644 index 0000000000..57c5e70e68 --- /dev/null +++ b/openecomp-ui/test-utils/factories/revisions/RevisionsFactories.js @@ -0,0 +1,30 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import {Factory} from 'rosie'; +import randomstring from 'randomstring'; +import IdMixin from 'test-utils/factories/mixins/IdMixin.js'; + + +export const RevisionsPagePropsFactory = new Factory() + .sequence('user') + .attr('message', 'message') + .attr('date', new Date().getTime()) + .extend(IdMixin).after(function(revisions) { + let longMessage = revisions.user % 2; + revisions.user = 'Carlos Santana'; + revisions.message = (longMessage) ? randomstring.generate(60) : randomstring.generate(10); + }); diff --git a/openecomp-ui/test-utils/factories/softwareProduct/SoftwareProductComponentsMonitoringFactories.js b/openecomp-ui/test-utils/factories/softwareProduct/SoftwareProductComponentsMonitoringFactories.js index 550e1a6d6c..8cb2221bea 100644 --- a/openecomp-ui/test-utils/factories/softwareProduct/SoftwareProductComponentsMonitoringFactories.js +++ b/openecomp-ui/test-utils/factories/softwareProduct/SoftwareProductComponentsMonitoringFactories.js @@ -26,13 +26,10 @@ export const VSPComponentsMonitoringRestFactory = new Factory() .option('createPoll', false) .option('createVes', false) - .attr(trap, ['createTrap'], (createTrap) => {return (createTrap) ? randomstring.generate() : undefined}) - .attr(poll, ['createPoll'], (createPoll) => {return (createPoll) ? randomstring.generate() : undefined}) - .attr(ves, ['createVes'], (createVes) => {return (createVes) ? randomstring.generate() : undefined}); + .attr(trap, ['createTrap'], (createTrap) => createTrap ? randomstring.generate() : undefined) + .attr(poll, ['createPoll'], (createPoll) => createPoll ? randomstring.generate() : undefined) + .attr(ves, ['createVes'], (createVes) => createVes ? randomstring.generate() : undefined); export const VSPComponentsMonitoringViewFactory = new Factory() .extend(VSPComponentsMonitoringRestFactory); -// .after(monitoring => { - -// }); diff --git a/openecomp-ui/test-utils/factories/softwareProduct/SoftwareProductDependenciesFactories.js b/openecomp-ui/test-utils/factories/softwareProduct/SoftwareProductDependenciesFactories.js index 6521c58a35..fab3f5f79e 100644 --- a/openecomp-ui/test-utils/factories/softwareProduct/SoftwareProductDependenciesFactories.js +++ b/openecomp-ui/test-utils/factories/softwareProduct/SoftwareProductDependenciesFactories.js @@ -23,10 +23,10 @@ const SoftwareProductDependenciesBaseFactory = new Factory() .attrs({ sourceId: () => randomstring.generate(), targetId: () => randomstring.generate(), relationType: relationTypes.DEPENDS_ON - }); + }).extend(IdMixin); export const SoftwareProductDependenciesResponseFactory = new Factory() - .extend(SoftwareProductDependenciesBaseFactory); + .extend(SoftwareProductDependenciesBaseFactory).extend(IdMixin); export const SoftwareProductDependenciesStoreFactory = new Factory() .extend(SoftwareProductDependenciesBaseFactory) diff --git a/openecomp-ui/test-utils/factories/softwareProduct/SoftwareProductEditorFactories.js b/openecomp-ui/test-utils/factories/softwareProduct/SoftwareProductEditorFactories.js index 5c5936155e..a820b70600 100644 --- a/openecomp-ui/test-utils/factories/softwareProduct/SoftwareProductEditorFactories.js +++ b/openecomp-ui/test-utils/factories/softwareProduct/SoftwareProductEditorFactories.js @@ -16,7 +16,6 @@ import {Factory} from 'rosie'; import IdMixin from 'test-utils/factories/mixins/IdMixin.js'; import randomstring from 'randomstring'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; Factory.define('VSPBaseFactory') .attrs( @@ -30,7 +29,7 @@ Factory.define('VSPBaseFactory') licensingVersion: {id: '1', label: '1'}, licensingData: {}, icon: 'icon', - version: {id: '1', label: '1'} + version: {id: '123'} } ); @@ -46,7 +45,6 @@ Factory.define('LicensingDataMixin') export const VSPEditorFactory = new Factory() .extend('VSPBaseFactory') - .extend(VersionControllerUtilsFactory) .extend(IdMixin); export const VSPEditorPostFactory = new Factory() @@ -54,7 +52,6 @@ export const VSPEditorPostFactory = new Factory() export const VSPEditorFactoryWithLicensingData = new Factory() .extend('VSPBaseFactory') - .extend(VersionControllerUtilsFactory) .extend('LicensingDataMixin') .extend(IdMixin); diff --git a/openecomp-ui/test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js b/openecomp-ui/test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js index 8c9640714d..ba3946be48 100644 --- a/openecomp-ui/test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js +++ b/openecomp-ui/test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js @@ -14,17 +14,9 @@ * permissions and limitations under the License. */ import {Factory} from 'rosie'; -import {statusEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; export default new Factory() .attrs({ version: { id: '1.2', label: '1.2'}, - viewableVersions: [{id: '1.0', label: '1.0'}, {id: '1.1', label: '1.1'}, {id: '1.2', label: '1.2'}], - status: statusEnum.CHECK_OUT_STATUS, - lockingUser: 'current' - }).after(function(inst) { - if (inst.status !== statusEnum.CHECK_OUT_STATUS) { - delete inst.lockingUser; - } + viewableVersions: [{id: '1.0', label: '1.0'}, {id: '1.1', label: '1.1'}, {id: '1.2', label: '1.2'}] }); - diff --git a/openecomp-ui/test-utils/factories/users/UsersFactories.js b/openecomp-ui/test-utils/factories/users/UsersFactories.js new file mode 100644 index 0000000000..cbafbe0747 --- /dev/null +++ b/openecomp-ui/test-utils/factories/users/UsersFactories.js @@ -0,0 +1,35 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import {Factory} from 'rosie'; +import randomstring from 'randomstring'; + +Factory.define('UserFactory') + .attrs( + { + firstName: () => randomstring.generate(5), + lastName: () => randomstring.generate(6), + userId: () => randomstring.generate(11), + email: randomstring.generate(5) + '@' + randomstring.generate(6) + '.com', + role: 'OPS', + lastLoginTime: 0, + status: 'ACTIVE', + fullName: () => randomstring.generate(5) + ' ' + randomstring.generate(6), + } +); + + +export const UserFactory = new Factory() + .extend('UserFactory'); \ No newline at end of file diff --git a/openecomp-ui/test-utils/factories/versionsPage/VersionsPageCreationFactories.js b/openecomp-ui/test-utils/factories/versionsPage/VersionsPageCreationFactories.js new file mode 100644 index 0000000000..c57ac87431 --- /dev/null +++ b/openecomp-ui/test-utils/factories/versionsPage/VersionsPageCreationFactories.js @@ -0,0 +1,38 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import {Factory} from 'rosie'; +import randomstring from 'randomstring'; + +export const VersionsPageCreationFactory = new Factory() + .attrs({ + name: () => randomstring.generate(), + description: () => randomstring.generate(), + creationMethod: () => ['major', 'minor'][Math.round(Math.random())] + }); + +export const VersionsPageCreationFieldInfoFactory = new Factory() + .attrs({ + description: () => ({ + isValid: true, + errorText: '', + validations: [{type: 'required', data: true}, {type: 'maxLength', data: 1000}] + }), + creationMethod: () => ({ + isValid: true, + errorText: '', + validations: [{type: 'required', data: true}] + }) + }); diff --git a/openecomp-ui/test-utils/factories/versionsPage/VersionsPageFactories.js b/openecomp-ui/test-utils/factories/versionsPage/VersionsPageFactories.js new file mode 100644 index 0000000000..49ceddc2bf --- /dev/null +++ b/openecomp-ui/test-utils/factories/versionsPage/VersionsPageFactories.js @@ -0,0 +1,27 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import {Factory} from 'rosie'; +import randomstring from 'randomstring'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; + +export const VersionsPageAdditionalPropsFactory = new Factory() + .attrs({ + itemId: () => randomstring.generate(), + itemType: () => 'vendor-license-models', + additionalProps: () => {}, + baseVersion: () => VersionFactory.build() + }); diff --git a/openecomp-ui/test-utils/failedTestReport.js b/openecomp-ui/test-utils/failedTestReport.js index 9520cc9c99..ed88ccde4f 100644 --- a/openecomp-ui/test-utils/failedTestReport.js +++ b/openecomp-ui/test-utils/failedTestReport.js @@ -22,7 +22,7 @@ stdin.on('end', function () { console.log('Failure Summary: \n'); } report.testResults.forEach((suite) => { - if(suite.status == 'failed') { + if(suite.status === 'failed') { console.log('Suite: ' + suite.name); suite.assertionResults.forEach((test) => { if (test.status === 'failed') { diff --git a/openecomp-ui/test/activity-log/ActivityLog.test.js b/openecomp-ui/test/activity-log/ActivityLog.test.js index 00aff49b26..d2c135eb79 100644 --- a/openecomp-ui/test/activity-log/ActivityLog.test.js +++ b/openecomp-ui/test/activity-log/ActivityLog.test.js @@ -24,11 +24,15 @@ import {mapStateToProps} from 'sdc-app/common/activity-log/ActivityLog.js'; import {storeCreator} from 'sdc-app/AppStore.js'; import mockRest from 'test-utils/MockRest.js'; import {ActivityLogStoreFactory} from 'test-utils/factories/activity-log/ActivityLogFactories.js'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; +import {UserFactory} from 'test-utils/factories/users/UsersFactories.js'; + +import {actionTypes as userActionTypes} from 'sdc-app/onboarding/users/UsersConstants.js'; describe('Activity Log Module Tests', function () { const LICENSE_MODEL_ID = '555'; - const version = VersionControllerUtilsFactory.build().version; + const version = VersionFactory.build(); + const usersList = UserFactory.buildList(3); it('mapStateToProps mapper exists', () => { expect(mapStateToProps).toBeTruthy(); @@ -37,11 +41,15 @@ describe('Activity Log Module Tests', function () { it('Loads Activity Log and renders into jsx', () => { const store = storeCreator(); const dispatch = store.dispatch; - let ActivityLogList = ActivityLogStoreFactory.buildList(1); + dispatch({ + type: userActionTypes.USERS_LIST_LOADED, + usersList + }); + let ActivityLogList = ActivityLogStoreFactory.buildList(1, {user: usersList[0].userId}); const expectedStore = cloneAndSet(store.getState(), 'licenseModel.activityLog', ActivityLogList); mockRest.addHandler('fetch', ({data, options, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/activity-logs/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}/activity-logs`); expect(data).toEqual(undefined); expect(options).toEqual(undefined); return {results: ActivityLogList}; @@ -51,7 +59,9 @@ describe('Activity Log Module Tests', function () { const state = store.getState(); expect(state).toEqual(expectedStore); const props = mapStateToProps(state); - expect(props.activities).toEqual(ActivityLogList); + expect(props.activities).toEqual(ActivityLogList.map(activity => + ({...activity, user: {id: activity.user, name: usersList.find(userObject => userObject.userId === activity.user).fullName}}) + )); const wrapper = mount(); expect(wrapper).toBeTruthy(); }); @@ -65,9 +75,9 @@ describe('Activity Log Module Tests', function () { const firstTimestamp = firstDate.getTime(); const secondTimestamp = secondDate.getTime(); - let firstActivity = ActivityLogStoreFactory.build({user: 'first', timestamp: firstTimestamp}); - let secondActivity = ActivityLogStoreFactory.build({user: 'second', timestamp: secondTimestamp, status: {success: false, message: 'error'}}); - let props = mapStateToProps({licenseModel: {activityLog: [firstActivity, secondActivity]}}); + let firstActivity = ActivityLogStoreFactory.build({user: usersList[0].userId, timestamp: firstTimestamp}); + let secondActivity = ActivityLogStoreFactory.build({user: usersList[1].userId, timestamp: secondTimestamp, status: {success: false, message: 'error'}}); + let props = mapStateToProps({users: {usersList}, licenseModel: {activityLog: [firstActivity, secondActivity]}}); const wrapper = mount(); expect(wrapper.find(ActivityListItem).length).toEqual(3); // Includes Header component @@ -82,8 +92,8 @@ describe('Activity Log Module Tests', function () { expect(newFirstInstanceProps.activity.timestamp).toEqual(firstTimestamp); const listEditor = wrapper.find(ListEditorView); - listEditor.props().onFilter('second'); + listEditor.props().onFilter(usersList[1].fullName); expect(wrapper.find(ActivityListItem).length).toEqual(2); - expect(wrapper.find(ActivityListItem).at(1).props().activity.user).toEqual('second'); + expect(wrapper.find(ActivityListItem).at(1).props().activity.user.name).toEqual(usersList[1].fullName); }); }); diff --git a/openecomp-ui/test/licenseModel/creation/LicenseModelCreation.test.js b/openecomp-ui/test/licenseModel/creation/LicenseModelCreation.test.js index 0d8ce945c8..935360b04b 100644 --- a/openecomp-ui/test/licenseModel/creation/LicenseModelCreation.test.js +++ b/openecomp-ui/test/licenseModel/creation/LicenseModelCreation.test.js @@ -32,6 +32,9 @@ describe('License Model Creation Module Tests', function() { licenseModelCreation: { data: {} } + }, + users: { + usersList: [] } }; let props = mapStateToProps(state); @@ -41,16 +44,19 @@ describe('License Model Creation Module Tests', function() { it ('should return vlm names list', () => { let state = { licenseModelList: [{ - vendorName: 'vlm1', + name: 'vlm1', id: 'vlm1_id' }, { - vendorName: 'vlm2', + name: 'vlm2', id: 'vlm2_id' }], licenseModel: { licenseModelCreation: { data: {} } + }, + users: { + usersList: [] } }; let props = mapStateToProps(state); diff --git a/openecomp-ui/test/licenseModel/entitlementPools/test.js b/openecomp-ui/test/licenseModel/entitlementPools/test.js index f5415239ad..173384dc02 100644 --- a/openecomp-ui/test/licenseModel/entitlementPools/test.js +++ b/openecomp-ui/test/licenseModel/entitlementPools/test.js @@ -19,14 +19,18 @@ import {cloneAndSet, buildListFromFactory} from 'test-utils/Util.js'; import {storeCreator} from 'sdc-app/AppStore.js'; import EntitlementPoolsActionHelper from 'sdc-app/onboarding/licenseModel/entitlementPools/EntitlementPoolsActionHelper.js'; import {EntitlementPoolStoreFactory, EntitlementPoolPostFactory} from 'test-utils/factories/licenseModel/EntitlementPoolFactories.js'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; import {LimitItemFactory, LimitPostFactory} from 'test-utils/factories/licenseModel/LimitFactories.js'; import {getStrValue} from 'nfvo-utils/getValue.js'; +import {SyncStates} from 'sdc-app/common/merge/MergeEditorConstants.js'; +import CurrentScreenFactory from 'test-utils/factories/common/CurrentScreenFactory.js'; describe('Entitlement Pools Module Tests', function () { const LICENSE_MODEL_ID = '555'; - const version = VersionControllerUtilsFactory.build().version; + const version = VersionFactory.build(); + const itemPermissionAndProps = CurrentScreenFactory.build({}, {version}); + const returnedVersionFields = {baseId: version.baseId, description: version.description, id: version.id, name: version.name, status: version.status}; it('Load Entitlement Pools List', () => { @@ -54,6 +58,7 @@ describe('Entitlement Pools Module Tests', function () { const entitlementPoolsList = buildListFromFactory(EntitlementPoolStoreFactory,1); deepFreeze(entitlementPoolsList); const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, licenseModel: { entitlementPool: { entitlementPoolsList @@ -62,7 +67,16 @@ describe('Entitlement Pools Module Tests', function () { }); deepFreeze(store.getState()); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.entitlementPool.entitlementPoolsList', []); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.entitlementPool.entitlementPoolsList', []); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('destroy', ({data, options, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/entitlement-pools/${entitlementPoolsList[0].id}`); @@ -75,6 +89,13 @@ describe('Entitlement Pools Module Tests', function () { }; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return EntitlementPoolsActionHelper.deleteEntitlementPool(store.dispatch, { licenseModelId: LICENSE_MODEL_ID, version, @@ -86,7 +107,9 @@ describe('Entitlement Pools Module Tests', function () { it('Add Entitlement Pool', () => { - const store = storeCreator(); + const store = storeCreator({ + currentScreen: {...itemPermissionAndProps} + }); deepFreeze(store.getState()); const EntitlementPoolPostRequest = EntitlementPoolPostFactory.build(); @@ -97,7 +120,16 @@ describe('Entitlement Pools Module Tests', function () { const entitlementPoolAfterAdd = EntitlementPoolStoreFactory.build({id: entitlementPoolIdFromResponse}); deepFreeze(entitlementPoolAfterAdd); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.entitlementPool.entitlementPoolsList', [entitlementPoolAfterAdd]); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.entitlementPool.entitlementPoolsList', [entitlementPoolAfterAdd]); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('post', ({data, options, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/entitlement-pools`); @@ -109,6 +141,13 @@ describe('Entitlement Pools Module Tests', function () { }; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return EntitlementPoolsActionHelper.saveEntitlementPool(store.dispatch, { licenseModelId: LICENSE_MODEL_ID, @@ -127,6 +166,7 @@ describe('Entitlement Pools Module Tests', function () { deepFreeze(entitlementPoolsList); const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, licenseModel: { entitlementPool: { entitlementPoolsList @@ -144,7 +184,16 @@ describe('Entitlement Pools Module Tests', function () { const entitlementPoolPutRequest = EntitlementPoolPostFactory.build({name: 'ep1_UPDATED', description: 'string_UPDATED'}); deepFreeze(entitlementPoolPutRequest); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.entitlementPool.entitlementPoolsList', [entitlementPoolUpdateData]); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.entitlementPool.entitlementPoolsList', [entitlementPoolUpdateData]); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('put', ({data, options, baseUrl}) => { @@ -154,6 +203,13 @@ describe('Entitlement Pools Module Tests', function () { return {returnCode: 'OK'}; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return EntitlementPoolsActionHelper.saveEntitlementPool(store.dispatch, { licenseModelId: LICENSE_MODEL_ID, version, @@ -187,7 +243,9 @@ describe('Entitlement Pools Module Tests', function () { it('Add Limit', () => { - const store = storeCreator(); + const store = storeCreator({ + currentScreen: {...itemPermissionAndProps} + }); deepFreeze(store.getState()); const limitToAdd = LimitPostFactory.build(); @@ -203,7 +261,16 @@ describe('Entitlement Pools Module Tests', function () { deepFreeze(limitAddedItem); const entitlementPool = EntitlementPoolStoreFactory.build(); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.entitlementPool.entitlementPoolEditor.limitsList', [limitAddedItem]); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.entitlementPool.entitlementPoolEditor.limitsList', [limitAddedItem]); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('post', ({data, options, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/entitlement-pools/${entitlementPool.id}/limits`); @@ -222,6 +289,13 @@ describe('Entitlement Pools Module Tests', function () { return {results: [limitAddedItem]}; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return EntitlementPoolsActionHelper.submitLimit(store.dispatch, { licenseModelId: LICENSE_MODEL_ID, @@ -241,6 +315,7 @@ describe('Entitlement Pools Module Tests', function () { deepFreeze(limitsList); const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, licenseModel: { entitlementPool: { entitlementPoolEditor: { @@ -252,7 +327,17 @@ describe('Entitlement Pools Module Tests', function () { deepFreeze(store.getState()); const entitlementPool = EntitlementPoolStoreFactory.build(); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.entitlementPool.entitlementPoolEditor.limitsList', []); + + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.entitlementPool.entitlementPoolEditor.limitsList', []); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('destroy', ({data, options, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/entitlement-pools/${entitlementPool.id}/limits/${limitsList[0].id}`); @@ -272,6 +357,13 @@ describe('Entitlement Pools Module Tests', function () { return {results: []}; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return EntitlementPoolsActionHelper.deleteLimit(store.dispatch, { licenseModelId: LICENSE_MODEL_ID, version, @@ -288,6 +380,7 @@ describe('Entitlement Pools Module Tests', function () { deepFreeze(limitsList); const entitlementPool = EntitlementPoolStoreFactory.build(); const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, licenseModel: { entitlementPool: { entitlementPoolEditor: { @@ -312,7 +405,16 @@ describe('Entitlement Pools Module Tests', function () { updatedLimit.unit = {choice: updatedLimit.unit, other: ''}; deepFreeze(updatedLimit); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.entitlementPool.entitlementPoolEditor.limitsList', [updatedLimitForPut]); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.entitlementPool.entitlementPoolEditor.limitsList', [updatedLimitForPut]); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('put', ({data, options, baseUrl}) => { @@ -329,6 +431,13 @@ describe('Entitlement Pools Module Tests', function () { return {results: [updatedLimitForPut]}; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return EntitlementPoolsActionHelper.submitLimit(store.dispatch, { licenseModelId: LICENSE_MODEL_ID, diff --git a/openecomp-ui/test/licenseModel/featureGroups/test.js b/openecomp-ui/test/licenseModel/featureGroups/test.js index 7d0d7242b5..eb947b83d0 100644 --- a/openecomp-ui/test/licenseModel/featureGroups/test.js +++ b/openecomp-ui/test/licenseModel/featureGroups/test.js @@ -19,13 +19,17 @@ import {cloneAndSet, buildListFromFactory} from 'test-utils/Util.js'; import {storeCreator} from 'sdc-app/AppStore.js'; import FeatureGroupsActionHelper from 'sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupsActionHelper.js'; import { FeatureGroupStoreFactory, FeatureGroupPostFactory, FeatureGroupDispatchFactory, FeatureGroupPutFactory } from 'test-utils/factories/licenseModel/FeatureGroupFactories.js'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; +import CurrentScreenFactory from 'test-utils/factories/common/CurrentScreenFactory.js'; +import {SyncStates} from 'sdc-app/common/merge/MergeEditorConstants.js'; describe('Feature Groups Module Tests', function () { const LICENSE_MODEL_ID = '555'; - const version = VersionControllerUtilsFactory.build().version; + const version = VersionFactory.build(); + const itemPermissionAndProps = CurrentScreenFactory.build({}, {version}); + const returnedVersionFields = {baseId: version.baseId, description: version.description, id: version.id, name: version.name, status: version.status}; it('Load Feature Groups List', () => { @@ -53,6 +57,7 @@ describe('Feature Groups Module Tests', function () { const featureGroupsList = buildListFromFactory(FeatureGroupStoreFactory, 1); deepFreeze(featureGroupsList); const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, licenseModel: { featureGroup: { featureGroupsList @@ -61,7 +66,16 @@ describe('Feature Groups Module Tests', function () { }); deepFreeze(store.getState()); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.featureGroup.featureGroupsList', []); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.featureGroup.featureGroupsList', []); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); const idToDelete = featureGroupsList[0].id; @@ -76,6 +90,13 @@ describe('Feature Groups Module Tests', function () { }; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return FeatureGroupsActionHelper.deleteFeatureGroup(store.dispatch, { licenseModelId: LICENSE_MODEL_ID, version, @@ -87,7 +108,14 @@ describe('Feature Groups Module Tests', function () { it('Add Feature Group', () => { - const store = storeCreator(); + const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, + licenseModel: { + featureGroup: { + featureGroupsList: [] + } + } + }); deepFreeze(store.getState()); const FeatureGroupPostRequest = FeatureGroupPostFactory.build({ @@ -105,7 +133,16 @@ describe('Feature Groups Module Tests', function () { id: featureGroupIdFromResponse }); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.featureGroup.featureGroupsList', [featureGroupAfterAdd]); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.featureGroup.featureGroupsList', [featureGroupAfterAdd]); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('post', ({data, options, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/feature-groups`); @@ -131,6 +168,13 @@ describe('Feature Groups Module Tests', function () { return {results: []}; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return FeatureGroupsActionHelper.saveFeatureGroup(store.dispatch, { licenseModelId: LICENSE_MODEL_ID, @@ -149,6 +193,7 @@ describe('Feature Groups Module Tests', function () { deepFreeze(featureGroupsList); const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, licenseModel: { featureGroup: { featureGroupsList @@ -178,7 +223,16 @@ describe('Feature Groups Module Tests', function () { }); deepFreeze(FeatureGroupPutFactoryRequest); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.featureGroup.featureGroupsList', [featureGroupUpdateData]); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.featureGroup.featureGroupsList', [featureGroupUpdateData]); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('put', ({data, options, baseUrl}) => { @@ -202,6 +256,13 @@ describe('Feature Groups Module Tests', function () { return {results: []}; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return FeatureGroupsActionHelper.saveFeatureGroup(store.dispatch, { licenseModelId: LICENSE_MODEL_ID, version, @@ -220,7 +281,6 @@ describe('Feature Groups Module Tests', function () { const editorData = FeatureGroupStoreFactory.build(); deepFreeze(editorData); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.featureGroup.featureGroupEditor.data', editorData); const LICENSE_MODEL_ID = '123'; mockRest.addHandler('fetch', ({data, options, baseUrl}) => { @@ -238,13 +298,9 @@ describe('Feature Groups Module Tests', function () { }); - FeatureGroupsActionHelper.openFeatureGroupsEditor(store.dispatch, {featureGroup: editorData, licenseModelId: '123', version}); - setTimeout(() =>{ - expect(store.getState()).toEqual(expectedStore); - }, 100); - - - + return FeatureGroupsActionHelper.openFeatureGroupsEditor(store.dispatch, {featureGroup: editorData, licenseModelId: '123', version}).then(() => { + expect(store.getState().licenseModel.featureGroup.featureGroupEditor.data).toEqual(editorData); + }); }); }); diff --git a/openecomp-ui/test/licenseModel/licenseAgreement/test.js b/openecomp-ui/test/licenseModel/licenseAgreement/test.js index 40b60da77f..11dc7edde5 100644 --- a/openecomp-ui/test/licenseModel/licenseAgreement/test.js +++ b/openecomp-ui/test/licenseModel/licenseAgreement/test.js @@ -21,12 +21,16 @@ import {storeCreator} from 'sdc-app/AppStore.js'; import LicenseAgreementActionHelper from 'sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementActionHelper.js'; import { LicenseAgreementStoreFactory, LicenseAgreementDispatchFactory, LicenseAgreementPostFactory, LicenseAgreementPutFactory } from 'test-utils/factories/licenseModel/LicenseAgreementFactories.js'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; +import {SyncStates} from 'sdc-app/common/merge/MergeEditorConstants.js'; +import CurrentScreenFactory from 'test-utils/factories/common/CurrentScreenFactory.js'; describe('License Agreement Module Tests', () => { const LICENSE_MODEL_ID = '777'; - const version = VersionControllerUtilsFactory.build().version; + const version = VersionFactory.build(); + const itemPermissionAndProps = CurrentScreenFactory.build({}, {version}); + const returnedVersionFields = {baseId: version.baseId, description: version.description, id: version.id, name: version.name, status: version.status}; it('Load License Agreement List', () => { const licenseAgreementList = buildListFromFactory(LicenseAgreementStoreFactory); @@ -50,6 +54,7 @@ describe('License Agreement Module Tests', () => { it('Delete License Agreement', () => { const licenseAgreementList = buildListFromFactory(LicenseAgreementStoreFactory, 1); const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, licenseModel: { licenseAgreement: { licenseAgreementList @@ -57,14 +62,28 @@ describe('License Agreement Module Tests', () => { } }); deepFreeze(store.getState()); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; const toBeDeletedLicenseAgreementId = licenseAgreementList[0].id; - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseAgreement.licenseAgreementList', []); + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseAgreement.licenseAgreementList', []); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('destroy', ({data, options, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/license-agreements/${toBeDeletedLicenseAgreementId}`); expect(data).toEqual(undefined); expect(options).toEqual(undefined); }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); return LicenseAgreementActionHelper.deleteLicenseAgreement(store.dispatch, { licenseAgreementId: toBeDeletedLicenseAgreementId, @@ -76,7 +95,9 @@ describe('License Agreement Module Tests', () => { }); it('Add License Agreement', () => { - const store = storeCreator(); + const store = storeCreator({ + currentScreen: {...itemPermissionAndProps} + }); deepFreeze(store.getState()); const licenseAgreementToAdd = LicenseAgreementDispatchFactory.build(); @@ -94,9 +115,16 @@ describe('License Agreement Module Tests', () => { }); deepFreeze(licenseAgreementAfterAdd); const licenseAgreementList = [licenseAgreementAfterAdd]; - + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; const featureGroupsList = licenseAgreementList.featureGroupsIds; - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseAgreement.licenseAgreementList', [licenseAgreementAfterAdd]); + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseAgreement.licenseAgreementList', [licenseAgreementAfterAdd]); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('post', ({options, data, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/license-agreements`); @@ -118,6 +146,13 @@ describe('License Agreement Module Tests', () => { expect(options).toEqual(undefined); return {results: featureGroupsList}; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + + }); return LicenseAgreementActionHelper.saveLicenseAgreement(store.dispatch, { licenseAgreement: licenseAgreementToAdd, licenseModelId: LICENSE_MODEL_ID, @@ -130,6 +165,7 @@ describe('License Agreement Module Tests', () => { it('Update License Agreement', () => { const licenseAgreementList = buildListFromFactory(LicenseAgreementStoreFactory, 1, {featureGroupsIds: ['77']}); const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, licenseModel: { licenseAgreement: { licenseAgreementList @@ -157,7 +193,15 @@ describe('License Agreement Module Tests', () => { deepFreeze(LicenseAgreementPutFactoryRequest); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseAgreement.licenseAgreementList', [licenseAgreementUpdateData]); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseAgreement.licenseAgreementList', [licenseAgreementUpdateData]); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('put', ({data, options, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/license-agreements/${toBeUpdatedLicenseAgreementId}`); @@ -170,12 +214,19 @@ describe('License Agreement Module Tests', () => { expect(options).toEqual(undefined); return {results: [licenseAgreementUpdateData]}; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); mockRest.addHandler('fetch', ({options, data, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/feature-groups`); expect(data).toEqual(undefined); expect(options).toEqual(undefined); return {results: newFeatureGroupsIds}; }); + return LicenseAgreementActionHelper.saveLicenseAgreement(store.dispatch, { licenseModelId: LICENSE_MODEL_ID, version, diff --git a/openecomp-ui/test/licenseModel/licenseKeyGroups/test.js b/openecomp-ui/test/licenseModel/licenseKeyGroups/test.js index 739e266d7f..09a2c6f53a 100644 --- a/openecomp-ui/test/licenseModel/licenseKeyGroups/test.js +++ b/openecomp-ui/test/licenseModel/licenseKeyGroups/test.js @@ -20,14 +20,18 @@ import {storeCreator} from 'sdc-app/AppStore.js'; import {LicenseKeyGroupStoreFactory, LicenseKeyGroupPostFactory} from 'test-utils/factories/licenseModel/LicenseKeyGroupFactories.js'; import LicenseKeyGroupsActionHelper from 'sdc-app/onboarding/licenseModel/licenseKeyGroups/LicenseKeyGroupsActionHelper.js'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; +import CurrentScreenFactory from 'test-utils/factories/common/CurrentScreenFactory.js'; import {LimitItemFactory, LimitPostFactory} from 'test-utils/factories/licenseModel/LimitFactories.js'; import {getStrValue} from 'nfvo-utils/getValue.js'; +import {SyncStates} from 'sdc-app/common/merge/MergeEditorConstants.js'; describe('License Key Groups Module Tests', function () { const LICENSE_MODEL_ID = '555'; - const version = VersionControllerUtilsFactory.build().version; + const version = VersionFactory.build(); + const itemPermissionAndProps = CurrentScreenFactory.build({}, {version}); + const returnedVersionFields = {baseId: version.baseId, description: version.description, id: version.id, name: version.name, status: version.status}; it('Load License Key Group', () => { @@ -57,6 +61,7 @@ describe('License Key Groups Module Tests', function () { deepFreeze(licenseKeyGroupsList); const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, licenseModel: { licenseKeyGroup: { licenseKeyGroupsList @@ -65,7 +70,17 @@ describe('License Key Groups Module Tests', function () { }); deepFreeze(store.getState()); const toBeDeletedLicenseKeyGroupId = licenseKeyGroupsList[0].id; - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseKeyGroup.licenseKeyGroupsList', []); + + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseKeyGroup.licenseKeyGroupsList', []); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('destroy', ({data, options, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/license-key-groups/${toBeDeletedLicenseKeyGroupId}`); @@ -73,6 +88,13 @@ describe('License Key Groups Module Tests', function () { expect(options).toEqual(undefined); }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return LicenseKeyGroupsActionHelper.deleteLicenseKeyGroup(store.dispatch, { licenseKeyGroupId: toBeDeletedLicenseKeyGroupId, licenseModelId: LICENSE_MODEL_ID, @@ -84,7 +106,9 @@ describe('License Key Groups Module Tests', function () { it('Add License Key Group', () => { - const store = storeCreator(); + const store = storeCreator({ + currentScreen: {...itemPermissionAndProps} + }); deepFreeze(store.getState()); const LicenseKeyGroupPost = LicenseKeyGroupPostFactory.build(); @@ -93,7 +117,16 @@ describe('License Key Groups Module Tests', function () { const LicenseKeyGroupStore = LicenseKeyGroupStoreFactory.build(); deepFreeze(LicenseKeyGroupStore); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseKeyGroup.licenseKeyGroupsList', [LicenseKeyGroupStore]); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseKeyGroup.licenseKeyGroupsList', [LicenseKeyGroupStore]); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('post', ({options, data, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/license-key-groups`); @@ -104,6 +137,13 @@ describe('License Key Groups Module Tests', function () { }; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return LicenseKeyGroupsActionHelper.saveLicenseKeyGroup(store.dispatch, { licenseKeyGroup: LicenseKeyGroupPost, licenseModelId: LICENSE_MODEL_ID, @@ -117,6 +157,7 @@ describe('License Key Groups Module Tests', function () { const licenseKeyGroupsList = buildListFromFactory(LicenseKeyGroupStoreFactory, 1); deepFreeze(licenseKeyGroupsList); const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, licenseModel: { licenseKeyGroup: { licenseKeyGroupsList @@ -141,7 +182,16 @@ describe('License Key Groups Module Tests', function () { deepFreeze(licenseKeyGroupPutRequest); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseKeyGroup.licenseKeyGroupsList', [licenseKeyGroupUpdatedData]); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseKeyGroup.licenseKeyGroupsList', [licenseKeyGroupUpdatedData]); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('put', ({data, options, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/license-key-groups/${toBeUpdatedLicenseKeyGroupId}`); @@ -149,6 +199,13 @@ describe('License Key Groups Module Tests', function () { expect(options).toEqual(undefined); }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return LicenseKeyGroupsActionHelper.saveLicenseKeyGroup(store.dispatch, { previousLicenseKeyGroup: previousLicenseKeyGroupData, licenseKeyGroup: licenseKeyGroupUpdatedData, @@ -182,7 +239,9 @@ describe('License Key Groups Module Tests', function () { it('Add Limit', () => { - const store = storeCreator(); + const store = storeCreator({ + currentScreen: {...itemPermissionAndProps} + }); deepFreeze(store.getState()); const limitToAdd = LimitPostFactory.build(); @@ -198,7 +257,16 @@ describe('License Key Groups Module Tests', function () { deepFreeze(limitAddedItem); const licenseKeyGroup = LicenseKeyGroupStoreFactory.build(); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseKeyGroup.licenseKeyGroupsEditor.limitsList', [limitAddedItem]); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseKeyGroup.licenseKeyGroupsEditor.limitsList', [limitAddedItem]); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('post', ({data, options, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/license-key-groups/${licenseKeyGroup.id}/limits`); @@ -217,6 +285,13 @@ describe('License Key Groups Module Tests', function () { return {results: [limitAddedItem]}; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return LicenseKeyGroupsActionHelper.submitLimit(store.dispatch, { licenseModelId: LICENSE_MODEL_ID, @@ -235,6 +310,7 @@ describe('License Key Groups Module Tests', function () { deepFreeze(limitsList); const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, licenseModel: { entitlementPool: { entitlementPoolEditor: { @@ -246,7 +322,17 @@ describe('License Key Groups Module Tests', function () { deepFreeze(store.getState()); const licenseKeyGroup = LicenseKeyGroupStoreFactory.build(); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseKeyGroup.licenseKeyGroupsEditor.limitsList', []); + + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseKeyGroup.licenseKeyGroupsEditor.limitsList', []); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('destroy', ({data, options, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${LICENSE_MODEL_ID}/versions/${version.id}/license-key-groups/${licenseKeyGroup.id}/limits/${limitsList[0].id}`); @@ -266,6 +352,13 @@ describe('License Key Groups Module Tests', function () { return {results: []}; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return LicenseKeyGroupsActionHelper.deleteLimit(store.dispatch, { licenseModelId: LICENSE_MODEL_ID, version, @@ -282,6 +375,7 @@ describe('License Key Groups Module Tests', function () { deepFreeze(limitsList); const licenseKeyGroup = LicenseKeyGroupStoreFactory.build(); const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, licenseModel: { licenseKeyGroup: { licenseKeyGroupsEditor: { @@ -304,7 +398,16 @@ describe('License Key Groups Module Tests', function () { updatedLimit.unit = {choice: updatedLimit.unit, other: ''}; deepFreeze(updatedLimit); - const expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseKeyGroup.licenseKeyGroupsEditor.limitsList', [updatedLimitForPut]); + const expectedCurrentScreenProps = { + ...itemPermissionAndProps, + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isDirty: true + } + }; + + let expectedStore = cloneAndSet(store.getState(), 'licenseModel.licenseKeyGroup.licenseKeyGroupsEditor.limitsList', [updatedLimitForPut]); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); mockRest.addHandler('put', ({data, options, baseUrl}) => { @@ -321,6 +424,13 @@ describe('License Key Groups Module Tests', function () { return {results: [updatedLimitForPut]}; }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${LICENSE_MODEL_ID}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...returnedVersionFields, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: true}}; + }); + return LicenseKeyGroupsActionHelper.submitLimit(store.dispatch, { licenseModelId: LICENSE_MODEL_ID, diff --git a/openecomp-ui/test/licenseModel/overview/summary/SummaryCountList.test.js b/openecomp-ui/test/licenseModel/overview/summary/SummaryCountList.test.js index 27f7aa68fd..87e35785ca 100644 --- a/openecomp-ui/test/licenseModel/overview/summary/SummaryCountList.test.js +++ b/openecomp-ui/test/licenseModel/overview/summary/SummaryCountList.test.js @@ -55,7 +55,6 @@ describe('License Model Overview Summary Count List module test', () => { ]; var result = mapStateToProps(obj); - expect(result.isReadOnlyMode).toEqual(true); expect(result.description).toEqual(obj.licenseModel.licenseModelEditor.data.description); expect(result.counts).toEqual(counts); }); @@ -79,7 +78,7 @@ describe('License Model Overview Summary Count List module test', () => { description: { isValid : true } - } + }; var view = TestUtils.renderIntoDocument(); expect(view).toBeTruthy(); }); diff --git a/openecomp-ui/test/licenseModel/overview/summary/VendorDataView.test.js b/openecomp-ui/test/licenseModel/overview/summary/VendorDataView.test.js index 7ec85a456b..57ae2618ce 100644 --- a/openecomp-ui/test/licenseModel/overview/summary/VendorDataView.test.js +++ b/openecomp-ui/test/licenseModel/overview/summary/VendorDataView.test.js @@ -33,7 +33,6 @@ describe('License Model Overview Summary module test', () => { }; var props = mapStateToProps(state); - expect(props.isReadOnlyMode).toEqual(true); expect(props.description).toEqual(undefined); expect(props.data).toEqual(state.licenseModel.licenseModelEditor.data); @@ -41,7 +40,7 @@ describe('License Model Overview Summary module test', () => { it('jsx view test', () => { var data = LicenseModelStoreFactory.build(); - var view = TestUtils.renderIntoDocument(); + var view = TestUtils.renderIntoDocument(); expect(view).toBeTruthy(); }); diff --git a/openecomp-ui/test/licenseModel/overview/test.js b/openecomp-ui/test/licenseModel/overview/test.js index cb1a9c34b2..d881985088 100644 --- a/openecomp-ui/test/licenseModel/overview/test.js +++ b/openecomp-ui/test/licenseModel/overview/test.js @@ -47,7 +47,6 @@ describe('License Model Overview: ', function () { }; var props = mapStateToProps(state); - expect(props.isReadOnlyMode).toEqual(true); expect(props.isDisplayModal).toEqual(false); expect(props.modalHeader).toEqual(undefined); expect(props.licenseModelId).toEqual(VLM1.licenseModelEditor.data.id); @@ -79,7 +78,6 @@ describe('License Model Overview: ', function () { }; var props = mapStateToProps(state); - expect(props.isReadOnlyMode).toEqual(true); expect(props.isDisplayModal).toEqual(true); expect(props.modalHeader).toEqual(overviewEditorHeaders.LICENSE_AGREEMENT); expect(props.licenseModelId).toEqual(VLM1.licenseModelEditor.data.id); @@ -112,7 +110,6 @@ describe('License Model Overview: ', function () { }; var props = mapStateToProps(state); - expect(props.isReadOnlyMode).toEqual(true); expect(props.isDisplayModal).toEqual(true); expect(props.modalHeader).toEqual(overviewEditorHeaders.FEATURE_GROUP); expect(props.licenseModelId).toEqual(VLM1.licenseModelEditor.data.id); @@ -121,7 +118,7 @@ describe('License Model Overview: ', function () { }); it('should mapper return overview data for show EP modal', () => { - const VLM1 = LicenseModelOverviewFactory.build( { + const VLM1 = LicenseModelOverviewFactory.build({ featureGroup: { featureGroupsList: [], }, @@ -141,7 +138,6 @@ describe('License Model Overview: ', function () { }; var props = mapStateToProps(state); - expect(props.isReadOnlyMode).toEqual(true); expect(props.isDisplayModal).toEqual(true); expect(props.modalHeader).toEqual(overviewEditorHeaders.ENTITLEMENT_POOL); expect(props.licenseModelId).toEqual(VLM1.licenseModelEditor.data.id); @@ -173,7 +169,6 @@ describe('License Model Overview: ', function () { }; var props = mapStateToProps(state); - expect(props.isReadOnlyMode).toEqual(true); expect(props.isDisplayModal).toEqual(true); expect(props.modalHeader).toEqual(overviewEditorHeaders.LICENSE_KEY_GROUP); expect(props.licenseModelId).toEqual(VLM1.licenseModelEditor.data.id); @@ -233,7 +228,6 @@ describe('License Model Overview: ', function () { var props = mapStateToProps(state); - expect(props.isReadOnlyMode).toEqual(true); expect(props.isDisplayModal).toEqual(false); expect(props.modalHeader).toEqual(undefined); expect(props.licenseModelId).toEqual(VLM1.licenseModelEditor.data.id); @@ -282,7 +276,6 @@ describe('License Model Overview: ', function () { var props = mapStateToProps(state); - expect(props.isReadOnlyMode).toEqual(true); expect(props.isDisplayModal).toEqual(false); expect(props.modalHeader).toEqual(undefined); expect(props.licenseModelId).toEqual(VLM1.licenseModelEditor.data.id); @@ -310,6 +303,7 @@ describe('License Model Overview: ', function () { selectedTab: selectedButton.NOT_IN_USE } }); + const state = { licenseModel: VLM1 }; @@ -322,7 +316,6 @@ describe('License Model Overview: ', function () { var props = mapStateToProps(state); - expect(props.isReadOnlyMode).toEqual(true); expect(props.isDisplayModal).toEqual(false); expect(props.modalHeader).toEqual(undefined); expect(props.licenseModelId).toEqual(VLM1.licenseModelEditor.data.id); @@ -372,7 +365,6 @@ describe('License Model Overview: ', function () { var props = mapStateToProps(state); - expect(props.isReadOnlyMode).toEqual(true); expect(props.isDisplayModal).toEqual(false); expect(props.modalHeader).toEqual(undefined); expect(props.licenseModelId).toEqual(VLM1.licenseModelEditor.data.id); @@ -380,5 +372,4 @@ describe('License Model Overview: ', function () { expect(props.orphanDataList).toEqual(expectedLicensingDataList); expect(props.selectedTab).toEqual(selectedButton.NOT_IN_USE); }); - }); diff --git a/openecomp-ui/test/licenseModel/overview/views.test.js b/openecomp-ui/test/licenseModel/overview/views.test.js index cee34145a8..c750f3dc02 100644 --- a/openecomp-ui/test/licenseModel/overview/views.test.js +++ b/openecomp-ui/test/licenseModel/overview/views.test.js @@ -39,7 +39,7 @@ describe('License Model Overview - View: ', function () { it('should render SummaryView', () => { var renderer = TestUtils.createRenderer(); renderer.render( - + ); let renderedOutput = renderer.getRenderOutput(); expect(renderedOutput).toBeTruthy(); diff --git a/openecomp-ui/test/licenseModel/test.js b/openecomp-ui/test/licenseModel/test.js index eac1297f3e..6cb2168cbb 100644 --- a/openecomp-ui/test/licenseModel/test.js +++ b/openecomp-ui/test/licenseModel/test.js @@ -16,9 +16,15 @@ import deepFreeze from 'deep-freeze'; import mockRest from 'test-utils/MockRest.js'; import {storeCreator} from 'sdc-app/AppStore.js'; +import {cloneAndSet} from 'test-utils/Util.js'; +import LicenseModelActionHelper from 'sdc-app/onboarding/licenseModel/LicenseModelActionHelper.js'; import LicenseModelCreationActionHelper from 'sdc-app/onboarding/licenseModel/creation/LicenseModelCreationActionHelper.js'; - -import {LicenseModelPostFactory, LicenseModelDispatchFactory} from 'test-utils/factories/licenseModel/LicenseModelFactories.js'; +import {LicenseModelPostFactory, LicenseModelDispatchFactory, LicenseModelStoreFactory} from 'test-utils/factories/licenseModel/LicenseModelFactories.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; +import {default as CurrentScreenFactory} from 'test-utils/factories/common/CurrentScreenFactory.js'; +import {actionsEnum as VersionControllerActionsEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; +import {SyncStates} from 'sdc-app/common/merge/MergeEditorConstants.js'; +import {itemTypes} from 'sdc-app/onboarding/versionsPage/VersionsPageConstants.js'; describe('License Model Module Tests', function () { it('Add License Model', () => { @@ -46,4 +52,90 @@ describe('License Model Module Tests', function () { expect(response.value).toEqual(licenseModelIdFromResponse); }); }); + + it('Validating readonly screen after submit', () => { + const version = VersionFactory.build({}, {isCertified: false}); + const itemPermissionAndProps = CurrentScreenFactory.build({}, {version}); + const licenseModel = LicenseModelStoreFactory.build(); + deepFreeze(licenseModel); + + const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, + licenseModel: { + licenseModelEditor: {data: licenseModel}, + } + }); + deepFreeze(store.getState()); + + const certifiedVersion = { + ...itemPermissionAndProps.props.version, + status: 'Certified' + }; + + const expectedCurrentScreenProps = { + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isCertified: true + }, + props: { + isReadOnlyMode: true, + version: certifiedVersion + } + }; + const expectedSuccessModal = { + cancelButtonText: 'OK', + modalClassName: 'notification-modal', + msg: 'This license model successfully submitted', + timeout: 2000, + title: 'Submit Succeeded', + type: 'success' + }; + + const versionsList = { + itemType: itemTypes.LICENSE_MODEL, + itemId: licenseModel.id, + versions: [{...certifiedVersion}] + }; + + let expectedStore = store.getState(); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.props', expectedCurrentScreenProps.props); + expectedStore = cloneAndSet(expectedStore, 'modal', expectedSuccessModal); + expectedStore = cloneAndSet(expectedStore, 'versionsPage.versionsList', versionsList ); + + mockRest.addHandler('put', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${licenseModel.id}/versions/${version.id}/actions`); + expect(data).toEqual({action: VersionControllerActionsEnum.SUBMIT}); + expect(options).toEqual(undefined); + return {returnCode: 'OK'}; + }); + + mockRest.addHandler('put', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${licenseModel.id}/versions/${version.id}/actions`); + expect(data).toEqual({action: VersionControllerActionsEnum.CREATE_PACKAGE}); + expect(options).toEqual(undefined); + return {returnCode: 'OK'}; + }); + + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${licenseModel.id}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...certifiedVersion, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: false}}; + }); + + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${licenseModel.id}/versions`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: [{...certifiedVersion}]}; + }); + + return LicenseModelActionHelper.performSubmitAction(store.dispatch, { + licenseModelId: licenseModel.id, + version + }).then(() => { + expect(store.getState()).toEqual(expectedStore); + }); + }); }); diff --git a/openecomp-ui/test/nfvo-components/editor/TabulatedEditor.test.js b/openecomp-ui/test/nfvo-components/editor/TabulatedEditor.test.js index e61261e09a..5f9f06b714 100644 --- a/openecomp-ui/test/nfvo-components/editor/TabulatedEditor.test.js +++ b/openecomp-ui/test/nfvo-components/editor/TabulatedEditor.test.js @@ -18,13 +18,15 @@ import React from 'react'; import TestUtils from 'react-addons-test-utils'; import TabulatedEditor from 'nfvo-components/editor/TabulatedEditor.jsx'; +import { Provider } from 'react-redux'; +import {storeCreator} from 'sdc-app/AppStore.js'; describe('Tabulated Editor test: ', function () { - + const store = storeCreator(); it('basic view test', () => { let renderer = TestUtils.createRenderer(); renderer.render( - + ); let renderedOutput = renderer.getRenderOutput(); expect(renderedOutput).toBeTruthy(); @@ -41,11 +43,12 @@ describe('Tabulated Editor test: ', function () { isCheckedOut: false, version: {id: '0.1', label: '0.1'}, viewableVersions: [{id: '0.1', label: '0.1'}], + itemPermission: {isCertified: false, isCollaborator: true, isDirty: false}, onSubmit: ()=>{}, onRevert: ()=>{} } }; - const view = TestUtils.renderIntoDocument(); + const view = TestUtils.renderIntoDocument(); expect(view).toBeTruthy(); }); diff --git a/openecomp-ui/test/nfvo-components/modal/globalModal.test.js b/openecomp-ui/test/nfvo-components/modal/globalModal.test.js index efe43b6c37..f27b1359f8 100644 --- a/openecomp-ui/test/nfvo-components/modal/globalModal.test.js +++ b/openecomp-ui/test/nfvo-components/modal/globalModal.test.js @@ -81,10 +81,10 @@ describe('Global Modal tests: ', function () { it('checking component default render', ()=> { - expect(window.document).toBeTruthy(); - let globalModalView = TestUtils.renderIntoDocument( - {}} /> - ); + expect(window.document).toBeTruthy(); + let renderer = TestUtils.createRenderer(); + renderer.render({}} />); + let globalModalView = renderer.getRenderOutput(); expect(globalModalView).toBeTruthy(); }); diff --git a/openecomp-ui/test/nfvo-components/panel/VersionController/versionController.test.js b/openecomp-ui/test/nfvo-components/panel/VersionController/versionController.test.js index e14e9b76f5..f2db01f3f1 100644 --- a/openecomp-ui/test/nfvo-components/panel/VersionController/versionController.test.js +++ b/openecomp-ui/test/nfvo-components/panel/VersionController/versionController.test.js @@ -16,13 +16,14 @@ import React from 'react'; -import ReactDOMServer from 'react-dom/server'; + import TestUtils from 'react-addons-test-utils'; -import {mount} from 'enzyme'; import VersionController from 'nfvo-components/panel/versionController/VersionController.jsx'; -import {actionsEnum, statusEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; +import {actionsEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; import {scryRenderedDOMComponentsWithTestId} from 'test-utils/Util.js'; import {VSPComponentsVersionControllerFactory} from 'test-utils/factories/softwareProduct/SoftwareProductComponentsNetworkFactories.js'; +import { Provider } from 'react-redux'; +import {storeCreator} from 'sdc-app/AppStore.js'; describe('versionController UI Component', () => { let onSave, onClose, onVersionSwitching = onSave = onClose = () => {return Promise.resolve();}; @@ -30,42 +31,42 @@ describe('versionController UI Component', () => { const isFormDataValid = true; const viewableVersions = versionData.viewableVersions; const version = versionData.version; - const props = {onSave, onClose, isFormDataValid, viewableVersions, version, onVersionSwitching}; + const itemPermission = {isCertified: false, isCollaborator: true, isDirty: false}; + const props = {onSave, onClose, isFormDataValid, viewableVersions, version, onVersionSwitching, itemPermission}; + const store = storeCreator(); it('function does exist', () => { var renderer = TestUtils.createRenderer(); - renderer.render(); + + renderer.render(); var renderedOutput = renderer.getRenderOutput(); expect(renderedOutput).toBeTruthy(); }); - it('validating checkin function', () => { - let versionController = TestUtils.renderIntoDocument(); - let cb = action => expect(action).toBe(actionsEnum.CHECK_IN); - versionController.checkin(cb); - }); - - it('validating checkout function', () => { - let versionController = TestUtils.renderIntoDocument(); - let cb = action => expect(action).toBe(actionsEnum.CHECK_OUT); - versionController.checkout(cb); - }); - it('validating submit function', () => { - let versionController = TestUtils.renderIntoDocument(); + let provider = TestUtils.renderIntoDocument( + ); + let versionController = TestUtils.findRenderedComponentWithType( + provider, + VersionController + ); let cb = action => expect(action).toBe(actionsEnum.SUBMIT); versionController.submit(cb); }); it('validating revert function', () => { - let versionController = TestUtils.renderIntoDocument(); - let cb = action => expect(action).toBe(actionsEnum.UNDO_CHECK_OUT); - versionController.revertCheckout(cb); + let provider = TestUtils.renderIntoDocument(); + let versionController = TestUtils.findRenderedComponentWithType( + provider, + VersionController + ); + let cb = action => expect(action).toBe(actionsEnum.REVERT); + versionController.revert(cb); }); it('does not show the save button when no onSave available', () => { let noSaveProps = {...props, onSave: null }; - let versionController = TestUtils.renderIntoDocument(); + let versionController = TestUtils.renderIntoDocument(); let elem = scryRenderedDOMComponentsWithTestId(versionController,'vc-save-btn'); expect(elem).toBeTruthy(); expect(elem.length).toBe(0); @@ -73,7 +74,7 @@ describe('versionController UI Component', () => { it('does not show the submit button when no callVCAction available', () => { let callVCActionProps = {...props, callVCAction: null}; - let versionController = TestUtils.renderIntoDocument(); + let versionController = TestUtils.renderIntoDocument(); let elem = scryRenderedDOMComponentsWithTestId(versionController,'vc-submit-btn'); expect(elem).toBeTruthy(); expect(elem.length).toBe(0); @@ -81,72 +82,45 @@ describe('versionController UI Component', () => { it('does not show the revert button when no callVCAction available', () => { let callVCActionProps = {...props, callVCAction: null}; - let versionController = TestUtils.renderIntoDocument(); + let versionController = TestUtils.renderIntoDocument(); let elem = scryRenderedDOMComponentsWithTestId(versionController,'vc-revert-btn'); expect(elem).toBeTruthy(); expect(elem.length).toBe(0); }); it('Shows the save button when onSave available', () => { - let versionController = TestUtils.renderIntoDocument(); + let versionController = TestUtils.renderIntoDocument(); let elem = scryRenderedDOMComponentsWithTestId(versionController,'vc-save-btn'); expect(elem).toBeTruthy(); expect(elem.length).toBe(1); }); - it('Shows the submit button when callVCAction available', () => { - let callVCActionProps = { ...props, callVCAction: function(){} }; - let versionController = TestUtils.renderIntoDocument(); + it('Shows the submit button when callVCAction available and user is owner', () => { + const permissions = {owner: {userId: '111'}}, + userInfo = {userId: '111'}; + let callVCActionProps = { ...props, callVCAction: function(){}, permissions, userInfo}; + let versionController = TestUtils.renderIntoDocument(); let elem = scryRenderedDOMComponentsWithTestId(versionController,'vc-submit-btn'); expect(elem).toBeTruthy(); expect(elem.length).toBe(1); }); - it('Shows the revert button when callVCAction available', () => { - let callVCActionProps = { ...props, callVCAction: function(){} }; - let versionController = TestUtils.renderIntoDocument(); - let elem = scryRenderedDOMComponentsWithTestId(versionController,'vc-revert-btn'); - expect(elem).toBeTruthy(); - expect(elem.length).toBe(1); - }); - - it('Shows the checkin button', () => { - let callVCActionProps = { ...props, callVCAction: function(){} }; - let versionController = TestUtils.renderIntoDocument(); - let elem = scryRenderedDOMComponentsWithTestId(versionController,'vc-checkout-btn'); + it('Doesn\'t show the submit button when user is not owner', () => { + const permissions = {owner: {userId: '111'}}, + userInfo = {userId: '222'}; + let callVCActionProps = { ...props, callVCAction: function(){}, permissions, userInfo}; + let versionController = TestUtils.renderIntoDocument(); + let elem = scryRenderedDOMComponentsWithTestId(versionController,'vc-submit-btn'); expect(elem).toBeTruthy(); - expect(elem.length).toBe(1); + expect(elem.length).toBe(0); }); - it('Shows the checkout button', () => { + it('Shows the revert button when callVCAction available', () => { let callVCActionProps = { ...props, callVCAction: function(){} }; - let versionController = TestUtils.renderIntoDocument(); - let elem = scryRenderedDOMComponentsWithTestId(versionController,'vc-checkout-btn'); - expect(elem).toBeTruthy(); - expect(elem.length).toBe(1); - - }); - - it('Doesn\'t show the checkin button for prev version', () => { - let callVCActionProps = { ...props, version: '1.0', callVCAction: function(){} }; - let versionController = mount(); - let elem = versionController.find('[data-test-id="vc-checkout-btn"]'); - - expect(elem).toBeTruthy(); - expect(elem.length).toEqual(1); - expect(elem.find('.svg-icon').length).toEqual(1); - expect(elem.find('.svg-icon').hasClass('disabled')).toBe(true); - }); - - it('Doesn\'t show the checkout button', () => { - let callVCActionProps = { ...props, version: '1.0', callVCAction: function(){} }; - let versionController = mount(); - let elem = versionController.find('[data-test-id="vc-checkout-btn"]'); + let versionController = TestUtils.renderIntoDocument(); + let elem = scryRenderedDOMComponentsWithTestId(versionController,'vc-revert-btn'); expect(elem).toBeTruthy(); expect(elem.length).toBe(1); - expect(elem.find('.svg-icon').length).toEqual(1); - expect(elem.find('.svg-icon').hasClass('disabled')).toBe(true); - }); }); diff --git a/openecomp-ui/test/nfvo-components/panel/VersionController/versionControllerUtils.test.js b/openecomp-ui/test/nfvo-components/panel/VersionController/versionControllerUtils.test.js deleted file mode 100644 index d654e16ddf..0000000000 --- a/openecomp-ui/test/nfvo-components/panel/VersionController/versionControllerUtils.test.js +++ /dev/null @@ -1,128 +0,0 @@ -/*! - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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. - */ - - -import Configuration from 'sdc-app/config/Configuration.js'; -import VersionControllerUtils from 'nfvo-components/panel/versionController/VersionControllerUtils.js'; -import {statusEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; - -const status = 'testStatus'; -const {lockingUser: currentUser, viewableVersions: defaultVersions} = VersionControllerUtilsFactory.build(); - -describe('versionController UI Component', () => { - - it('function does exist', () => { - expect(VersionControllerUtils).toBeTruthy(); - }); - - it('validating getCheckOutStatusKindByUserID - without "UserID"', () => { - var result = VersionControllerUtils.getCheckOutStatusKindByUserID(status); - expect(result.status).toBe(status); - expect(result.isCheckedOut).toBe(false); - }); - - it('validating getCheckOutStatusKindByUserID - without "UserID" with locking user', () => { - var result = VersionControllerUtils.getCheckOutStatusKindByUserID(status, 'locking user'); - expect(result.status).toBe(statusEnum.LOCK_STATUS); - expect(result.isCheckedOut).toBe(false); - }); - - it('validating getCheckOutStatusKindByUserID - with "UserID" with configuration set', () => { - const Uid = 'ecomp'; - - Configuration.set('UserID', Uid); - var result = VersionControllerUtils.getCheckOutStatusKindByUserID(status, Uid); - Configuration.set('UserID', undefined); - expect(result.status).toBe(status); - expect(result.isCheckedOut).toBe(true); - }); - - - - it('validating isCheckedOutByCurrentUser - when resource is not checked out', () => { - const resource = VersionControllerUtilsFactory.build({status: statusEnum.SUBMIT_STATUS}); - - Configuration.set('UserID', currentUser); - const result = VersionControllerUtils.isCheckedOutByCurrentUser(resource); - Configuration.set('UserID', undefined); - - expect(result).toBe(false); - }); - - it('validating isCheckedOutByCurrentUser - when resource is checked out', () => { - const resource = VersionControllerUtilsFactory.build(); - - Configuration.set('UserID', currentUser); - const result = VersionControllerUtils.isCheckedOutByCurrentUser(resource); - Configuration.set('UserID', undefined); - - expect(result).toBe(true); - }); - - it('validating isCheckedOutByCurrentUser - when resource is checked out by another user', () => { - const resource = VersionControllerUtilsFactory.build({lockingUser: 'another'}); - - Configuration.set('UserID', currentUser); - const result = VersionControllerUtils.isCheckedOutByCurrentUser(resource); - Configuration.set('UserID', undefined); - - expect(result).toBe(false); - }); - - - - it('validating isReadOnly - when resource is not checked out', () => { - const resource = VersionControllerUtilsFactory.build({status: statusEnum.SUBMIT_STATUS}); - - Configuration.set('UserID', currentUser); - const result = VersionControllerUtils.isReadOnly(resource); - Configuration.set('UserID', undefined); - - expect(result).toBe(true); - }); - - it('validating isReadOnly - when resource is checked out', () => { - const resource = VersionControllerUtilsFactory.build(); - - Configuration.set('UserID', currentUser); - const result = VersionControllerUtils.isReadOnly(resource); - Configuration.set('UserID', undefined); - - expect(result).toBe(false); - }); - - it('validating isReadOnly - when version of resource is not latest', () => { - - const resource = VersionControllerUtilsFactory.build({version: defaultVersions[defaultVersions.length - 2]}); - - Configuration.set('UserID', currentUser); - const result = VersionControllerUtils.isReadOnly(resource); - Configuration.set('UserID', undefined); - - expect(result).toBe(true); - }); - - it('validating isReadOnly - when resource is checked out by another user', () => { - const resource = VersionControllerUtilsFactory.build({lockingUser: 'another'}); - - Configuration.set('UserID', currentUser); - const result = VersionControllerUtils.isReadOnly(resource); - Configuration.set('UserID', undefined); - - expect(result).toBe(true); - }); -}); diff --git a/openecomp-ui/test/nfvo-components/tree/tree.test.js b/openecomp-ui/test/nfvo-components/tree/tree.test.js new file mode 100644 index 0000000000..95d0ae7f87 --- /dev/null +++ b/openecomp-ui/test/nfvo-components/tree/tree.test.js @@ -0,0 +1,31 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +import Tree from 'nfvo-components/tree/Tree.jsx'; + +describe('Tree Module Tests', function () { + + it('Tree view should exist', () => { + expect(Tree).toBeTruthy(); + }); + + it('should render Tree and call onNodeClick', done => { + const tree = [{id: '123', name: '', parent: ''}]; + let treeView = new Tree({nodes: tree, onNodeClick: () => done()}); + expect(treeView).toBeTruthy(); + treeView.onNodeClick(tree[0]); + }); + +}); diff --git a/openecomp-ui/test/onboard/onboardingCatalog/views.test.js b/openecomp-ui/test/onboard/onboardingCatalog/views.test.js index fb038eb680..fedd25b160 100644 --- a/openecomp-ui/test/onboard/onboardingCatalog/views.test.js +++ b/openecomp-ui/test/onboard/onboardingCatalog/views.test.js @@ -20,6 +20,7 @@ import {defaultStoreFactory} from 'test-utils/factories/onboard/OnboardingCatalo import {FinalizedLicenseModelFactory} from 'test-utils/factories/licenseModel/LicenseModelFactories.js'; import {VSPEditorFactory} from 'test-utils/factories/softwareProduct/SoftwareProductEditorFactories.js'; import {mapStateToProps} from 'sdc-app/onboarding/onboard/Onboard.js'; +import {catalogItemTypes} from 'sdc-app/onboarding/onboard/onboardingCatalog/OnboardingCatalogConstants.js'; import OnboardingCatalogView from 'sdc-app/onboarding/onboard/onboardingCatalog/OnboardingCatalogView.jsx'; import VendorItem from 'sdc-app/onboarding/onboard/onboardingCatalog/VendorItem.jsx'; import VSPOverlay from 'sdc-app/onboarding/onboard/onboardingCatalog/VSPOverlay.jsx'; @@ -49,9 +50,9 @@ describe('OnBoarding Catalog test - View: ', function () { it('licenseModelList creating algorithm test', () => { const finalizedLicenseModelList = FinalizedLicenseModelFactory.buildList(3); - const licenseModelList = [...finalizedLicenseModelList]; - const finalizedSoftwareProductList = VSPEditorFactory.buildList(4 ,{vendorId: finalizedLicenseModelList[0].id}); - const softwareProductList = [...finalizedSoftwareProductList]; + const licenseModelList = FinalizedLicenseModelFactory.buildList(3); + const finalizedSoftwareProductList = VSPEditorFactory.buildList(4, {vendorId: finalizedLicenseModelList[0].id}); + const softwareProductList = VSPEditorFactory.buildList(4, {vendorId: finalizedLicenseModelList[1].id}); const data = defaultStoreFactory.build({licenseModelList, finalizedLicenseModelList, softwareProductList, finalizedSoftwareProductList}); var results = mapStateToProps(data); @@ -63,7 +64,7 @@ describe('OnBoarding Catalog test - View: ', function () { const dummyFunc = () => {}; const licenseModelList = FinalizedLicenseModelFactory.buildList(3); - const softwareProductList = VSPEditorFactory.buildList(4 ,{vendorId: licenseModelList[0].id}); + const softwareProductList = VSPEditorFactory.buildList(4, {vendorId: licenseModelList[0].id}); const data = defaultStoreFactory.build({licenseModelList, softwareProductList}); const func = { @@ -118,7 +119,7 @@ describe('OnBoarding Catalog test - View: ', function () { let params = { catalogItemData: FinalizedLicenseModelFactory.build(), onSelect: () => {}, - catalogItemTypeClass: '' + catalogItemTypeClass: catalogItemTypes.LICENSE_MODEL }; let CatalogItemDetailsView = TestUtils.renderIntoDocument(
    ); diff --git a/openecomp-ui/test/permissions/permissionsManaager.test.js b/openecomp-ui/test/permissions/permissionsManaager.test.js new file mode 100644 index 0000000000..2d880c7ce0 --- /dev/null +++ b/openecomp-ui/test/permissions/permissionsManaager.test.js @@ -0,0 +1,110 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import React from 'react'; +import TestUtils from 'react-addons-test-utils'; + +import {UserFactory} from 'test-utils/factories/users/UsersFactories.js'; +import {mapStateToProps} from 'sdc-app/onboarding/permissions/PermissionsManager.js'; +import PermissionsManager from 'sdc-app/onboarding/permissions/PermissionsManager.jsx'; + + + +describe('Manage Permissions: ', function () { + let globalItemId = '343434', usersList = [], userInfo = {}, versionsPage = {}, contributor = {}, contributorToAdd = {}, owner = {}; + beforeAll(function() { + usersList = UserFactory.buildList(3); + userInfo = usersList[0]; + owner = usersList[0]; + contributor = usersList[1]; + contributorToAdd = usersList[2]; + versionsPage = { + permissions: { + owner: owner, + contributors: [contributor], + viewers: [] + } + }; + }); + + it('should mapper exist', () => { + expect(mapStateToProps).toBeTruthy(); + }); + + it('should mapper return basic permissions page data', () => { + const obj = {versionsPage, users: {usersList, userInfo}}; + const result = mapStateToProps(obj); + result.itemId = globalItemId; + expect(result.owner).toBeTruthy(); + expect(result.itemUsers).toBeTruthy(); + expect(result.userInfo).toBeTruthy(); + expect(result.itemId).toBeTruthy(); + expect(result.users).toBeTruthy(); + }); + + it('permission manager basic view', () => { + + const obj = {versionsPage, users: {usersList, userInfo}}; + const params = mapStateToProps(obj); + let permissionsView = TestUtils.renderIntoDocument(); + expect(permissionsView).toBeTruthy(); + }); + + it('permisssion manager onChange contributors test', () => { + + const obj = {versionsPage, users: {usersList, userInfo}}; + const params = mapStateToProps(obj); + params.itemId = globalItemId; + let permissionsView = TestUtils.renderIntoDocument(); + expect(permissionsView).toBeTruthy(); + const userToAdd = { + value: contributorToAdd.userId, + label: contributorToAdd.fullName + }; + let itemUsers = [{...userToAdd}]; + + permissionsView.onChangeItemUsers({itemUsers}); + expect(permissionsView.state.itemUsers[0].userId).toEqual(userToAdd.value); + }); + + it('permisssion manager onSave contributors test', () => { + + const obj = {versionsPage, users: {usersList, userInfo}}; + let params = mapStateToProps(obj); + params.itemId = globalItemId; + const userToAdd = { + value: contributorToAdd.userId, + label: contributorToAdd.fullName + }; + let itemUsers = [{...userToAdd}]; + + + params.onSubmit = ({itemId, addedUsersIds, removedUsersIds, allUsers, owner}) => { + expect(itemId).toEqual(globalItemId); + expect(addedUsersIds[0]).toEqual(contributorToAdd.userId); + expect(removedUsersIds[0]).toEqual(contributor.userId); + expect(allUsers).toEqual(usersList); + expect(owner).toEqual(owner); + }; + let permissionsView = TestUtils.renderIntoDocument(); + expect(permissionsView).toBeTruthy(); + permissionsView.onChangeItemUsers({itemUsers}); + permissionsView.onsaveItemUsers(); + }); + + + +}); \ No newline at end of file diff --git a/openecomp-ui/test/revisions/revisions.test.js b/openecomp-ui/test/revisions/revisions.test.js new file mode 100644 index 0000000000..1b5f35c9db --- /dev/null +++ b/openecomp-ui/test/revisions/revisions.test.js @@ -0,0 +1,240 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import React from 'react'; +import TestUtils from 'react-addons-test-utils'; +import {scryRenderedDOMComponentsWithTestId} from 'test-utils/Util.js'; +import deepFreeze from 'deep-freeze'; +import mockRest from 'test-utils/MockRest.js'; +import {cloneAndSet} from 'test-utils/Util.js'; +import {storeCreator} from 'sdc-app/AppStore.js'; + +import {actionsEnum as vcActionsEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; +import Configuration from 'sdc-app/config/Configuration.js'; +import {mapStateToProps, mapActionsToProps} from 'sdc-app/onboarding/revisions/Revisions.js'; +import RevisionsView from 'sdc-app/onboarding/revisions/RevisionsView.jsx'; +import RevisionsActionHelper from 'sdc-app/onboarding/revisions/RevisionsActionHelper.js'; +import {RevisionsPagePropsFactory} from 'test-utils/factories/revisions/RevisionsFactories.js'; +import {UserFactory} from 'test-utils/factories/users/UsersFactories.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; +import {screenTypes} from 'sdc-app/onboarding/OnboardingConstants.js'; +import ReactTestUtils from 'react-addons-test-utils'; +import {enums} from 'sdc-app/onboarding/OnboardingConstants.js'; + +const state = {}; +state.revisions = RevisionsPagePropsFactory.buildList(2); +state.users = {usersList : UserFactory.buildList(2)}; +state.revisions[0].user = state.users.usersList[0].userId; +state.revisions[1].user = state.users.usersList[1].userId; + + +describe('Revision List Tests', () => { + /* + it ('mapStateToProps mapper exists', () => { + + expect(mapStateToProps).toBeTruthy(); + + }); + + it ('should have state in props', () => { + + const props = mapStateToProps(state); + expect(props.revisions.length).toEqual(2); + + }); + + it('simple jsx test', () => { + + const store = storeCreator(); + const dispatch = store.dispatch; + + const props = Object.assign({}, mapStateToProps(state), mapActionsToProps(dispatch, {})); + const renderer = TestUtils.createRenderer(); + renderer.render(); + + const renderedOutput = renderer.getRenderOutput(); + expect(renderedOutput).toBeTruthy(); + + }); + + it('get list data', () => { + + const store = storeCreator(); + const dispatch = store.dispatch; + + const props = Object.assign({}, mapStateToProps(state), mapActionsToProps(dispatch, {})); + + let revisionsView = TestUtils.renderIntoDocument( + + ); + let list = scryRenderedDOMComponentsWithTestId(revisionsView,'revision-list-item'); + expect(list.length).toEqual(props.revisions.length); + let revert = scryRenderedDOMComponentsWithTestId(revisionsView,'form-submit-button'); + expect(revert[0].innerHTML).toEqual('Revert'); + let date = scryRenderedDOMComponentsWithTestId(revisionsView,'revision-date'); + expect(date.length).toEqual(props.revisions.length); + expect(date[0].children[0].className).toEqual('revision-date'); + expect(date[0].children[1].className).toEqual('revision-time'); + let user = ReactTestUtils.scryRenderedDOMComponentsWithClass(revisionsView, 'svg-icon-label'); + expect(user[0].innerHTML).toEqual(state.users.usersList[0].fullName); + expect(user[1].innerHTML).toEqual(state.users.usersList[1].fullName); + let message = scryRenderedDOMComponentsWithTestId(revisionsView,'revision-message'); + expect(message[0].children[0].innerHTML).toEqual('Show Message With More Mock'); + expect(message[1].children[0].innerHTML).toEqual('Show Message Mock'); + }); +*/ + +}); + + +describe('Revisions Action Helper', () => { + let store, dispatch, restPrefix = '', revisions, version; + let itemId = 'testRevisionId'; + + beforeAll(() => { + restPrefix = Configuration.get('restPrefix'); + store = storeCreator(); + dispatch = store.dispatch; + deepFreeze(store.getState()); + revisions = RevisionsPagePropsFactory.buildList(2); + version = VersionFactory.build(); + }); + + beforeEach(() => { + mockRest.resetQueue(); + }); + + + + it('Get revisions list', () => { + + const expectedStore = cloneAndSet(store.getState(), 'revisions', revisions); + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`${restPrefix}/v1.0/items/${itemId}/versions/${version.id}/revisions`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: revisions}; + }); + + return RevisionsActionHelper.fetchRevisions(dispatch, {itemId, version}).then(() => { + expect(store.getState()).toEqual(expectedStore); + expect(store.getState().revisions.length).toEqual(2); + }); + }); +/* + it('Revert to revision software product model', () => { + mockRest.resetQueue(); + let revisionId = revisions[1].id; + mockRest.addHandler('put', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`${restPrefix}/v1.0/items/${itemId}/versions/${version.id}/actions`); + expect(data).toEqual({ + action: vcActionsEnum.REVERT, + revisionRequest: { + revisionId: revisionId + } + + }); + expect(options).toEqual(undefined); + return {results: {}}; + }); + + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`${restPrefix}/v1.0/items/${itemId}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: {}}; + }); + + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`${restPrefix}/v1.0/vendor-software-products/${itemId}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: {}}; + }); + + + + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`${restPrefix}/v1.0/vendor-software-products/${itemId}/versions/${version.id}/questionnaire`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {data: JSON.stringify({}), schema: JSON.stringify({})}; + }); + + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`${restPrefix}/v1.0/vendor-software-products/${itemId}/versions/${version.id}/components`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: {}}; + }); + + + return RevisionsActionHelper.revertToRevision(dispatch, {itemId, version, revisionId, itemType: screenTypes.SOFTWARE_PRODUCT}).then(() => { + }); + + }); +*/ + it('Revert to revision license model', () => { + + let revisionId = revisions[0].id; + mockRest.addHandler('put', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`${restPrefix}/v1.0/items/${itemId}/versions/${version.id}/actions`); + expect(data).toEqual({ + action: vcActionsEnum.REVERT, + revisionRequest: { + revisionId: revisionId + } + + }); + expect(options).toEqual(undefined); + return {results: {}}; + }); + + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`${restPrefix}/v1.0/items/${itemId}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: {}}; + }); + + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`${restPrefix}/v1.0/vendor-license-models/${itemId}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: {}}; + }); + + + let vlmFetched = ['license-agreements', 'feature-groups', 'entitlement-pools', 'license-key-groups']; + vlmFetched.forEach(fetchCall => { + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`${restPrefix}/v1.0/vendor-license-models/${itemId}/versions/${version.id}/` + fetchCall); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: {}}; + }); + }); + + + return RevisionsActionHelper.revertToRevision(dispatch, {itemId, version, revisionId, itemType: screenTypes.LICENSE_MODEL}).then(() => { + }); + + }); + + + + +}); diff --git a/openecomp-ui/test/softwareProduct/attachments/validation/HeatValidationView.test.js b/openecomp-ui/test/softwareProduct/attachments/validation/HeatValidationView.test.js index a5ba297d2b..a0a8a42660 100644 --- a/openecomp-ui/test/softwareProduct/attachments/validation/HeatValidationView.test.js +++ b/openecomp-ui/test/softwareProduct/attachments/validation/HeatValidationView.test.js @@ -19,8 +19,6 @@ import TestUtils from 'react-addons-test-utils'; import {mapStateToProps} from 'sdc-app/onboarding/softwareProduct/attachments/validation/HeatValidation.js'; import HeatValidationView from 'sdc-app/onboarding/softwareProduct/attachments/validation/HeatValidationView.jsx'; -import {statusEnum as versionStatusEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; - describe('SoftwareProductAttachments Modal Mapper and View Classes', () => { @@ -41,7 +39,6 @@ describe('SoftwareProductAttachments Modal Mapper and View Classes', () => { id: 'D4774719D085414E9D5642D1ACD59D20', version: '0.10', viewableVersions: ['0.1', '0.2'], - status: versionStatusEnum.CHECK_OUT_STATUS, lockingUser: 'cs0008' }; const atTree = { diff --git a/openecomp-ui/test/softwareProduct/components/compute/SoftwareProductComponentComputeEditor.test.js b/openecomp-ui/test/softwareProduct/components/compute/SoftwareProductComponentComputeEditor.test.js index c14246f810..07268e514c 100644 --- a/openecomp-ui/test/softwareProduct/components/compute/SoftwareProductComponentComputeEditor.test.js +++ b/openecomp-ui/test/softwareProduct/components/compute/SoftwareProductComponentComputeEditor.test.js @@ -21,7 +21,7 @@ import ComputeEditorView from 'sdc-app/onboarding/softwareProduct/components/com import {SoftwareProductFactory} from 'test-utils/factories/softwareProduct/SoftwareProductFactory.js'; import {VSPEditorFactory} from 'test-utils/factories/softwareProduct/SoftwareProductEditorFactories.js'; import {ComputeFlavorBaseData, ComputeFlavorQData, VSPComponentsComputeDataMapFactory} from 'test-utils/factories/softwareProduct/SoftwareProductComponentsComputeFactory.js'; - +import CurrentScreenFactory from 'test-utils/factories/common/CurrentScreenFactory.js'; describe('Software Product Component Compute-Editor Mapper and View Classes.', () => { @@ -33,6 +33,7 @@ describe('Software Product Component Compute-Editor Mapper and View Classes.', ( const currentSoftwareProduct = VSPEditorFactory.build(); var obj = { + currentScreen: CurrentScreenFactory.build(), softwareProduct: SoftwareProductFactory.build({ softwareProductEditor: { data: currentSoftwareProduct @@ -58,7 +59,7 @@ describe('Software Product Component Compute-Editor Mapper and View Classes.', ( expect(results.qgenericFieldInfo).toBeTruthy(); expect(results.dataMap).toBeTruthy(); expect(results.genericFieldInfo).toBeTruthy(); - expect(results.isReadOnlyMode).toBeTruthy(); + expect(results.isReadOnlyMode).toBe(false); expect(results.isFormValid).toBeTruthy(); expect(results.formReady).toBeTruthy(); }); diff --git a/openecomp-ui/test/softwareProduct/components/compute/VSPComponentComputeActionHelperHeatMode.test.js b/openecomp-ui/test/softwareProduct/components/compute/VSPComponentComputeActionHelperHeatMode.test.js index 4fe9408e34..e8195314b4 100644 --- a/openecomp-ui/test/softwareProduct/components/compute/VSPComponentComputeActionHelperHeatMode.test.js +++ b/openecomp-ui/test/softwareProduct/components/compute/VSPComponentComputeActionHelperHeatMode.test.js @@ -22,11 +22,11 @@ import Configuration from 'sdc-app/config/Configuration.js'; import SoftwareProductComponentsActionHelper from 'sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js'; import {ComputeFlavorQData, VSPComponentsComputeDataMapFactory} from 'test-utils/factories/softwareProduct/SoftwareProductComponentsComputeFactory.js'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; const softwareProductId = '123'; const vspComponentId = '111'; -const version = VersionControllerUtilsFactory.build().version; +const version = VersionFactory.build(); describe('Software Product Components Compute Module Tests - HEAT mode', function () { diff --git a/openecomp-ui/test/softwareProduct/components/compute/VSPComponentComputeActionHelperManualMode.test.js b/openecomp-ui/test/softwareProduct/components/compute/VSPComponentComputeActionHelperManualMode.test.js index ca3d12f3e9..addd800c43 100644 --- a/openecomp-ui/test/softwareProduct/components/compute/VSPComponentComputeActionHelperManualMode.test.js +++ b/openecomp-ui/test/softwareProduct/components/compute/VSPComponentComputeActionHelperManualMode.test.js @@ -19,14 +19,14 @@ import {cloneAndSet} from 'test-utils/Util.js'; import {storeCreator} from 'sdc-app/AppStore.js'; import Configuration from 'sdc-app/config/Configuration.js'; import ComputeFlavorActionHelper from 'sdc-app/onboarding/softwareProduct/components/compute/ComputeFlavorActionHelper.js'; -import {VSPEditorFactory} from 'test-utils/factories/softwareProduct/SoftwareProductEditorFactories.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; import {ComputeFlavorQData, ComputeFlavorBaseData, ComponentComputeFactory, VSPComponentsComputeDataMapFactory} from 'test-utils/factories/softwareProduct/SoftwareProductComponentsComputeFactory.js'; const softwareProductId = '123'; const vspComponentId = '111'; const computeId = '111'; -const version = VSPEditorFactory.build().version; +const version = VersionFactory.build(); describe('Software Product Components Compute Module Tests - Manual mode', function () { @@ -92,16 +92,6 @@ describe('Software Product Components Compute Module Tests - Manual mode', funct }; deepFreeze(softwareProductComponentCompute); - - const expectedStore = cloneAndSet(store.getState(), 'softwareProduct.softwareProductComponents.computeFlavor.computeEditor', { - data: computeData, - qdata, - dataMap, - qgenericFieldInfo: {}, - genericFieldInfo: {}, - formReady: true - }); - mockRest.addHandler('fetch', ({options, data, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/components/${vspComponentId}/compute-flavors/${computeId}`); expect(data).toEqual(undefined); @@ -109,15 +99,18 @@ describe('Software Product Components Compute Module Tests - Manual mode', funct return {data: computeData}; }); mockRest.addHandler('fetch', ({options, data, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/components/${vspComponentId}/compute-flavors/${computeId}/questionnaire`); + expect(baseUrl).toEqual( + `/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/components/${vspComponentId}/compute-flavors/${computeId}/questionnaire` + ); expect(data).toEqual(undefined); expect(options).toEqual(undefined); return softwareProductComponentCompute; }); - return ComputeFlavorActionHelper.loadComputeData({softwareProductId, componentId: vspComponentId, version, computeId}).then(() => { - ComputeFlavorActionHelper.loadComputeQuestionnaire(store.dispatch, {softwareProductId, componentId: vspComponentId, computeId, version}).then(() => - expect(store.getState()).toEqual(expectedStore)); + return ComputeFlavorActionHelper.loadCompute(store.dispatch, {softwareProductId, componentId: vspComponentId, version, computeId}).then(() => { + expect(store.getState().softwareProduct.softwareProductComponents.computeFlavor.computeEditor.data).toEqual(computeData); + expect(store.getState().softwareProduct.softwareProductComponents.computeFlavor.computeEditor.qdata).toEqual(qdata); + expect(store.getState().softwareProduct.softwareProductComponents.computeFlavor.computeEditor.dataMap).toEqual(dataMap); }); }); @@ -142,7 +135,9 @@ describe('Software Product Components Compute Module Tests - Manual mode', funct deepFreeze(expectedStore); mockRest.addHandler('put', ({options, data, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/components/${vspComponentId}/compute-flavors/${computeId}/questionnaire`); + expect(baseUrl).toEqual( + `/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/components/${vspComponentId}/compute-flavors/${computeId}/questionnaire` + ); expect(data).toEqual(qdata); expect(options).toEqual(undefined); return {returnCode: 'OK'}; diff --git a/openecomp-ui/test/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoring.test.js b/openecomp-ui/test/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoring.test.js index 423a7b39f6..21e58057e9 100644 --- a/openecomp-ui/test/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoring.test.js +++ b/openecomp-ui/test/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoring.test.js @@ -85,24 +85,18 @@ describe('SoftwareProductComponentsMonitoring Module Tests', function () { expect(renderedOutput).toBeTruthy(); }); - it('should change state to dragging', done => { + it('should change state to dragging', () => { var view = TestUtils.renderIntoDocument(); expect(view.state.dragging).toBe(false); view.handleOnDragEnter(false); - setTimeout(()=> { - expect(view.state.dragging).toBe(true); - done(); - }, 100); + expect(view.state.dragging).toBe(true); }); - it('should not change state to dragging', done => { + it('should not change state to dragging', () => { var view = TestUtils.renderIntoDocument(); expect(view.state.dragging).toBe(false); view.handleOnDragEnter(true); - setTimeout(()=> { - expect(view.state.dragging).toBe(false); - done(); - }, 0); + expect(view.state.dragging).toBe(false); }); }); diff --git a/openecomp-ui/test/softwareProduct/components/monitoring/test.js b/openecomp-ui/test/softwareProduct/components/monitoring/test.js index 8fafcdb968..50fda91871 100644 --- a/openecomp-ui/test/softwareProduct/components/monitoring/test.js +++ b/openecomp-ui/test/softwareProduct/components/monitoring/test.js @@ -16,16 +16,14 @@ import mockRest from 'test-utils/MockRest.js'; import {storeCreator} from 'sdc-app/AppStore.js'; -import SoftwareProductComponentsMonitoringConstants from 'sdc-app/onboarding/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoringConstants.js'; import SoftwareProductComponentsMonitoringActionHelper from 'sdc-app/onboarding/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoringActionHelper.js'; import {fileTypes} from 'sdc-app/onboarding/softwareProduct/components/monitoring/SoftwareProductComponentsMonitoringConstants.js'; - +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; import {VSPComponentsMonitoringRestFactory, trap, poll, ves} from 'test-utils/factories/softwareProduct/SoftwareProductComponentsMonitoringFactories.js'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; const softwareProductId = '123'; const componentId = '123'; -const version = VersionControllerUtilsFactory.build().version; +const version = VersionFactory.build(); describe('Software Product Components Monitoring Module Tests', function () { @@ -132,7 +130,7 @@ describe('Software Product Components Monitoring Module Tests', function () { version, componentId, type: fileTypes.SNMP_TRAP - }).then((dispatch) => { + }).then(() => { var {softwareProduct: {softwareProductComponents: {monitoring}}} = store.getState(); expect(monitoring[trap]).toEqual(undefined); done(); diff --git a/openecomp-ui/test/softwareProduct/components/network/SoftwareProductComponentsNICEditor.test.js b/openecomp-ui/test/softwareProduct/components/network/SoftwareProductComponentsNICEditor.test.js index 094b95a091..78d88b008a 100644 --- a/openecomp-ui/test/softwareProduct/components/network/SoftwareProductComponentsNICEditor.test.js +++ b/openecomp-ui/test/softwareProduct/components/network/SoftwareProductComponentsNICEditor.test.js @@ -23,6 +23,7 @@ import {VSPEditorFactory} from 'test-utils/factories/softwareProduct/SoftwarePro import {SoftwareProductFactory} from 'test-utils/factories/softwareProduct/SoftwareProductFactory.js'; import {VSPComponentsNicFactory, VSPComponentsNetworkQDataFactory, VSPComponentsNicFactoryQGenericFieldInfo, VSPComponentsNicFactoryGenericFieldInfo, VSPComponentsNetworkDataMapFactory} from 'test-utils/factories/softwareProduct/SoftwareProductComponentsNetworkFactories.js'; +import CurrentScreenFactory from 'test-utils/factories/common/CurrentScreenFactory.js'; describe('Software Product Component Network NIC Editor and View Classes', () => { it('mapStateToProps mapper exists', () => { @@ -34,8 +35,8 @@ describe('Software Product Component Network NIC Editor and View Classes', () => const currentSoftwareProduct = VSPEditorFactory.build(); - var obj = { + currentScreen: CurrentScreenFactory.build(), softwareProduct: SoftwareProductFactory.build({ softwareProductEditor: { data: currentSoftwareProduct @@ -55,12 +56,14 @@ describe('Software Product Component Network NIC Editor and View Classes', () => }; var results = mapStateToProps(obj); + expect(results.isReadOnlyMode).toBe(false); expect(results.currentSoftwareProduct).toBeTruthy(); expect(results.qdata).toBeTruthy(); expect(results.dataMap).toBeTruthy(); expect(results.genericFieldInfo).toBeTruthy(); expect(results.qgenericFieldInfo).toBeTruthy(); expect(results.data).toBeTruthy(); + }); diff --git a/openecomp-ui/test/softwareProduct/components/network/SoftwareProductComponentsNetworkActionHelper.test.js b/openecomp-ui/test/softwareProduct/components/network/SoftwareProductComponentsNetworkActionHelper.test.js index b6050265a6..11a0ca787f 100644 --- a/openecomp-ui/test/softwareProduct/components/network/SoftwareProductComponentsNetworkActionHelper.test.js +++ b/openecomp-ui/test/softwareProduct/components/network/SoftwareProductComponentsNetworkActionHelper.test.js @@ -19,15 +19,20 @@ import {cloneAndSet} from 'test-utils/Util.js'; import {storeCreator} from 'sdc-app/AppStore.js'; import SoftwareProductComponentsNetworkActionHelper from 'sdc-app/onboarding/softwareProduct/components/network/SoftwareProductComponentsNetworkActionHelper.js'; -import {VSPComponentsNicPostFactory, VSPComponentsNicFactory, VSPComponentsNetworkFactory, VSPComponentsNetworkQDataFactory, VSPComponentsNetworkDataMapFactory, VSPComponentsNicFactoryGenericFieldInfo} from 'test-utils/factories/softwareProduct/SoftwareProductComponentsNetworkFactories.js'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; +import {VSPComponentsNicFactory, + VSPComponentsNicPostFactory, + VSPComponentsNetworkFactory, + VSPComponentsNetworkQDataFactory, + VSPComponentsNetworkDataMapFactory, + VSPComponentsNicFactoryGenericFieldInfo} from 'test-utils/factories/softwareProduct/SoftwareProductComponentsNetworkFactories.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; import VSPQSchemaFactory from 'test-utils/factories/softwareProduct/SoftwareProductQSchemaFactory.js'; import {forms} from 'sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsConstants.js'; const softwareProductId = '123'; const componentId = '321'; const nicId = '111'; -const version = VersionControllerUtilsFactory.build().version; +const version = VersionFactory.build(); describe('Software Product Components Network Action Helper Tests', function () { @@ -55,60 +60,62 @@ describe('Software Product Components Network Action Helper Tests', function () }); }); + it('Add NIC', () => { - const store = storeCreator(); - deepFreeze(store.getState()); - - const NICPostRequest = VSPComponentsNicPostFactory.build(); - - const expectedNIC = VSPComponentsNicFactory.build({...NICPostRequest, id: nicId}); - - mockRest.addHandler('post', ({options, data, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/components/${componentId}/nics`); - expect(data).toEqual(NICPostRequest); - expect(options).toEqual(undefined); - return { - nicId - }; - }); - - mockRest.addHandler('fetch', ({options, data, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/components/${componentId}/nics`); - expect(data).toEqual(undefined); - expect(options).toEqual(undefined); - return {results: [expectedNIC]}; - }); - - mockRest.addHandler('destroy', ({options, data, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/components/${componentId}/nics/${nicId}`); - expect(data).toEqual(undefined); - expect(options).toEqual(undefined); - return {}; - }); - - mockRest.addHandler('fetch', ({options, data, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/components/${componentId}/nics`); - expect(data).toEqual(undefined); - expect(options).toEqual(undefined); - return {results: []}; - }); - - const network = VSPComponentsNetworkFactory.build({ - nicList: [expectedNIC] - }); - - const networkAfterDelete = VSPComponentsNetworkFactory.build(); - - let expectedStore = cloneAndSet(store.getState(), 'softwareProduct.softwareProductComponents.network', network); - - return SoftwareProductComponentsNetworkActionHelper.createNIC(store.dispatch, {nic: NICPostRequest, softwareProductId, componentId, version}).then(() => { - expect(store.getState()).toEqual(expectedStore); - return SoftwareProductComponentsNetworkActionHelper.deleteNIC(store.dispatch, {softwareProductId, componentId, nicId, version}); - }).then(() => { - let expectedStore = cloneAndSet(store.getState(), 'softwareProduct.softwareProductComponents.network', networkAfterDelete); - expect(store.getState()).toEqual(expectedStore); - }); + const store = storeCreator(); + deepFreeze(store.getState()); + + const NICPostRequest = VSPComponentsNicPostFactory.build(); + + const expectedNIC = VSPComponentsNicFactory.build({...NICPostRequest, id: nicId}); + + mockRest.addHandler('post', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/components/${componentId}/nics`); + expect(data).toEqual(NICPostRequest); + expect(options).toEqual(undefined); + return { + nicId + }; + }); + + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/components/${componentId}/nics`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: [expectedNIC]}; + }); + + mockRest.addHandler('destroy', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/components/${componentId}/nics/${nicId}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {}; }); + + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/components/${componentId}/nics`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: []}; + }); + + const network = VSPComponentsNetworkFactory.build({ + nicList: [expectedNIC] + }); + + const networkAfterDelete = VSPComponentsNetworkFactory.build(); + + let expectedStore = cloneAndSet(store.getState(), 'softwareProduct.softwareProductComponents.network', network); + + return SoftwareProductComponentsNetworkActionHelper.createNIC(store.dispatch, {nic: NICPostRequest, softwareProductId, componentId, version}).then(() => { + expect(store.getState()).toEqual(expectedStore); + return SoftwareProductComponentsNetworkActionHelper.deleteNIC(store.dispatch, {softwareProductId, componentId, nicId, version}); + }).then(() => { + let expectedStore = cloneAndSet(store.getState(), 'softwareProduct.softwareProductComponents.network', networkAfterDelete); + expect(store.getState()).toEqual(expectedStore); + }); + }); + it('open NICE editor', () => { const store = storeCreator(); @@ -172,7 +179,6 @@ describe('Software Product Components Network Action Helper Tests', function () }); }); - it('load NIC Questionnaire', () => { mockRest.resetQueue(); const store = storeCreator(); diff --git a/openecomp-ui/test/softwareProduct/components/processes/SoftwareProductComponentsProcessesView.test.js b/openecomp-ui/test/softwareProduct/components/processes/SoftwareProductComponentsProcessesView.test.js index ac866727a6..921d1bbc90 100644 --- a/openecomp-ui/test/softwareProduct/components/processes/SoftwareProductComponentsProcessesView.test.js +++ b/openecomp-ui/test/softwareProduct/components/processes/SoftwareProductComponentsProcessesView.test.js @@ -66,8 +66,8 @@ describe('SoftwareProductComponetsProcesses Mapper and View Classes', () => { softwareProductId={currentSoftwareProduct.id} componentId={currentSoftwareProductComponent.id} onAddProcess={() => {}} - onEditProcessClick={() => {}} - onDeleteProcessClick={() => {}} + onEditProcess={() => {}} + onDeleteProcess={() => {}} isDisplayEditor={false} isReadOnlyMode={false}/> ); diff --git a/openecomp-ui/test/softwareProduct/components/storage/test.js b/openecomp-ui/test/softwareProduct/components/storage/test.js index 138c4da7d6..1cc0c7b636 100644 --- a/openecomp-ui/test/softwareProduct/components/storage/test.js +++ b/openecomp-ui/test/softwareProduct/components/storage/test.js @@ -22,11 +22,11 @@ import Configuration from 'sdc-app/config/Configuration.js'; import SoftwareProductComponentsActionHelper from 'sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js'; import {default as VSPComponentsStorageFactory, VSPComponentsStorageDataMapFactory} from 'test-utils/factories/softwareProduct/SoftwareProductComponentsStorageFactory.js'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; const softwareProductId = '123'; const vspComponentId = '111'; -const version = VersionControllerUtilsFactory.build().version; +const version = VersionFactory.build(); describe('Software Product Components Storage Module Tests', function () { diff --git a/openecomp-ui/test/softwareProduct/components/test.js b/openecomp-ui/test/softwareProduct/components/test.js index b3994b1461..ab379937c0 100644 --- a/openecomp-ui/test/softwareProduct/components/test.js +++ b/openecomp-ui/test/softwareProduct/components/test.js @@ -20,11 +20,11 @@ import {storeCreator} from 'sdc-app/AppStore.js'; import SoftwareProductComponentsActionHelper from 'sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js'; import {VSPComponentsFactory, VSPComponentsGeneralFactory} from 'test-utils/factories/softwareProduct/SoftwareProductComponentsFactories.js'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; const softwareProductId = '123'; const vspComponentId = '321'; -const version = VersionControllerUtilsFactory.build().version; +const version = VersionFactory.build(); describe('Software Product Components Module Tests', function () { it('Get Software Products Components List', () => { diff --git a/openecomp-ui/test/softwareProduct/creation/SoftwareProductCreation.test.js b/openecomp-ui/test/softwareProduct/creation/SoftwareProductCreation.test.js index c7c55bdbaf..0b46721da0 100644 --- a/openecomp-ui/test/softwareProduct/creation/SoftwareProductCreation.test.js +++ b/openecomp-ui/test/softwareProduct/creation/SoftwareProductCreation.test.js @@ -35,6 +35,9 @@ describe('Software Product Creation Module Tests', function() { softwareProductCreation: { data: {} } + }, + users: { + usersList: [] } }; let props = mapStateToProps(state); @@ -54,6 +57,9 @@ describe('Software Product Creation Module Tests', function() { softwareProductCreation: { data: {} } + }, + users: { + usersList: [] } }; let props = mapStateToProps(state); @@ -71,7 +77,10 @@ describe('Software Product Creation Module Tests', function() { softwareProductCreation: SoftwareProductCreationFactory.build(), softwareProductCategories: CategoryWithSubFactory.buildList({}, {quantity: 2}) }, - finalizedLicenseModelList: FinalizedLicenseModelFactory.buildList(3) + finalizedLicenseModelList: FinalizedLicenseModelFactory.buildList(3), + users: { + usersList: [] + } }; let props = Object.assign({}, mapStateToProps(state), mapActionsToProps(dispatch)); var renderer = TestUtils.createRenderer(); @@ -92,7 +101,10 @@ describe('Software Product Creation Module Tests', function() { softwareProductCreation: SoftwareProductCreationFactoryWithSelectedVendor.build({selectedVendorId: finalizedLicenseModelList[0].id}), softwareProductCategories: CategoryWithSubFactory.buildList({}, {quantity: 2}) }, - finalizedLicenseModelList + finalizedLicenseModelList, + users: { + usersList: [] + } }; let props = Object.assign({}, mapStateToProps(state), mapActionsToProps(dispatch)); let renderer = TestUtils.createRenderer(); diff --git a/openecomp-ui/test/softwareProduct/dependencies/SoftwareProductDependencies.test.js b/openecomp-ui/test/softwareProduct/dependencies/SoftwareProductDependencies.test.js index 5325a58959..595a93fe60 100644 --- a/openecomp-ui/test/softwareProduct/dependencies/SoftwareProductDependencies.test.js +++ b/openecomp-ui/test/softwareProduct/dependencies/SoftwareProductDependencies.test.js @@ -21,34 +21,45 @@ import { SoftwareProductDependenciesResponseFactory, SoftwareProductDependenciesStoreFactory} from 'test-utils/factories/softwareProduct/SoftwareProductDependenciesFactories.js'; import {VSPComponentsFactory} from 'test-utils/factories/softwareProduct/SoftwareProductComponentsFactories.js'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; import {storeCreator} from 'sdc-app/AppStore.js'; import {cloneAndSet} from 'test-utils/Util.js'; import mockRest from 'test-utils/MockRest.js'; import SoftwareProductComponentsActionHelper from 'sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js'; +import {relationTypes, NEW_RULE_TEMP_ID} from 'sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesConstants.js'; import SoftwareProductDependenciesActionHelper from 'sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesActionHelper.js'; import SoftwareProductDependenciesView from 'sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependenciesView.jsx'; import {VSPEditorFactory} from 'test-utils/factories/softwareProduct/SoftwareProductEditorFactories.js'; +function addNewRowElement(arr, data) { + if (data === undefined) { + arr.push({id: NEW_RULE_TEMP_ID, targetId: null, sourceId: null, relationType: relationTypes.DEPENDS_ON}); + } else { + arr.push(data); + } +} + describe('Software Product Dependencies Module Tests', function () { const softwareProductId = '555'; - const version = VersionControllerUtilsFactory.build().version; + const version = VersionFactory.build(); + it('mapStateToProps mapper exists', () => { expect(mapStateToProps).toBeTruthy(); }); - + it('Get Software Product Dependencies List', () => { const store = storeCreator(); const dispatch = store.dispatch; let DependenciesListResponse = SoftwareProductDependenciesResponseFactory.buildList(2); let DependenciesListStore = DependenciesListResponse.map(dependency => SoftwareProductDependenciesStoreFactory.build(dependency)); + addNewRowElement(DependenciesListStore); const expectedStore = cloneAndSet(store.getState(), 'softwareProduct.softwareProductDependencies', DependenciesListStore); mockRest.addHandler('fetch', ({data, options, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependency-model`); + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependencies`); expect(data).toEqual(undefined); expect(options).toEqual(undefined); return {results: DependenciesListResponse}; @@ -59,92 +70,201 @@ describe('Software Product Dependencies Module Tests', function () { const depndenciesWithGeneratedId = state.softwareProduct.softwareProductDependencies; const currentDependencies = expectedStore.softwareProduct.softwareProductDependencies; let expectedStoreDependencies = currentDependencies.map((dependency, index) => ({...dependency, id: depndenciesWithGeneratedId[index].id})); - const newExpectedStore = cloneAndSet(expectedStore, 'softwareProduct.softwareProductDependencies', expectedStoreDependencies); - expect(state).toEqual(newExpectedStore); }); }); - it('Update Software Product Dependencies List', () => { + /* + Test update: + - fetch initial item + - update existing item + - auto fetch again + */ + it('Update Software Product Dependency', () => { const store = storeCreator(); const dispatch = store.dispatch; - let DependenciesListResponse = SoftwareProductDependenciesResponseFactory.buildList(3); + let DependenciesListResponse = SoftwareProductDependenciesResponseFactory.buildList(1); let DependenciesListStore = DependenciesListResponse.map(dependency => SoftwareProductDependenciesStoreFactory.build(dependency)); + addNewRowElement(DependenciesListStore); const expectedStore = cloneAndSet(store.getState(), 'softwareProduct.softwareProductDependencies', DependenciesListStore); mockRest.addHandler('fetch', ({data, options, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependency-model`); + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependencies`); expect(data).toEqual(undefined); expect(options).toEqual(undefined); return {results: DependenciesListResponse}; }); - return SoftwareProductDependenciesActionHelper.fetchDependencies(dispatch, {softwareProductId, version}).then(() => { - + const state = store.getState(); const depndenciesWithGeneratedId = state.softwareProduct.softwareProductDependencies; const currentDependencies = expectedStore.softwareProduct.softwareProductDependencies; let expectedStoreDependencies = currentDependencies.map((dependency, index) => ({...dependency, id: depndenciesWithGeneratedId[index].id})); - - let newDependency = SoftwareProductDependenciesStoreFactory.build(); - expectedStoreDependencies.push(newDependency); - + let item = expectedStoreDependencies.find((dep) => dep.id !== NEW_RULE_TEMP_ID); + item.targetId = 'testChangeTarget'; + item.sourceId = 'testChangesource'; + // removing 'new row' from response + expectedStoreDependencies = expectedStoreDependencies.slice(0, expectedStoreDependencies.length - 1); + let expDependenciesListStore = expectedStoreDependencies.map(dependency => SoftwareProductDependenciesStoreFactory.build(dependency)); + + mockRest.addHandler('put', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependencies/${item.id}`); + expect(data.targetId).toEqual('testChangeTarget'); + expect(data.sourceId).toEqual('testChangesource'); + expect(options).toEqual(undefined); + return {results: null}; + }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependencies`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: expDependenciesListStore}; + }); + + addNewRowElement(expectedStoreDependencies); const newExpectedStore = cloneAndSet(expectedStore, 'softwareProduct.softwareProductDependencies', expectedStoreDependencies); + return SoftwareProductDependenciesActionHelper.updateDependency(dispatch, {softwareProductId, version, item}).then(() => { + const newState = store.getState(); + expect(newState).toEqual(newExpectedStore); - SoftwareProductDependenciesActionHelper.updateDependencyList(dispatch, {dependenciesList: expectedStoreDependencies}); - const newState = store.getState(); - expect(newState).toEqual(newExpectedStore); + }); }); }); - it('Add And Save Software Product Dependencies List', () => { + /* + - Fetch item list + - Delete item from list + - Fetch again + */ + it('Delete Software Product Dependency', () => { const store = storeCreator(); const dispatch = store.dispatch; + let DependenciesListResponse = SoftwareProductDependenciesResponseFactory.buildList(1); + let DependenciesListStore = DependenciesListResponse.map(dependency => SoftwareProductDependenciesStoreFactory.build(dependency)); + addNewRowElement(DependenciesListStore); + const expectedStore = cloneAndSet(store.getState(), 'softwareProduct.softwareProductDependencies', DependenciesListStore); - let mockServerDependencies = []; + let deleteItem = DependenciesListStore.find((dep) => dep.id !== NEW_RULE_TEMP_ID); - SoftwareProductDependenciesActionHelper.addDependency(dispatch); - let state = store.getState(); - let dependencies = state.softwareProduct.softwareProductDependencies; - expect(dependencies.length).toEqual(1); - expect(dependencies[0].sourceId).toEqual(null); - expect(dependencies[0].targetId).toEqual(null); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependencies`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: DependenciesListResponse}; + }); + mockRest.addHandler('destroy', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependencies/${deleteItem.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: null}; + }); + return SoftwareProductDependenciesActionHelper.fetchDependencies(dispatch, {softwareProductId, version}).then(() => { + const state = store.getState(); + const depndenciesWithGeneratedId = state.softwareProduct.softwareProductDependencies; + const currentDependencies = expectedStore.softwareProduct.softwareProductDependencies; + let expectedStoreDependencies = currentDependencies.map((dependency, index) => ({...dependency, id: depndenciesWithGeneratedId[index].id})) - let newDependencies = SoftwareProductDependenciesStoreFactory.buildList(1); - const expectedStore = cloneAndSet(store.getState(), 'softwareProduct.softwareProductDependencies', newDependencies); - SoftwareProductDependenciesActionHelper.updateDependencyList(dispatch, {dependenciesList: newDependencies}); + const newExpectedStore = cloneAndSet(expectedStore, 'softwareProduct.softwareProductDependencies', expectedStoreDependencies); + expect(state).toEqual(newExpectedStore); - mockRest.addHandler('post', ({data, options, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependency-model`); - expect(data).toEqual({componentDependencyModels: newDependencies.map(item => ({sourceId: item.sourceId, targetId: item.targetId, relationType: item.relationType}) )}); - expect(options).toEqual(undefined); - mockServerDependencies = [...data.componentDependencyModels]; - return {returnCode: 'OK'}; + expectedStoreDependencies = expectedStoreDependencies.filter((dep) => dep.id !== deleteItem.id); + const postDeleteExpectedStore = cloneAndSet(expectedStore, 'softwareProduct.softwareProductDependencies', expectedStoreDependencies); + + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependencies`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: []}; + }); + + return SoftwareProductDependenciesActionHelper.removeDependency(dispatch, {softwareProductId, version, item: deleteItem}).then(() => { + const state = store.getState(); + const depndenciesWithGeneratedId = state.softwareProduct.softwareProductDependencies; + const currentDependencies = postDeleteExpectedStore.softwareProduct.softwareProductDependencies; + expect(depndenciesWithGeneratedId).toEqual(currentDependencies); + }); }); + }); + + /* + - Create initial list + - Update the new row and make sure there is no API call + - Submit the new row + - Getch data with reset new row and new entity with info from the new item + */ + + it('Create Software Product Dependency', () => { + const store = storeCreator(); + const dispatch = store.dispatch; + + let DependenciesListResponse = SoftwareProductDependenciesResponseFactory.buildList(1); + let DependenciesListStore = DependenciesListResponse.map(dependency => SoftwareProductDependenciesStoreFactory.build(dependency)); + addNewRowElement(DependenciesListStore); + const expectedStore = cloneAndSet(store.getState(), 'softwareProduct.softwareProductDependencies', DependenciesListStore); mockRest.addHandler('fetch', ({data, options, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependency-model`); + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependencies`); expect(data).toEqual(undefined); expect(options).toEqual(undefined); - return {results: mockServerDependencies}; + return {results: DependenciesListResponse}; }); + return SoftwareProductDependenciesActionHelper.fetchDependencies(dispatch, {softwareProductId, version}).then(() => { + // setting properties on the 'new role' should not call an API + let addItem = {id: NEW_RULE_TEMP_ID, sourceId: 'sId', targetId : 'tId',relationType: relationTypes.DEPENDS_ON}; + try { + SoftwareProductDependenciesActionHelper.updateDependency(dispatch, {softwareProductId, version, item: addItem}).then(()=> { + //go to error that fetch was not defined + }); + } catch (error) { + if(error.name === 'TypeError') { + // Expected error because we expected there is no promise + } else { + fail('Error:' + error); + } + } - return SoftwareProductDependenciesActionHelper.saveDependencies(dispatch, {softwareProductId, version, dependenciesList: newDependencies}).then(() => { - return SoftwareProductDependenciesActionHelper.fetchDependencies(dispatch, {softwareProductId, version}); - }).then(() => { const state = store.getState(); const depndenciesWithGeneratedId = state.softwareProduct.softwareProductDependencies; const currentDependencies = expectedStore.softwareProduct.softwareProductDependencies; let expectedStoreDependencies = currentDependencies.map((dependency, index) => ({...dependency, id: depndenciesWithGeneratedId[index].id})); + // creating the new item + let item = SoftwareProductDependenciesResponseFactory.buildList(1, + {sourceId: 'sId', targetId : 'tId',relationType: relationTypes.DEPENDS_ON})[0]; + addNewRowElement(expectedStoreDependencies, item); + expectedStoreDependencies = expectedStoreDependencies.filter((dep) => dep.id !== NEW_RULE_TEMP_ID); + + mockRest.addHandler('post', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependencies`); + expect(data.targetId).toEqual('tId'); + expect(data.sourceId).toEqual('sId'); + expect(data.id).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: item.id}; + }); + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependencies`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: expectedStoreDependencies}; + }); + + let PostCreateItemListStore = expectedStoreDependencies.map(dependency => SoftwareProductDependenciesStoreFactory.build(dependency)); + addNewRowElement(PostCreateItemListStore); + const newExpectedStore = cloneAndSet(store.getState(), 'softwareProduct.softwareProductDependencies', PostCreateItemListStore); + + return SoftwareProductDependenciesActionHelper.createDependency(dispatch, {softwareProductId, version, item: addItem}).then(() => { + const newState = store.getState(); + expect(newState.softwareProduct.softwareProductDependencies.length).toEqual(3); + expect(newState).toEqual(newExpectedStore); + }); - const newExpectedStore = cloneAndSet(expectedStore, 'softwareProduct.softwareProductDependencies', expectedStoreDependencies); - - expect(state).toEqual(newExpectedStore); }); + }); + it('Get Software Product Dependencies List with loop, and render to JSX', () => { const store = storeCreator(); const dispatch = store.dispatch; @@ -161,10 +281,11 @@ describe('Software Product Dependencies Module Tests', function () { secondDependency.targetId = firstDependecy.sourceId; let DependenciesListStore = DependenciesListResponse.map(dependency => SoftwareProductDependenciesStoreFactory.build({...dependency, hasCycle: true})); + addNewRowElement(DependenciesListStore); const expectedStore = cloneAndSet(store.getState(), 'softwareProduct.softwareProductDependencies', DependenciesListStore); mockRest.addHandler('fetch', ({data, options, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependency-model`); + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProductId}/versions/${version.id}/component-dependencies`); expect(data).toEqual(undefined); expect(options).toEqual(undefined); return {results: DependenciesListResponse}; @@ -187,9 +308,9 @@ describe('Software Product Dependencies Module Tests', function () { let expectedStoreDependencies = currentDependencies.map((dependency, index) => ({...dependency, id: depndenciesWithGeneratedId[index].id})); const newExpectedStore = { - ...expectedStore, + ...expectedStore, softwareProduct: { - ...expectedStore.softwareProduct, + ...expectedStore.softwareProduct, softwareProductDependencies: expectedStoreDependencies, softwareProductEditor: {data: vspEditor}, softwareProductComponents: { @@ -207,4 +328,5 @@ describe('Software Product Dependencies Module Tests', function () { expect(wrapper).toBeTruthy(); }); }); -}); \ No newline at end of file + +}); diff --git a/openecomp-ui/test/softwareProduct/deployment/SoftwareProductDeploymentEditor.test.js b/openecomp-ui/test/softwareProduct/deployment/SoftwareProductDeploymentEditor.test.js index 4277f28ee8..c355d9d273 100644 --- a/openecomp-ui/test/softwareProduct/deployment/SoftwareProductDeploymentEditor.test.js +++ b/openecomp-ui/test/softwareProduct/deployment/SoftwareProductDeploymentEditor.test.js @@ -20,6 +20,7 @@ import SoftwareProductDeploymentEditorView from 'sdc-app/onboarding/softwareProd import { VSPComponentsFactory } from 'test-utils/factories/softwareProduct/SoftwareProductComponentsFactories.js'; import { VSPEditorFactoryWithLicensingData } from 'test-utils/factories/softwareProduct/SoftwareProductEditorFactories.js'; import { FeatureGroupStoreFactory } from 'test-utils/factories/licenseModel/FeatureGroupFactories.js'; +import CurrentScreenFactory from 'test-utils/factories/common/CurrentScreenFactory.js'; describe('Software Product Deployment Editor Module Tests', function () { @@ -32,8 +33,10 @@ describe('Software Product Deployment Editor Module Tests', function () { const currentSoftwareProduct = VSPEditorFactoryWithLicensingData.build(); const componentsList = VSPComponentsFactory.buildList(1); const featureGroupsList = FeatureGroupStoreFactory.buildList(2); + const currentScreen = CurrentScreenFactory.build(); var state = { + currentScreen, softwareProduct: { softwareProductEditor: { data: currentSoftwareProduct diff --git a/openecomp-ui/test/softwareProduct/details/detailsView.test.js b/openecomp-ui/test/softwareProduct/details/detailsView.test.js index 37c5df5079..d83fedaf7d 100644 --- a/openecomp-ui/test/softwareProduct/details/detailsView.test.js +++ b/openecomp-ui/test/softwareProduct/details/detailsView.test.js @@ -24,10 +24,12 @@ import {FeatureGroupStoreFactory} from 'test-utils/factories/licenseModel/Featu import {SchemaGenericFieldInfoFactory} from 'test-utils/factories/softwareProduct/SoftwareProductQSchemaFactory.js'; import {default as VspQdataFactory, VspDataMapFactory} from 'test-utils/factories/softwareProduct/VspQdataFactory.js'; import {FinalizedLicenseModelFactory} from 'test-utils/factories/licenseModel/LicenseModelFactories.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; +import CurrentScreenFactory from 'test-utils/factories/common/CurrentScreenFactory.js'; describe('Software Product Details: ', function () { - let currentSoftwareProduct = {}, currentSoftwareProductWithLicensingData = {}, softwareProductCategories = [], + let currentSoftwareProduct = {}, currentSoftwareProductWithLicensingData = {}, softwareProductCategories = [], licensingVersionsList = [], currentScreen = {}, finalizedLicenseModelList, licenseAgreementList, featureGroupsList, qdata = {}, dataMap = {}, genericFieldInfo = {}, qGenericFieldInfo = {}; let dummyFunc = () => {}; @@ -35,11 +37,18 @@ describe('Software Product Details: ', function () { finalizedLicenseModelList = FinalizedLicenseModelFactory.buildList(2); currentSoftwareProduct = VSPEditorFactory.build({ id: 'RTRTG454545', + licensingVersion: undefined, vendorId: finalizedLicenseModelList[0].id, - vendorName: finalizedLicenseModelList[0].vendorName + vendorName: finalizedLicenseModelList[0].name }); softwareProductCategories = CategoryWithSubFactory.buildList(2, {}, {quantity: 1}); licenseAgreementList = LicenseAgreementStoreFactory.buildList(2); + licensingVersionsList = [ + { + "id":"0127b419e9574a11aab8e031a78fc534", + "name":"1.0","description":"Initial version", + "baseId":"","status":"Certified","creationTime":1506409288390,"modificationTime":1506409288390,"additionalInfo":{"OptionalCreationMethods":["minor"]}},{"id":"ea159ffedd9a4f9a8a56d53ba66b7314","name":"2.0","description":"ggggg","baseId":"0127b419e9574a11aab8e031a78fc534","status":"Draft","creationTime":1508839019802,"modificationTime":1508839019802,"additionalInfo":{"OptionalCreationMethods":[]}} + ]; featureGroupsList = FeatureGroupStoreFactory.buildList(2, {referencingLicenseAgreements: [licenseAgreementList[0].id]}); qdata = VspQdataFactory.build(); dataMap = VspDataMapFactory.build(); @@ -48,7 +57,8 @@ describe('Software Product Details: ', function () { licensingData: { licenseAgreement: licenseAgreementList[0].id, featureGroups: [featureGroupsList[0].id] - } + }, + licensingVersion : licensingVersionsList[0].id }; genericFieldInfo = { 'name': { @@ -66,6 +76,7 @@ describe('Software Product Details: ', function () { } }; qGenericFieldInfo = SchemaGenericFieldInfoFactory.build(); + currentScreen = CurrentScreenFactory.build(); }); it('should mapper exist', () => { @@ -75,10 +86,12 @@ describe('Software Product Details: ', function () { it('should mapper return vsp basic data', () => { var obj = { + currentScreen, softwareProduct: { softwareProductEditor: { data: currentSoftwareProduct, - genericFieldInfo + genericFieldInfo, + licensingVersionsList }, softwareProductCategories, softwareProductQuestionnaire: { @@ -104,7 +117,7 @@ describe('Software Product Details: ', function () { expect(result.finalizedLicenseModelList.length).toBeGreaterThan(0); expect(finalizedLicenseModelList[0]).toMatchObject({ id: result.currentSoftwareProduct.vendorId, - vendorName: result.currentSoftwareProduct.vendorName + name: result.currentSoftwareProduct.vendorName }); expect(result.softwareProductCategories).toEqual(softwareProductCategories); expect(result.licenseAgreementList).toEqual([]); @@ -112,16 +125,17 @@ describe('Software Product Details: ', function () { expect(result.qdata).toEqual(qdata); expect(result.dataMap).toEqual(dataMap); expect(result.isFormValid).toEqual(true); - expect(result.isReadOnlyMode).toEqual(true); }); it('should mapper return vsp data with selected licenseAgreement and featureGroup', () => { var obj = { + currentScreen, softwareProduct: { softwareProductEditor: { data: currentSoftwareProductWithLicensingData, - genericFieldInfo + genericFieldInfo, + licensingVersionsList }, softwareProductCategories, softwareProductQuestionnaire: { @@ -147,7 +161,7 @@ describe('Software Product Details: ', function () { expect(result.finalizedLicenseModelList.length).toBeGreaterThan(0); expect(result.finalizedLicenseModelList[0]).toMatchObject({ id: result.currentSoftwareProduct.vendorId, - vendorName: result.currentSoftwareProduct.vendorName + name: result.currentSoftwareProduct.vendorName }); expect(result.softwareProductCategories).toEqual(softwareProductCategories); expect(result.licenseAgreementList).toEqual(licenseAgreementList); @@ -156,12 +170,12 @@ describe('Software Product Details: ', function () { expect(featureGroupsList[0]).toMatchObject({...featureGroupsList[0], id: fg}); }); expect(result.qdata).toEqual(qdata); - expect(result.isReadOnlyMode).toEqual(true); }); it('VSP Details view test', () => { let params = { + ...currentScreen.props, currentSoftwareProduct, softwareProductCategories, qdata, @@ -170,6 +184,7 @@ describe('Software Product Details: ', function () { finalizedLicenseModelList, licenseAgreementList, featureGroupsList, + licensingVersionsList, genericFieldInfo, qGenericFieldInfo, }; @@ -185,6 +200,8 @@ describe('Software Product Details: ', function () { ); let renderedOutput = renderer.getRenderOutput(); expect(renderedOutput).toBeTruthy(); + expect(renderedOutput.props.children.props.isReadOnlyMode).toBe(false); + }); it('in view: should change vendorId and update vsp licensing-version', done => { @@ -199,11 +216,12 @@ describe('Software Product Details: ', function () { qGenericFieldInfo, finalizedLicenseModelList, licenseAgreementList, + licensingVersionsList, featureGroupsList }; const onVendorChangedListener = (deltaData) => { expect(deltaData.vendorId).toEqual(finalizedLicenseModelList[1].id); - expect(deltaData.vendorName).toEqual(finalizedLicenseModelList[1].vendorName); + expect(deltaData.vendorName).toEqual(finalizedLicenseModelList[1].name); expect(deltaData.licensingVersion).toEqual(''); expect(deltaData.licensingData).toEqual({}); done(); @@ -215,6 +233,7 @@ describe('Software Product Details: ', function () { qdata = {params.qdata} qGenericFieldInfo = {params.qGenericFieldInfo} genericFieldInfo = {params.genericFieldInfo} + licensingVersionsList={params.licensingVersionsList} isFormValid={params.isFormValid} dataMap={params.dataMap} finalizedLicenseModelList = {params.finalizedLicenseModelList} @@ -235,6 +254,7 @@ describe('Software Product Details: ', function () { softwareProductCategories, qdata, dataMap, + licensingVersionsList, isFormValid: true, genericFieldInfo, qGenericFieldInfo, @@ -244,8 +264,8 @@ describe('Software Product Details: ', function () { }; const onVendorChangedListener = (deltaData) => { expect(deltaData.vendorId).toEqual(finalizedLicenseModelList[1].id); - expect(deltaData.vendorName).toEqual(finalizedLicenseModelList[1].vendorName); - expect(deltaData.licensingVersion).toEqual(finalizedLicenseModelList[1].viewableVersion[0]); + expect(deltaData.vendorName).toEqual(finalizedLicenseModelList[1].name); + expect(deltaData.licensingVersion).toEqual(licensingVersionsList[1]); expect(deltaData.licensingData).toEqual({}); done(); }; @@ -258,7 +278,7 @@ describe('Software Product Details: ', function () { onQDataChanged = {dummyFunc} onVendorParamChanged = {(deltaData) => onVendorChangedListener(deltaData)}/>); expect(vspDetailsView).toBeTruthy(); - vspDetailsView.onVendorParamChanged({vendorId: finalizedLicenseModelList[1].id, licensingVersion: finalizedLicenseModelList[1].viewableVersion[0]}); + vspDetailsView.onVendorParamChanged({vendorId: finalizedLicenseModelList[1].id, licensingVersion: licensingVersionsList[1]}); }); it('in view: should change subcategory', done => { @@ -270,6 +290,7 @@ describe('Software Product Details: ', function () { isFormValid: true, genericFieldInfo, qGenericFieldInfo, + licensingVersionsList, finalizedLicenseModelList, licenseAgreementList, featureGroupsList @@ -301,6 +322,7 @@ describe('Software Product Details: ', function () { isFormValid: true, genericFieldInfo, qGenericFieldInfo, + licensingVersionsList, finalizedLicenseModelList, licenseAgreementList, featureGroupsList @@ -328,8 +350,8 @@ describe('Software Product Details: ', function () { ]}); }); - it('in view: should change license agreement', done => { + it('in view: should change license agreement', done => { let params = { currentSoftwareProduct: currentSoftwareProductWithLicensingData, softwareProductCategories, @@ -338,6 +360,7 @@ describe('Software Product Details: ', function () { isFormValid: true, genericFieldInfo, qGenericFieldInfo, + licensingVersionsList, finalizedLicenseModelList, licenseAgreementList, featureGroupsList @@ -358,4 +381,5 @@ describe('Software Product Details: ', function () { expect(vspDetailsView).toBeTruthy(); vspDetailsView.onLicensingDataChanged({licenseAgreement: licenseAgreementList[1].id, featureGroups: []}); }); + }); diff --git a/openecomp-ui/test/softwareProduct/details/test.js b/openecomp-ui/test/softwareProduct/details/test.js index df84d184ce..27cbaa40ef 100644 --- a/openecomp-ui/test/softwareProduct/details/test.js +++ b/openecomp-ui/test/softwareProduct/details/test.js @@ -30,10 +30,11 @@ import {heatSetupManifest} from 'test-utils/factories/softwareProduct/SoftwarePr import { FeatureGroupStoreFactory as FeatureGroup} from 'test-utils/factories/licenseModel/FeatureGroupFactories.js'; import {LicenseAgreementStoreFactory as LicenseAgreement} from 'test-utils/factories/licenseModel/LicenseAgreementFactories.js'; -import VersionControllerUtilsFactory from 'test-utils/factories/softwareProduct/VersionControllerUtilsFactory.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; +import {InitializedCurrentScreenFactory} from 'test-utils/factories/common/CurrentScreenFactory.js'; -describe('Software Product Module Tests', function () { +describe('Software Product Details Module Tests', function () { it('Get Software Products List', () => { const store = storeCreator(); deepFreeze(store.getState()); @@ -43,14 +44,14 @@ describe('Software Product Module Tests', function () { const expectedStore = cloneAndSet(store.getState(), 'softwareProductList', softwareProductList); mockRest.addHandler('fetch', ({options, data, baseUrl}) => { - expect(baseUrl).toEqual('/onboarding-api/v1.0/vendor-software-products/'); + expect(baseUrl).toEqual('/onboarding-api/v1.0/vendor-software-products/?versionFilter=Draft'); expect(data).toEqual(undefined); expect(options).toEqual(undefined); return {results: softwareProductList}; }); mockRest.addHandler('fetch', ({options, data, baseUrl}) => { - expect(baseUrl).toEqual('/onboarding-api/v1.0/vendor-software-products/?versionFilter=Final'); + expect(baseUrl).toEqual('/onboarding-api/v1.0/vendor-software-products/?versionFilter=Certified'); expect(data).toEqual(undefined); expect(options).toEqual(undefined); return {results: []}; @@ -130,6 +131,10 @@ describe('Software Product Module Tests', function () { let manifest = heatSetupManifest.build(); expectedStore = cloneAndSet(expectedStore, 'softwareProduct.softwareProductAttachments.heatSetup', manifest); + const expectedCurrentScreen = InitializedCurrentScreenFactory.build(); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreen.itemPermission); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.props', expectedCurrentScreen.props); + mockRest.addHandler('post', ({options, data, baseUrl}) => { expect(baseUrl).toEqual('/onboarding-api/v1.0/vendor-software-products/'); expect(data).toEqual(softwareProductPostRequest); @@ -184,7 +189,7 @@ describe('Software Product Module Tests', function () { deepFreeze(softwareProductPostRequest); const licenseModelId = softwareProductPostRequest.vendorId; - const LMVersion = VersionControllerUtilsFactory.build().version; + const LMVersion = VersionFactory.build(); const secondLicenseModelId = 'secondLicenseModelId'; let FG1 = FeatureGroup.build(); @@ -205,12 +210,19 @@ describe('Software Product Module Tests', function () { }); mockRest.addHandler('fetch', ({options, data, baseUrl}) => { - expect(baseUrl).toEqual('/onboarding-api/v1.0/vendor-license-models/?versionFilter=Final'); + expect(baseUrl).toEqual('/onboarding-api/v1.0/vendor-license-models/?versionFilter=Certified'); expect(data).toEqual(undefined); expect(options).toEqual(undefined); return {results: []}; }); + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${licenseModelId}/versions/${LMVersion.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: {}}; + }); + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${licenseModelId}/versions/${LMVersion.id}/license-agreements`); expect(data).toEqual(undefined); @@ -225,6 +237,13 @@ describe('Software Product Module Tests', function () { return {results: [FG1]}; }); + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${secondLicenseModelId}/versions/${LMVersion.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: {}}; + }); + mockRest.addHandler('fetch', ({options, data, baseUrl}) => { expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-license-models/${secondLicenseModelId}/versions/${LMVersion.id}/license-agreements`); expect(data).toEqual(undefined); @@ -239,17 +258,18 @@ describe('Software Product Module Tests', function () { return {results: [FG2]}; }); - return SoftwareProductActionHelper.loadSoftwareProductDetailsData(store.dispatch, {licenseModelId, licensingVersion: LMVersion}).then(() => { + return SoftwareProductActionHelper.loadSoftwareProductDetailsData(store.dispatch, {licenseModelId, licensingVersion: LMVersion.id}).then(() => { let state = store.getState(); expect(state.licenseModel.licenseAgreement.licenseAgreementList).toEqual([LA1]); expect(state.licenseModel.featureGroup.featureGroupsList).toEqual([FG1]); return SoftwareProductActionHelper.softwareProductEditorVendorChanged(store.dispatch, - {deltaData: {vendorId: secondLicenseModelId, licensingVersion: LMVersion}, - formName: forms.VENDOR_SOFTWARE_PRODUCT_DETAILS}); - }).then(() => { - let state = store.getState(); - expect(state.licenseModel.licenseAgreement.licenseAgreementList).toEqual([LA2]); - expect(state.licenseModel.featureGroup.featureGroupsList).toEqual([FG2]); + {deltaData: {vendorId: secondLicenseModelId, licensingVersion: LMVersion.id}, + formName: forms.VENDOR_SOFTWARE_PRODUCT_DETAILS} + ).then(() => { + let state = store.getState(); + expect(state.licenseModel.licenseAgreement.licenseAgreementList).toEqual([LA2]); + expect(state.licenseModel.featureGroup.featureGroupsList).toEqual([FG2]); + }); }); }); @@ -258,6 +278,8 @@ describe('Software Product Module Tests', function () { const softwareProduct = VSPEditorFactoryWithLicensingData.build(); deepFreeze(softwareProduct); + const version = VersionFactory.build(); + const store = storeCreator({ softwareProduct: { softwareProductEditor: {data: softwareProduct}, @@ -291,13 +313,13 @@ describe('Software Product Module Tests', function () { deepFreeze(questionnaireData); mockRest.addHandler('put', ({data, options, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${toBeUpdatedSoftwareProductId}/versions/${softwareProduct.version.id}`); + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${toBeUpdatedSoftwareProductId}/versions/${version.id}`); expect(data).toEqual(softwareProductUpdateData); expect(options).toEqual(undefined); return {returnCode: 'OK'}; }); mockRest.addHandler('put', ({data, options, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${toBeUpdatedSoftwareProductId}/versions/${softwareProduct.version.id}/questionnaire`); + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${toBeUpdatedSoftwareProductId}/versions/${version.id}/questionnaire`); expect(data).toEqual(questionnaireData); expect(options).toEqual(undefined); return {returnCode: 'OK'}; @@ -305,7 +327,8 @@ describe('Software Product Module Tests', function () { return SoftwareProductActionHelper.updateSoftwareProduct(store.dispatch, { softwareProduct: softwareProductPutRequest, - qdata: questionnaireData + qdata: questionnaireData, + version }).then(() => { expect(store.getState()).toEqual(expectedStore); }); @@ -316,6 +339,8 @@ describe('Software Product Module Tests', function () { const softwareProduct = VSPEditorFactoryWithLicensingData.build(); deepFreeze(softwareProduct); + const version = VersionFactory.build(); + const store = storeCreator({ softwareProduct: { softwareProductEditor: {data: softwareProduct}, @@ -334,19 +359,20 @@ describe('Software Product Module Tests', function () { let softwareProductUpdateData = VSPEditorPostFactoryWithLicensingData.build(dataForUpdate); delete softwareProductUpdateData.version; - const softwareProductPutRequest = buildFromExistingObject(VSPEditorFactoryWithLicensingData, softwareProductUpdateData, {id: toBeUpdatedSoftwareProductId, version: softwareProduct.version}); + const softwareProductPutRequest = buildFromExistingObject(VSPEditorFactoryWithLicensingData, softwareProductUpdateData, {id: toBeUpdatedSoftwareProductId}); deepFreeze(softwareProductUpdateData); mockRest.addHandler('put', ({data, options, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${toBeUpdatedSoftwareProductId}/versions/${softwareProduct.version.id}`); + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${toBeUpdatedSoftwareProductId}/versions/${version.id}`); expect(data).toEqual(softwareProductUpdateData); expect(options).toEqual(undefined); return {returnCode: 'OK'}; }); return SoftwareProductActionHelper.updateSoftwareProductData(store.dispatch, { - softwareProduct: softwareProductPutRequest + softwareProduct: softwareProductPutRequest, + version }).then(() => { expect(store.getState()).toEqual(expectedStore); }); @@ -356,6 +382,8 @@ describe('Software Product Module Tests', function () { const softwareProduct = VSPEditorFactoryWithLicensingData.build(); deepFreeze(softwareProduct); + const version = VersionFactory.build(); + const store = storeCreator({ softwareProduct: { softwareProductEditor: {data: softwareProduct}, @@ -377,7 +405,7 @@ describe('Software Product Module Tests', function () { deepFreeze(questionnaireData); mockRest.addHandler('put', ({data, options, baseUrl}) => { - expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${toBeUpdatedSoftwareProductId}/versions/${softwareProduct.version.id}/questionnaire`); + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${toBeUpdatedSoftwareProductId}/versions/${version.id}/questionnaire`); expect(data).toEqual(questionnaireData); expect(options).toEqual(undefined); return {returnCode: 'OK'}; @@ -385,7 +413,7 @@ describe('Software Product Module Tests', function () { return SoftwareProductActionHelper.updateSoftwareProductQuestionnaire(store.dispatch, { softwareProductId: softwareProduct.id, - version: softwareProduct.version, + version, qdata: questionnaireData }).then(() => { expect(store.getState()).toEqual(expectedStore); diff --git a/openecomp-ui/test/softwareProduct/landingPage/landingPage.test.js b/openecomp-ui/test/softwareProduct/landingPage/landingPage.test.js index 4da0ec98d4..c53919b802 100644 --- a/openecomp-ui/test/softwareProduct/landingPage/landingPage.test.js +++ b/openecomp-ui/test/softwareProduct/landingPage/landingPage.test.js @@ -19,6 +19,9 @@ import React from 'react'; import TestUtils from 'react-addons-test-utils'; +import {Provider} from 'react-redux'; +import {storeCreator} from 'sdc-app/AppStore.js'; + import {VSPEditorFactory} from 'test-utils/factories/softwareProduct/SoftwareProductEditorFactories.js'; import {CategoryWithSubFactory} from 'test-utils/factories/softwareProduct/VSPCategoriesFactory.js'; import {LicenseAgreementStoreFactory} from 'test-utils/factories/licenseModel/LicenseAgreementFactories.js'; @@ -27,9 +30,7 @@ import {default as SoftwareProductQSchemaFactory} from 'test-utils/factories/so import {default as VspQdataFactory} from 'test-utils/factories/softwareProduct/VspQdataFactory.js'; import {VSPComponentsFactory} from 'test-utils/factories/softwareProduct/SoftwareProductComponentsFactories.js'; import {FinalizedLicenseModelFactory} from 'test-utils/factories/licenseModel/LicenseModelFactories.js'; - -import { Provider } from 'react-redux'; -import {storeCreator} from 'sdc-app/AppStore.js'; +import CurrentScreenFactory from 'test-utils/factories/common/CurrentScreenFactory.js'; import {mapStateToProps} from 'sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPage.js'; import SoftwareProductLandingPageView from 'sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPageView.jsx'; @@ -37,28 +38,28 @@ import SoftwareProductLandingPageView from 'sdc-app/onboarding/softwareProduct/l describe('Software Product Landing Page: ', function () { - let currentSoftwareProduct = {}, softwareProductCategories = [], + let currentSoftwareProduct = {}, softwareProductCategories = [], currentScreen = {}, finalizedLicenseModelList, licenseAgreementList, featureGroupsList, qschema, qdata = {}; const dummyFunc = () => {}; + beforeAll(function() { finalizedLicenseModelList = FinalizedLicenseModelFactory.buildList(2); - currentSoftwareProduct = VSPEditorFactory.build({id:'RTRTG454545', vendorId: finalizedLicenseModelList[0].id, vendorName: finalizedLicenseModelList[0].name}); + currentSoftwareProduct = VSPEditorFactory.build({id:'RTRTG454545', vendorId: finalizedLicenseModelList[0].id, vendorName: finalizedLicenseModelList[0].name, onBoardingMethod: 'HEAT'}); softwareProductCategories = CategoryWithSubFactory.buildList(2,{},{quantity: 1}); licenseAgreementList = LicenseAgreementStoreFactory.buildList(2); featureGroupsList = FeatureGroupStoreFactory.buildList(2,{referencingLicenseAgreements:[licenseAgreementList[0].id]}); + currentScreen = CurrentScreenFactory.build(); qdata = VspQdataFactory.build(); qschema = SoftwareProductQSchemaFactory.build(qdata); - }); - - it('should mapper exist', () => { expect(mapStateToProps).toBeTruthy(); }); it('should mapper return vsp basic data', () => { - const obj = { + const state = { + currentScreen, softwareProduct: { softwareProductEditor: { data: currentSoftwareProduct @@ -70,6 +71,9 @@ describe('Software Product Landing Page: ', function () { }, softwareProductComponents: { componentsList:[] + }, + softwareProductAttachments: { + heatSetup: {} } }, finalizedLicenseModelList, @@ -83,23 +87,25 @@ describe('Software Product Landing Page: ', function () { } }; - const result = mapStateToProps(obj); + const result = mapStateToProps(state); expect(result.currentSoftwareProduct).toBeTruthy(); - expect(result.isReadOnlyMode).toEqual(true); }); it('vsp landing basic view', () => { const params = { + ...currentScreen.props, currentSoftwareProduct, - isReadOnlyMode: false, componentsList: VSPComponentsFactory.buildList(2) }; const store = storeCreator(); - let vspLandingView = TestUtils.renderIntoDocument(); + let vspLandingView = TestUtils.renderIntoDocument( + + + + ); expect(vspLandingView).toBeTruthy(); }); @@ -107,13 +113,16 @@ describe('Software Product Landing Page: ', function () { const params = { currentSoftwareProduct, - isReadOnlyMode: false, + ...currentScreen.props, componentsList: VSPComponentsFactory.buildList(2) }; const store = storeCreator(); - let vspLandingView = TestUtils.renderIntoDocument(); + let vspLandingView = TestUtils.renderIntoDocument( + + + + ); let vspLandingViewWrapper = TestUtils.findRenderedComponentWithType( vspLandingView, SoftwareProductLandingPageView @@ -127,8 +136,8 @@ describe('Software Product Landing Page: ', function () { it('vsp landing handleImportSubmit test ', () => { const params = { + ...currentScreen.props, currentSoftwareProduct, - isReadOnlyMode: false, componentsList: VSPComponentsFactory.buildList(2), onUploadConfirmation: dummyFunc, onUpload: dummyFunc, @@ -144,7 +153,12 @@ describe('Software Product Landing Page: ', function () { const store = storeCreator(); - let vspLandingView = TestUtils.renderIntoDocument(); + let vspLandingView = TestUtils.renderIntoDocument( + + + + ); + let vspLandingViewWrapper = TestUtils.findRenderedComponentWithType( vspLandingView, SoftwareProductLandingPageView @@ -166,7 +180,7 @@ describe('Software Product Landing Page: ', function () { const params = { currentSoftwareProduct, - isReadOnlyMode: false, + ...currentScreen.props, componentsList: VSPComponentsFactory.buildList(2), onUploadConfirmation: dummyFunc, onUpload: dummyFunc, @@ -175,8 +189,11 @@ describe('Software Product Landing Page: ', function () { const store = storeCreator(); - let vspLandingView = TestUtils.renderIntoDocument(); + let vspLandingView = TestUtils.renderIntoDocument( + + + + ); let vspLandingViewWrapper = TestUtils.findRenderedComponentWithType( vspLandingView, diff --git a/openecomp-ui/test/softwareProduct/networks/SoftwareProductNetworksView.test.js b/openecomp-ui/test/softwareProduct/networks/SoftwareProductNetworksView.test.js index 6ef6bcf02a..b4ea4049a6 100644 --- a/openecomp-ui/test/softwareProduct/networks/SoftwareProductNetworksView.test.js +++ b/openecomp-ui/test/softwareProduct/networks/SoftwareProductNetworksView.test.js @@ -57,9 +57,8 @@ describe('SoftwareProductNetworks Mapper and View Classes', () => { const networksList = VSPNetworkFactory.buildList(2); const versionControllerData = VSPComponentsVersionControllerFactory.build(); - var renderer = TestUtils.createRenderer(); - renderer.render(); + renderer.render(); var renderedOutput = renderer.getRenderOutput(); expect(renderedOutput).toBeTruthy(); diff --git a/openecomp-ui/test/softwareProduct/processes/test.js b/openecomp-ui/test/softwareProduct/processes/test.js index 43110d2e55..6ad696ae85 100644 --- a/openecomp-ui/test/softwareProduct/processes/test.js +++ b/openecomp-ui/test/softwareProduct/processes/test.js @@ -29,10 +29,10 @@ import { VSPProcessStoreWithArtifactNameFactory } from 'test-utils/factories/softwareProduct/SoftwareProductProcessFactories.js'; import {buildFromExistingObject} from 'test-utils/Util.js'; import {VSPEditorFactory} from 'test-utils/factories/softwareProduct/SoftwareProductEditorFactories.js'; -import ValidationHelper from 'sdc-app/common/helpers/ValidationHelper.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; const softwareProductId = '123'; -const version = VSPEditorFactory.build().version; +const version = VersionFactory.build(); describe('Software Product Processes Module Tests', function () { @@ -317,7 +317,6 @@ describe('Software Product Processes Module Tests', function () { }); const processId = softwareProductProcessesList[0].id; - const version = store.getState().softwareProduct.softwareProductEditor.data.version; const versionId = version.id; deepFreeze(store.getState()); @@ -343,7 +342,7 @@ describe('Software Product Processes Module Tests', function () { }); }); - it('Validating Software Products Processes Delete confirmation', done => { + it('Validating Software Products Processes Delete confirmation', () => { const store = storeCreator(); deepFreeze(store.getState()); @@ -352,15 +351,12 @@ describe('Software Product Processes Module Tests', function () { const expectedStore = cloneAndSet(store.getState(), 'softwareProduct.softwareProductProcesses.processToDelete', process); - SoftwareProductProcessesActionHelper.openDeleteProcessesConfirm(store.dispatch, {process}); + return SoftwareProductProcessesActionHelper.openDeleteProcessesConfirm(store.dispatch, {process}); - setTimeout(function(){ - expect(store.getState()).toEqual(expectedStore); - done(); - }, 100); + expect(store.getState()).toEqual(expectedStore); }); - it('Validating Software Products Processes Cancel Delete', done => { + it('Validating Software Products Processes Cancel Delete', () => { const store = storeCreator(); deepFreeze(store.getState()); @@ -368,10 +364,7 @@ describe('Software Product Processes Module Tests', function () { SoftwareProductProcessesActionHelper.hideDeleteConfirm(store.dispatch); - setTimeout(function(){ - expect(store.getState()).toEqual(expectedStore); - done(); - }, 100); + expect(store.getState()).toEqual(expectedStore); }); //** diff --git a/openecomp-ui/test/softwareProduct/test.js b/openecomp-ui/test/softwareProduct/test.js new file mode 100644 index 0000000000..15f7a21866 --- /dev/null +++ b/openecomp-ui/test/softwareProduct/test.js @@ -0,0 +1,116 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import deepFreeze from 'deep-freeze'; +import mockRest from 'test-utils/MockRest.js'; +import {cloneAndSet} from 'test-utils/Util.js'; +import {storeCreator} from 'sdc-app/AppStore.js'; + +import SoftwareProductActionHelper from 'sdc-app/onboarding/softwareProduct/SoftwareProductActionHelper.js'; +import {VSPEditorFactoryWithLicensingData} from 'test-utils/factories/softwareProduct/SoftwareProductEditorFactories.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; +import {default as CurrentScreenFactory} from 'test-utils/factories/common/CurrentScreenFactory.js'; +import {actionsEnum as VersionControllerActionsEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js'; +import {SyncStates} from 'sdc-app/common/merge/MergeEditorConstants.js'; +import {itemTypes} from 'sdc-app/onboarding/versionsPage/VersionsPageConstants.js'; + +describe('Software Product Module Tests', function () { + it('Validating readonly screen after submit', () => { + const version = VersionFactory.build({}, {isCertified: false}); + const itemPermissionAndProps = CurrentScreenFactory.build({}, {version}); + const softwareProduct = VSPEditorFactoryWithLicensingData.build(); + deepFreeze(softwareProduct); + + const store = storeCreator({ + currentScreen: {...itemPermissionAndProps}, + softwareProduct: { + softwareProductEditor: {data: softwareProduct}, + softwareProductQuestionnaire: {qdata: 'test', qschema: {type: 'string'}} + } + }); + deepFreeze(store.getState()); + + const certifiedVersion = { + ...itemPermissionAndProps.props.version, + status: 'Certified' + }; + + const versionsList = { + itemType: itemTypes.SOFTWARE_PRODUCT, + itemId: softwareProduct.id, + versions: [{...certifiedVersion}] + }; + const expectedCurrentScreenProps = { + itemPermission: { + ...itemPermissionAndProps.itemPermission, + isCertified: true + }, + props: { + isReadOnlyMode: true, + version: certifiedVersion + } + }; + const expectedSuccessModal = { + cancelButtonText: 'OK', + modalClassName: 'notification-modal', + msg: 'This software product successfully submitted', + timeout: 2000, + title: 'Submit Succeeded', + type: 'success' + }; + + let expectedStore = store.getState(); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.itemPermission', expectedCurrentScreenProps.itemPermission); + expectedStore = cloneAndSet(expectedStore, 'currentScreen.props', expectedCurrentScreenProps.props); + expectedStore = cloneAndSet(expectedStore, 'modal', expectedSuccessModal); + expectedStore = cloneAndSet(expectedStore, 'versionsPage.versionsList', versionsList ); + + mockRest.addHandler('put', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProduct.id}/versions/${version.id}/actions`); + expect(data).toEqual({action: VersionControllerActionsEnum.SUBMIT}); + expect(options).toEqual(undefined); + return {returnCode: 'OK'}; + }); + + mockRest.addHandler('put', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/vendor-software-products/${softwareProduct.id}/versions/${version.id}/actions`); + expect(data).toEqual({action: VersionControllerActionsEnum.CREATE_PACKAGE}); + expect(options).toEqual(undefined); + return {returnCode: 'OK'}; + }); + + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${softwareProduct.id}/versions/${version.id}`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {...certifiedVersion, state: {synchronizationState: SyncStates.UP_TO_DATE, dirty: false}}; + }); + + mockRest.addHandler('fetch', ({data, options, baseUrl}) => { + expect(baseUrl).toEqual(`/onboarding-api/v1.0/items/${softwareProduct.id}/versions`); + expect(data).toEqual(undefined); + expect(options).toEqual(undefined); + return {results: [{...certifiedVersion}]}; + }); + + return SoftwareProductActionHelper.performSubmitAction(store.dispatch, { + softwareProductId: softwareProduct.id, + version + }).then(() => { + expect(store.getState()).toEqual(expectedStore); + }); + }); +}); \ No newline at end of file diff --git a/openecomp-ui/test/utils/errorResponseHandler.test.js b/openecomp-ui/test/utils/errorResponseHandler.test.js index 40836f728a..07f7ff72ac 100644 --- a/openecomp-ui/test/utils/errorResponseHandler.test.js +++ b/openecomp-ui/test/utils/errorResponseHandler.test.js @@ -26,7 +26,7 @@ describe('Error Response Handler Util', () => { deepFreeze(store.getState()); }); - it('validating error in policyException', done => { + it('validating error in policyException', () => { let textStatus = '', errorThrown = ''; let xhr = { responseJSON: { @@ -53,13 +53,10 @@ describe('Error Response Handler Util', () => { errorResponseHandler(xhr, textStatus, errorThrown); - setTimeout(function () { - expect(store.getState()).toEqual(expectedStore); - done(); - }, 100); + expect(store.getState()).toEqual(expectedStore); }); - it('validating error in serviceException with variables', done => { + it('validating error in serviceException with variables', () => { let textStatus = '', errorThrown = ''; let xhr = { responseJSON: { @@ -85,13 +82,10 @@ describe('Error Response Handler Util', () => { errorResponseHandler(xhr, textStatus, errorThrown); - setTimeout(function () { - expect(store.getState()).toEqual(expectedStore); - done(); - }, 100); + expect(store.getState()).toEqual(expectedStore); }); - it('validating error in response', done => { + it('validating error in response', () => { let textStatus = '', errorThrown = ''; let xhr = { responseJSON: { @@ -112,13 +106,10 @@ describe('Error Response Handler Util', () => { errorResponseHandler(xhr, textStatus, errorThrown); - setTimeout(function () { - expect(store.getState()).toEqual(expectedStore); - done(); - }, 100); + expect(store.getState()).toEqual(expectedStore); }); - it('validating error in request', done => { + it('validating error in request', () => { let textStatus = '', errorThrown = ''; let xhr = { statusText: '500', @@ -137,9 +128,6 @@ describe('Error Response Handler Util', () => { errorResponseHandler(xhr, textStatus, errorThrown); - setTimeout(function () { - expect(store.getState()).toEqual(expectedStore); - done(); - }, 100); + expect(store.getState()).toEqual(expectedStore); }); }); diff --git a/openecomp-ui/test/versionsPage/VersionsPage.test.js b/openecomp-ui/test/versionsPage/VersionsPage.test.js new file mode 100644 index 0000000000..7265ebf0a9 --- /dev/null +++ b/openecomp-ui/test/versionsPage/VersionsPage.test.js @@ -0,0 +1,154 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import React from 'react'; +import TestUtils from 'react-addons-test-utils'; +import deepFreeze from 'deep-freeze'; +import mockRest from 'test-utils/MockRest.js'; +import Configuration from 'sdc-app/config/Configuration.js'; +import {storeCreator} from 'sdc-app/AppStore.js'; + +import {mapStateToProps, mapActionsToProps} from 'sdc-app/onboarding/versionsPage/VersionsPage.js'; +import VersionsPageView from 'sdc-app/onboarding/versionsPage/VersionsPage.jsx'; +import VersionsPageActionHelper from 'sdc-app/onboarding/versionsPage/VersionsPageActionHelper.js'; +import VersionsPageCreationActionHelper from 'sdc-app/onboarding/versionsPage/creation/VersionsPageCreationActionHelper.js'; +import {itemTypes as versionPageItemTypes} from 'sdc-app/onboarding/versionsPage/VersionsPageConstants.js'; +import VersionFactory from 'test-utils/factories/common/VersionFactory.js'; +import {VersionsPageCreationFactory} from 'test-utils/factories/versionsPage/VersionsPageCreationFactories.js'; +import {VersionsPageAdditionalPropsFactory} from 'test-utils/factories/versionsPage/VersionsPageFactories.js'; + +describe('Versions Page Module Tests', () => { + + const state = { + currentScreen: { + itemPermission: { + isCollaborator: true + }, + props: { + itemId: '23' + } + }, + users: { + userInfo: 'user123' + }, + versionsPage: { + permissions: {}, + versionsList: {versions: []}, + versionCreation: {} + } + }; + + it ('mapStateToProps mapper exists', () => { + + expect(mapStateToProps).toBeTruthy(); + + }); + + it ('should have state in props', () => { + + const props = mapStateToProps(state); + expect(props.currentUser).toEqual('user123'); + + }); + + it('simple jsx test', () => { + + const store = storeCreator(); + const dispatch = store.dispatch; + + const additionalProps = VersionsPageAdditionalPropsFactory.build(); + + const props = Object.assign({}, mapStateToProps(state), mapActionsToProps(dispatch, additionalProps)); + const renderer = TestUtils.createRenderer(); + renderer.render(); + + const renderedOutput = renderer.getRenderOutput(); + expect(renderedOutput).toBeTruthy(); + + }); + +}); + +describe('Versions Page Actions', () => { + + let store, dispatch, restPrefix = '', version; + + beforeAll(() => { + restPrefix = Configuration.get('restPrefix'); + store = storeCreator(); + dispatch = store.dispatch; + deepFreeze(store.getState()); + version = VersionFactory.build(); + }); + + it('Select and deselect version', () => { + + let selectedVersionOf = (state) => state.versionsPage.versionsList.selectedVersion; + VersionsPageActionHelper.selectVersion(dispatch, {version}); + expect(selectedVersionOf(store.getState())).toEqual(version.id); + VersionsPageActionHelper.selectNone(dispatch); + expect(selectedVersionOf(store.getState())).toEqual(null); + + }); + + it('Create version', () => { + + const {id, baseId} = version; + + mockRest.addHandler('post', ({baseUrl}) => { + expect(baseUrl).toEqual(`${restPrefix}/v1.0/items/${id}/versions/${baseId}/`); + return version; + }); + + mockRest.addHandler('fetch', ({baseUrl}) => { + expect(baseUrl).toEqual(`${restPrefix}/v1.0/items/${id}/versions`); + return {results: [version]}; + }); + + return VersionsPageCreationActionHelper.createVersion(dispatch, { + itemId: id, + baseVersion: {id: baseId}, + payload: VersionsPageCreationFactory.build() + }) + .then(result => { + expect(result.id).toEqual(id); + }); + + }); + + it('Fetch versions', () => { + + const {id} = version; + + mockRest.addHandler('fetch', ({baseUrl}) => { + expect(baseUrl).toEqual(`${restPrefix}/v1.0/items/${id}/versions`); + return {results: [version]}; + }); + + return VersionsPageActionHelper.fetchVersions(dispatch, { + itemType: versionPageItemTypes.SOFTWARE_PRODUCT, + itemId: id + }) + .then(() => { + const {versionsPage: {versionsList}} = store.getState(); + expect(versionsList.versions[0].id).toEqual(id); + expect(versionsList.itemId).toEqual(id); + expect(versionsList.itemType).toEqual(versionPageItemTypes.SOFTWARE_PRODUCT); + }); + + }); + +}); diff --git a/openecomp-ui/test/versionsPage/creation/VersionsPageCreation.test.js b/openecomp-ui/test/versionsPage/creation/VersionsPageCreation.test.js new file mode 100644 index 0000000000..d490111178 --- /dev/null +++ b/openecomp-ui/test/versionsPage/creation/VersionsPageCreation.test.js @@ -0,0 +1,113 @@ +/*! + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ + +import React from 'react'; +import TestUtils from 'react-addons-test-utils'; +import {mapStateToProps, mapActionsToProps} from 'sdc-app/onboarding/versionsPage/creation/VersionsPageCreation.js'; +import {VERSION_CREATION_FORM_NAME} from 'sdc-app/onboarding/versionsPage/creation/VersionsPageCreationConstants.js'; +import VersionsPageCreationActionHelper from 'sdc-app/onboarding/versionsPage/creation/VersionsPageCreationActionHelper.js'; +import VersionsPageCreationView from 'sdc-app/onboarding/versionsPage/creation/VersionsPageCreationView.jsx'; +import {VersionsPageCreationFactory, + VersionsPageCreationFieldInfoFactory} from 'test-utils/factories/versionsPage/VersionsPageCreationFactories.js'; +import {VersionsPageAdditionalPropsFactory} from 'test-utils/factories/versionsPage/VersionsPageFactories.js'; +import {storeCreator} from 'sdc-app/AppStore.js'; + +describe('Versions Page Creation Module Tests', function() { + + let versionCreationData, genericFieldInfo; + let store, dispatch; + + beforeAll(() => { + store = storeCreator(); + dispatch = store.dispatch; + versionCreationData = VersionsPageCreationFactory.build(); + genericFieldInfo = VersionsPageCreationFieldInfoFactory.build(); + }); + + const additionalProps = VersionsPageAdditionalPropsFactory.build(); + + it ('mapStateToProps mapper exists', () => { + + expect(mapStateToProps).toBeTruthy(); + + }); + + it ('should return empty data', () => { + + const state = { + versionsPage: { + versionCreation: { + data: {}, + genericFieldInfo: {} + } + } + }; + + const props = mapStateToProps(state); + expect(props.data).toEqual({}); + expect(props.isFormValid).toEqual(true); + + }); + + it ('should have state in props', () => { + + const state = { + versionsPage: { + versionCreation: { + data: versionCreationData, + genericFieldInfo + } + } + }; + + const props = mapStateToProps(state); + expect(props.isFormValid).toEqual(true); + expect(props.data.description).toEqual(versionCreationData.description); + expect(props.genericFieldInfo).toEqual(genericFieldInfo); + + }); + + it('simple jsx test', () => { + + const state = { + versionsPage: { + versionCreation: { + data: versionCreationData, + genericFieldInfo + } + } + }; + + const props = Object.assign({}, mapStateToProps(state), mapActionsToProps(dispatch, additionalProps), additionalProps); + const renderer = TestUtils.createRenderer(); + renderer.render(); + + const renderedOutput = renderer.getRenderOutput(); + expect(renderedOutput).toBeTruthy(); + + }); + + it('open/close form actions', () => { + + VersionsPageCreationActionHelper.open(dispatch, additionalProps); + expect(store.getState().versionsPage.versionCreation.formName).toEqual(VERSION_CREATION_FORM_NAME); + + VersionsPageCreationActionHelper.close(dispatch); + expect(store.getState().versionsPage.versionCreation).toEqual({}); + + }); + +}); \ No newline at end of file diff --git a/openecomp-ui/webpack.common.js b/openecomp-ui/webpack.common.js index ebe4a8454a..68d8923458 100644 --- a/openecomp-ui/webpack.common.js +++ b/openecomp-ui/webpack.common.js @@ -5,7 +5,9 @@ let path = require('path'); let localDevConfig = {}; try { localDevConfig = require('./devConfig'); -} catch (e) {} +} catch (e) { + console.log('Could not find local dev config.'); +} let devConfig = Object.assign({}, require('./devConfig.defaults'), localDevConfig); module.exports = { @@ -23,11 +25,11 @@ module.exports = { }, module: { rules: [ - {test: /\.(js|jsx)$/, loader: 'source-map-loader', exclude: /node_modules/, enforce: 'pre'}, + {test: /\.(js|jsx)$/, loader: 'source-map-loader', exclude: [/node_modules/, path.resolve(__dirname, '../dox-sequence-diagram/')], enforce: 'pre'}, {test: /\.(js|jsx)$/, use: [ {loader : 'react-hot-loader'}, {loader : 'babel-loader'}, - {loader : 'eslint-loader'}], exclude: /node_modules/}, + {loader : 'eslint-loader'}], exclude: [/node_modules/, path.resolve(__dirname, '../dox-sequence-diagram/')]}, {test: /\.(css|scss)$/, use: [ {loader: 'style-loader'}, {loader: 'css-loader?sourceMap'}, -- cgit 1.2.3-korg