diff --git a/Dockerfile b/Dockerfile index 7953abb037..ec76ded9ab 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM --platform=$BUILDPLATFORM gradle:8.4.0-jdk21 AS build +FROM --platform=$BUILDPLATFORM gradle:8.5.0-jdk21 AS build ARG RELEASE_MODE ARG APP_VERSION WORKDIR /usr/app diff --git a/Jenkinsfile b/Jenkinsfile deleted file mode 100644 index 74087836ed..0000000000 --- a/Jenkinsfile +++ /dev/null @@ -1,44 +0,0 @@ -#!groovy - -node { - - load "$JENKINS_HOME/jobvars.env" - - env.JAVA_HOME = "${tool 'openjdk-11'}" - env.PATH = "${env.JAVA_HOME}/bin:${env.PATH}" - - stage('Checkout') { - checkout scm - } - stage('Assemble') { - sh "./gradlew clean assemble -P buildNumber=${env.BUILD_NUMBER}" - } - stage('Test') { - sh './gradlew test --full-stacktrace' - } - stage('Build') { - sh './gradlew build' - } - stage('Docker image') { - sh "./gradlew buildDocker" - } - stage('Push to registries') { - withEnv(["AWS_URI=${AWS_URI}", "AWS_REGION=${AWS_REGION}"]) { - sh 'docker tag reportportal-dev/service-api ${AWS_URI}/service-api:SNAPSHOT-${BUILD_NUMBER}' - def image = env.AWS_URI + '/service-api' + ':SNAPSHOT-' + env.BUILD_NUMBER - def url = 'https://' + env.AWS_URI - def credentials = 'ecr:' + env.AWS_REGION + ':aws_credentials' - echo image - docker.withRegistry(url, credentials) { - docker.image(image).push() - } - } - } - stage('Cleanup') { - withEnv(["AWS_URI=${AWS_URI}"]) { - sh 'docker rmi ${AWS_URI}/service-api:SNAPSHOT-${BUILD_NUMBER}' - sh 'docker rmi reportportal-dev/service-api:latest' - sh './gradlew removeScripts' - } - } -} diff --git a/Jenkinsfile-candidate b/Jenkinsfile-candidate deleted file mode 100644 index 162dfed587..0000000000 --- a/Jenkinsfile-candidate +++ /dev/null @@ -1,57 +0,0 @@ -#!groovy -properties([ - parameters ([ - string( - name: "VERSION", - defaultValue: "", - description: "Release candidate version tag" - ), - string( - name: "BRANCH", - defaultValue: "", - description: "Specify the GitHub branch from which the image will be built" - ) - ]) -]) - -node { - - load "$JENKINS_HOME/jobvars.env" - - env.JAVA_HOME = "${tool 'openjdk-11'}" - env.PATH = "${env.JAVA_HOME}/bin:${env.PATH}" - - stage('Checkout') { - checkout scm - } - - stage('Assemble') { - sh "./gradlew clean assemble -P buildNumber=${env.BUILD_NUMBER}" - } - - stage('Test') { - sh './gradlew test --full-stacktrace' - } - - stage('Build') { - sh './gradlew build -x test' - } - - stage('Push to ECR') { - withEnv(["AWS_URI=${AWS_URI}", "AWS_REGION=${AWS_REGION}", "TAG=${VERSION}"]) { - def image = env.AWS_URI + '/service-api:' + env.TAG + '-RC-' + env.BUILD_NUMBER - def url = 'https://' + env.AWS_URI - def credentials = 'ecr:' + env.AWS_REGION + ':aws_credentials' - sh './gradlew buildDocker -P dockerTag=$AWS_URI/service-api:$VERSION-RC-$BUILD_NUMBER' - docker.withRegistry(url, credentials) { - docker.image(image).push() - } - } - } - - stage('Cleanup') { - withEnv(["AWS_URI=${AWS_URI}"]) { - sh 'docker rmi $AWS_URI/service-api:$VERSION-RC-$BUILD_NUMBER' - } - } -} diff --git a/Jenkinsfile-release b/Jenkinsfile-release deleted file mode 100644 index cd1bc94e47..0000000000 --- a/Jenkinsfile-release +++ /dev/null @@ -1,42 +0,0 @@ -pipeline { - agent any - - environment { - JAVA_HOME = "${tool 'openjdk-11'}" - PATH = "${env.JAVA_HOME}/bin:${env.PATH}" - DOCKERHUB = credentials('dockerhub') - GITHUB = credentials('github_token') - } - - stages { - stage('Assemble') { - steps { - sh './gradlew clean assemble -P buildNumber=$VERSION' - } - } - - stage('Test') { - steps { - sh './gradlew test --full-stacktrace' - } - } - - stage('Build Artifact'){ - steps{ - sh './gradlew build -PreleaseMode=true -PgithubUserName=$GITHUB_USR -PgithubToken=$GITHUB_PSW' - } - } - - stage('Build Docker Image'){ - steps{ - sh './gradlew buildDocker -P dockerTag=reportportal/service-api:$VERSION' - } - } - - stage('Push to DockerHub') { - steps { - sh 'echo $DOCKERHUB_PSW | docker login -u $DOCKERHUB_USR --password-stdin && docker push reportportal/service-api:$VERSION' - } - } - } -} \ No newline at end of file diff --git a/build.gradle b/build.gradle index 1ff5d40461..f5e3d303f9 100644 --- a/build.gradle +++ b/build.gradle @@ -18,13 +18,12 @@ plugins { id "io.spring.dependency-management" version "1.1.4" id 'org.springframework.boot' version '2.5.15' id 'java' - id "org.owasp.dependencycheck" version "8.2.1" + id "org.owasp.dependencycheck" version "9.0.9" } import org.owasp.dependencycheck.reporting.ReportGenerator apply from: 'project-properties.gradle' -apply from: "$scriptsUrl/build-docker.gradle" apply from: "$scriptsUrl/build-commons.gradle" apply from: "$scriptsUrl/build-info.gradle" apply from: "$scriptsUrl/release-service.gradle" @@ -73,13 +72,14 @@ dependencies { implementation 'com.epam.reportportal:commons-fonts' implementation 'com.epam.reportportal:plugin-api' } else { - implementation 'com.epam.reportportal:commons-events' - implementation 'com.epam.reportportal:commons-dao' - implementation 'com.epam.reportportal:commons-rules' - implementation 'com.epam.reportportal:commons-model' - implementation 'com.epam.reportportal:commons' - implementation 'com.epam.reportportal:commons-fonts' - implementation 'com.epam.reportportal:plugin-api' + implementation 'com.github.reportportal:commons-events:e337f8b7be' + implementation 'com.github.reportportal:commons-dao:b2c73ac' + implementation 'com.github.reportportal:commons-rules:1f6bfed' + implementation 'com.github.reportportal:commons-model:f466951' + implementation 'com.github.reportportal:commons-reporting:12c31b1' + implementation 'com.github.reportportal:commons:07566b8e' + implementation 'com.github.reportportal:commons-fonts:d6e62dd' + implementation 'com.github.reportportal:plugin-api:cc3c5c8' } implementation 'org.springframework.boot:spring-boot-starter-aop' @@ -113,9 +113,11 @@ dependencies { implementation 'xerces:xercesImpl:2.12.2' implementation 'com.lowagie:itext:2.1.7.js7' // JasperReport's export to XLS uses Apache POI - implementation 'org.apache.poi:poi:4.1.2' - implementation 'io.springfox:springfox-swagger2:2.9.2' + implementation 'org.apache.poi:poi:5.2.3' + implementation 'org.springdoc:springdoc-openapi-ui:1.7.0' implementation 'com.google.code.gson:gson:2.8.9' + implementation 'com.google.api-client:google-api-client:2.3.0' + implementation 'joda-time:joda-time:2.12.7' ///// Security @@ -181,7 +183,8 @@ dependencyCheck { } bootJar { - project.hasProperty('gcp') ? getArchiveFileName().set('app.jar') : archiveClassifier.set('exec') + project.hasProperty('gcp') ? getArchiveFileName().set('app.jar') : archiveClassifier.set('' + + 'exec') } jar.enabled(true) jar.archiveClassifier.set('') diff --git a/docker-compose.yml b/docker-compose.yml index ee9e4e2b8d..e23d9c8c6f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -24,11 +24,11 @@ services: ports: - "5432:5432" - elastic: - image: docker.elastic.co/elasticsearch/elasticsearch-oss:7.3.0 + opensearch: + image: opensearchproject/opensearch:2.11.0 restart: always volumes: - - elastic:/usr/share/elasticsearch/data + - opensearch:/usr/share/opensearch/data environment: - "bootstrap.memory_lock=true" - "discovery.type=single-node" @@ -77,5 +77,5 @@ services: volumes: reportportal-database: - elastic: + opensearch: minio: \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e69de29bb2..7f93135c49 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index e411586a54..1af9e0930b 100755 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/project-properties.gradle b/project-properties.gradle index 5aa0e51a56..a6cbd58fe2 100755 --- a/project-properties.gradle +++ b/project-properties.gradle @@ -16,7 +16,7 @@ project.ext { isDebugMode = System.getProperty("DEBUG", "false") == "true" releaseMode = project.hasProperty("releaseMode") scriptsUrl = commonScriptsUrl + (releaseMode ? '5.11.0' : 'develop') - migrationsUrl = migrationsScriptsUrl + (releaseMode ? '5.11.0' : 'feature/settings') + migrationsUrl = migrationsScriptsUrl + (releaseMode ? '5.11.0' : 'develop') //TODO refactor with archive download testScriptsSrc = [ (migrationsUrl + '/migrations/0_extensions.up.sql') : 'V001__extensions.sql', @@ -77,10 +77,11 @@ project.ext { '**/job/FlushingDataJob**', "**/core/analyzer/auto/client/model/**", '**/core/analyzer/auto/impl/SuggestedItem**', - '**/core/item/impl/provider/impl/mock/**' + '**/core/item/impl/provider/impl/mock/**', + '**/model/**' ] } wrapper { - gradleVersion = '8.4' + gradleVersion = '8.5' } diff --git a/src/main/java/com/epam/ta/reportportal/auth/permissions/AssignedToProjectPermission.java b/src/main/java/com/epam/ta/reportportal/auth/permissions/AssignedToProjectPermission.java index de589a17f0..d1f5dd4dfe 100644 --- a/src/main/java/com/epam/ta/reportportal/auth/permissions/AssignedToProjectPermission.java +++ b/src/main/java/com/epam/ta/reportportal/auth/permissions/AssignedToProjectPermission.java @@ -19,15 +19,16 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Maps; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.stereotype.Component; -import java.util.*; - /** * Check whether user assigned to project * diff --git a/src/main/java/com/epam/ta/reportportal/auth/permissions/BaseProjectPermission.java b/src/main/java/com/epam/ta/reportportal/auth/permissions/BaseProjectPermission.java index 372b7be071..bab527a16d 100644 --- a/src/main/java/com/epam/ta/reportportal/auth/permissions/BaseProjectPermission.java +++ b/src/main/java/com/epam/ta/reportportal/auth/permissions/BaseProjectPermission.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Maps; import java.util.Map; import java.util.Objects; diff --git a/src/main/java/com/epam/ta/reportportal/core/activity/ActivityHandler.java b/src/main/java/com/epam/ta/reportportal/core/activity/ActivityHandler.java index e795b03a7b..7f4d841322 100644 --- a/src/main/java/com/epam/ta/reportportal/core/activity/ActivityHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/activity/ActivityHandler.java @@ -14,12 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.activity; import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.querygen.Queryable; -import com.epam.ta.reportportal.ws.model.ActivityEventResource; +import com.epam.ta.reportportal.model.ActivityEventResource; import com.epam.ta.reportportal.ws.model.ActivityResource; import org.springframework.data.domain.Pageable; @@ -32,16 +33,15 @@ public interface ActivityHandler { * Load list of {@link com.epam.ta.reportportal.ws.model.ActivityResource} for specified * {@link com.epam.ta.reportportal.entity.item.TestItem} * - * @param projectDetails Details of project - * {@link com.epam.ta.reportportal.commons.ReportPortalUser.ProjectDetails} - * @param filter Filter - * @param pageable Page Details - * @param predefinedFilter Additional filter + * @param projectDetails Details of project + * {@link com.epam.ta.reportportal.commons.ReportPortalUser.ProjectDetails} + * @param filter Filter + * @param pageable Page Details + * @param predefinedFilter Additional filter * @return Found activities */ Iterable getActivitiesHistory(ReportPortalUser.ProjectDetails projectDetails, - Filter filter, - Queryable predefinedFilter, Pageable pageable); + Filter filter, Queryable predefinedFilter, Pageable pageable); /** * Load {@link com.epam.ta.reportportal.ws.model.ActivityResource} @@ -53,23 +53,22 @@ Iterable getActivitiesHistory(ReportPortalUser.ProjectDetails */ ActivityResource getActivity(ReportPortalUser.ProjectDetails projectDetails, Long activityId); - /** - * Load list of {@link com.epam.ta.reportportal.ws.model.ActivityEventResource} for specified - * {@link com.epam.ta.reportportal.entity.item.TestItem} - * - * @param projectDetails Details of project - * {@link com.epam.ta.reportportal.commons.ReportPortalUser.ProjectDetails} - * @param itemId ID of test item - * @param filter Filter - * @param pageable Page Details - * @return Found activities - */ - Iterable getItemActivities(ReportPortalUser.ProjectDetails projectDetails, - Long itemId, Filter filter, - Pageable pageable); + /** + * Load list of {@link ActivityEventResource} for specified + * {@link com.epam.ta.reportportal.entity.item.TestItem} + * + * @param projectDetails Details of project + * {@link com.epam.ta.reportportal.commons.ReportPortalUser.ProjectDetails} + * @param itemId ID of test item + * @param filter Filter + * @param pageable Page Details + * @return Found activities + */ + Iterable getItemActivities(ReportPortalUser.ProjectDetails projectDetails, + Long itemId, Filter filter, Pageable pageable); /** - * Load list of {@link com.epam.ta.reportportal.ws.model.ActivityResource} for specified + * Load list of {@link ActivityResource} for specified * {@link com.epam.ta.reportportal.entity.project.Project} * * @param projectDetails Details of project {@link ReportPortalUser.ProjectDetails} diff --git a/src/main/java/com/epam/ta/reportportal/core/activity/impl/ActivityHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/activity/impl/ActivityHandlerImpl.java index a14b93f9d9..5ce7c2021b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/activity/impl/ActivityHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/activity/impl/ActivityHandlerImpl.java @@ -21,10 +21,11 @@ import static com.epam.ta.reportportal.commons.querygen.constant.ActivityCriteriaConstant.CRITERIA_OBJECT_TYPE; import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_PROJECT_ID; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACTIVITY_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.TEST_ITEM_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACTIVITY_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.TEST_ITEM_NOT_FOUND; import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.CompositeFilter; @@ -46,12 +47,11 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.ActivityEventResource; import com.epam.ta.reportportal.ws.converter.PagedResourcesAssembler; import com.epam.ta.reportportal.ws.converter.converters.ActivityConverter; import com.epam.ta.reportportal.ws.converter.converters.ActivityEventConverter; -import com.epam.ta.reportportal.ws.model.ActivityEventResource; import com.epam.ta.reportportal.ws.model.ActivityResource; -import com.epam.ta.reportportal.ws.model.ErrorType; import java.util.function.Predicate; import org.apache.commons.lang3.BooleanUtils; import org.jooq.Operator; @@ -118,7 +118,7 @@ public Iterable getItemActivities( Pageable pageable) { TestItem testItem = testItemRepository.findById(itemId).orElseThrow(() -> new ReportPortalException(TEST_ITEM_NOT_FOUND, itemId)); Launch launch = launchRepository.findById(testItem.getLaunchId()) - .orElseThrow(() -> new ReportPortalException(ErrorType.LAUNCH_NOT_FOUND, testItem.getLaunchId())); + .orElseThrow(() -> new ReportPortalException(LAUNCH_NOT_FOUND, testItem.getLaunchId())); expect(projectDetails.getProjectId(), Predicate.isEqual(launch.getProjectId())).verify(ACCESS_DENIED, Suppliers.formattedSupplier("Test item with id '{}' is not under project with id '{}'", itemId, diff --git a/src/main/java/com/epam/ta/reportportal/core/activityevent/ActivityEventHandler.java b/src/main/java/com/epam/ta/reportportal/core/activityevent/ActivityEventHandler.java index 398e503048..5fa60a2bd4 100644 --- a/src/main/java/com/epam/ta/reportportal/core/activityevent/ActivityEventHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/activityevent/ActivityEventHandler.java @@ -18,12 +18,11 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Queryable; -import com.epam.ta.reportportal.ws.model.ActivityEventResource; -import com.epam.ta.reportportal.ws.model.PagedResponse; +import com.epam.ta.reportportal.model.ActivityEventResource; +import com.epam.ta.reportportal.model.PagedResponse; import java.util.List; import org.springframework.data.domain.Pageable; - /** * Activity Event Handler. * diff --git a/src/main/java/com/epam/ta/reportportal/core/activityevent/impl/ActivityEventHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/activityevent/impl/ActivityEventHandlerImpl.java index bb1db79398..16ebdc0b4c 100644 --- a/src/main/java/com/epam/ta/reportportal/core/activityevent/impl/ActivityEventHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/activityevent/impl/ActivityEventHandlerImpl.java @@ -24,11 +24,11 @@ import com.epam.ta.reportportal.core.activityevent.ActivityEventHandler; import com.epam.ta.reportportal.dao.ActivityRepository; import com.epam.ta.reportportal.entity.activity.Activity; +import com.epam.ta.reportportal.model.ActivityEventResource; +import com.epam.ta.reportportal.model.PagedResponse; import com.epam.ta.reportportal.ws.converter.PagedResourcesAssembler; import com.epam.ta.reportportal.ws.converter.converters.ActivityEventConverter; -import com.epam.ta.reportportal.ws.model.ActivityEventResource; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.PagedResponse; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -42,8 +42,8 @@ @Service public class ActivityEventHandlerImpl implements ActivityEventHandler { - private static final String LENGTH_LESS_THAN_1_SYMBOL_MSG = "Length of the filtering string " - + "'{}' is less than 1 symbol"; + private static final String LENGTH_LESS_THAN_1_SYMBOL_MSG = + "Length of the filtering string " + "'{}' is less than 1 symbol"; private final ActivityRepository activityRepository; @@ -55,8 +55,7 @@ public ActivityEventHandlerImpl(ActivityRepository activityRepository) { public PagedResponse getActivityEventsHistory(Queryable filter, Pageable pageable) { Page activityPage = activityRepository.findByFilter(filter, pageable); - return PagedResourcesAssembler - .pagedResponseConverter(ActivityEventConverter.TO_RESOURCE) + return PagedResourcesAssembler.pagedResponseConverter(ActivityEventConverter.TO_RESOURCE) .apply(activityPage); } @@ -68,8 +67,9 @@ public List getSubjectNames(ProjectDetails projectDetails, String value) } private void checkBusinessRuleLessThan1Symbol(String value) { - BusinessRule.expect(value.length() >= 1, Predicates.equalTo(true)) - .verify(ErrorType.INCORRECT_FILTER_PARAMETERS, - Suppliers.formattedSupplier(LENGTH_LESS_THAN_1_SYMBOL_MSG, value)); + BusinessRule.expect(value.length() >= 1, Predicates.equalTo(true)).verify( + ErrorType.INCORRECT_FILTER_PARAMETERS, + Suppliers.formattedSupplier(LENGTH_LESS_THAN_1_SYMBOL_MSG, value) + ); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/admin/ServerAdminHandler.java b/src/main/java/com/epam/ta/reportportal/core/admin/ServerAdminHandler.java index 591afac049..c08511248e 100644 --- a/src/main/java/com/epam/ta/reportportal/core/admin/ServerAdminHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/admin/ServerAdminHandler.java @@ -16,9 +16,9 @@ package com.epam.ta.reportportal.core.admin; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.settings.AnalyticsResource; -import com.epam.ta.reportportal.ws.model.settings.ServerSettingsResource; +import com.epam.ta.reportportal.model.settings.AnalyticsResource; +import com.epam.ta.reportportal.model.settings.ServerSettingsResource; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.Map; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/admin/ServerAdminHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/admin/ServerAdminHandlerImpl.java index feb792b1d6..c4708106f7 100644 --- a/src/main/java/com/epam/ta/reportportal/core/admin/ServerAdminHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/admin/ServerAdminHandlerImpl.java @@ -22,9 +22,9 @@ import com.epam.ta.reportportal.dao.ServerSettingsRepository; import com.epam.ta.reportportal.entity.ServerSettings; +import com.epam.ta.reportportal.model.settings.AnalyticsResource; import com.epam.ta.reportportal.ws.converter.converters.ServerSettingsConverter; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.settings.AnalyticsResource; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.Map; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; @@ -54,17 +54,17 @@ public Map getServerSettings() { @Override public OperationCompletionRS saveAnalyticsSettings(AnalyticsResource analyticsResource) { String analyticsType = analyticsResource.getType(); - Map serverAnalyticsDetails = findServerSettings().entrySet() - .stream() + Map serverAnalyticsDetails = findServerSettings().entrySet().stream() .filter(entry -> entry.getKey().startsWith(ANALYTICS_CONFIG_PREFIX)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - String formattedAnalyticsType = analyticsType.startsWith(ANALYTICS_CONFIG_PREFIX) ? - analyticsType : - ANALYTICS_CONFIG_PREFIX + analyticsType; + String formattedAnalyticsType = + analyticsType.startsWith(ANALYTICS_CONFIG_PREFIX) ? analyticsType : + ANALYTICS_CONFIG_PREFIX + analyticsType; - ServerSettings analyticsDetails = ofNullable( - serverAnalyticsDetails.get(formattedAnalyticsType)).orElseGet(ServerSettings::new); + ServerSettings analyticsDetails = + ofNullable(serverAnalyticsDetails.get(formattedAnalyticsType)).orElseGet( + ServerSettings::new); analyticsDetails.setKey(formattedAnalyticsType); analyticsDetails.setValue( String.valueOf((ofNullable(analyticsResource.getEnabled()).orElse(false)))); @@ -74,8 +74,7 @@ public OperationCompletionRS saveAnalyticsSettings(AnalyticsResource analyticsRe } private Map findServerSettings() { - return serverSettingsRepository.selectServerSettings() - .stream() + return serverSettingsRepository.selectServerSettings().stream() .collect(toMap(ServerSettings::getKey, s -> s, (prev, curr) -> prev)); } } \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/SearchLogService.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/SearchLogService.java index e6913b8035..2e4d880ae5 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/SearchLogService.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/SearchLogService.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.core.analyzer.auto; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.log.SearchLogRq; -import com.epam.ta.reportportal.ws.model.log.SearchLogRs; +import com.epam.ta.reportportal.model.log.SearchLogRq; +import com.epam.ta.reportportal.model.log.SearchLogRs; /** * @author Ihar Kahadouski diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/AnalyzerServiceClient.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/AnalyzerServiceClient.java index f6fdd5b19e..2e0c78334d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/AnalyzerServiceClient.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/AnalyzerServiceClient.java @@ -21,10 +21,10 @@ import com.epam.ta.reportportal.core.analyzer.auto.client.model.SuggestRq; import com.epam.ta.reportportal.core.analyzer.auto.client.model.cluster.ClusterData; import com.epam.ta.reportportal.core.analyzer.auto.client.model.cluster.GenerateClustersRq; -import com.epam.ta.reportportal.ws.model.analyzer.AnalyzedItemRs; +import com.epam.ta.reportportal.model.analyzer.AnalyzedItemRs; +import com.epam.ta.reportportal.model.analyzer.SearchRq; +import com.epam.ta.reportportal.model.analyzer.SearchRs; import com.epam.ta.reportportal.ws.model.analyzer.IndexLaunch; -import com.epam.ta.reportportal.ws.model.analyzer.SearchRq; -import com.epam.ta.reportportal.ws.model.analyzer.SearchRs; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/impl/AnalyzerServiceClientImpl.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/impl/AnalyzerServiceClientImpl.java index 69de662e08..f643f89612 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/impl/AnalyzerServiceClientImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/impl/AnalyzerServiceClientImpl.java @@ -29,11 +29,11 @@ import com.epam.ta.reportportal.core.analyzer.auto.client.model.cluster.ClusterData; import com.epam.ta.reportportal.core.analyzer.auto.client.model.cluster.GenerateClustersRq; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.analyzer.AnalyzedItemRs; +import com.epam.ta.reportportal.model.analyzer.AnalyzedItemRs; +import com.epam.ta.reportportal.model.analyzer.SearchRq; +import com.epam.ta.reportportal.model.analyzer.SearchRs; import com.epam.ta.reportportal.ws.model.analyzer.IndexLaunch; -import com.epam.ta.reportportal.ws.model.analyzer.SearchRq; -import com.epam.ta.reportportal.ws.model.analyzer.SearchRs; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.rabbitmq.http.client.domain.ExchangeInfo; import java.util.Collections; import java.util.Comparator; @@ -90,28 +90,31 @@ public Map> analyze(IndexLaunch rq) { @Override public List searchLogs(SearchRq rq) { - String exchangeName = resolveExchangeName(DOES_SUPPORT_SEARCH) - .orElseThrow(() -> new ReportPortalException(ErrorType.UNABLE_INTERACT_WITH_INTEGRATION, + String exchangeName = + resolveExchangeName(DOES_SUPPORT_SEARCH).orElseThrow(() -> new ReportPortalException( + ErrorType.UNABLE_INTERACT_WITH_INTEGRATION, "There are no analyzer services with search logs support deployed." )); return rabbitTemplate.convertSendAndReceiveAsType(exchangeName, SEARCH_ROUTE, rq, new ParameterizedTypeReference<>() { - }); + } + ); } @Override public void removeSuggest(Long projectId) { - resolveExchangeName(DOES_SUPPORT_SUGGEST) - .ifPresent( - suggestExchange -> rabbitTemplate.convertAndSend(suggestExchange, REMOVE_SUGGEST_ROUTE, - projectId)); + resolveExchangeName(DOES_SUPPORT_SUGGEST).ifPresent( + suggestExchange -> rabbitTemplate.convertAndSend(suggestExchange, REMOVE_SUGGEST_ROUTE, + projectId + )); } @Override public List searchSuggests(SuggestRq rq) { return rabbitTemplate.convertSendAndReceiveAsType(getSuggestExchangeName(), SUGGEST_ROUTE, rq, new ParameterizedTypeReference<>() { - }); + } + ); } @Override @@ -121,42 +124,41 @@ public void handleSuggestChoice(List suggestInfos) { @Override public ClusterData generateClusters(GenerateClustersRq generateClustersRq) { - final String exchangeName = resolveExchangeName(DOES_SUPPORT_CLUSTER).orElseThrow( - () -> new ReportPortalException(ErrorType.UNABLE_INTERACT_WITH_INTEGRATION, + final String exchangeName = + resolveExchangeName(DOES_SUPPORT_CLUSTER).orElseThrow(() -> new ReportPortalException( + ErrorType.UNABLE_INTERACT_WITH_INTEGRATION, "There are no analyzer services with clusters creation support deployed." )); return rabbitTemplate.convertSendAndReceiveAsType(exchangeName, CLUSTER_ROUTE, generateClustersRq, new ParameterizedTypeReference<>() { - }); + } + ); } private Optional resolveExchangeName(Predicate supportCondition) { - return rabbitMqManagementClient.getAnalyzerExchangesInfo() - .stream() - .filter(supportCondition) - .min(Comparator.comparingInt(EXCHANGE_PRIORITY)) - .map(ExchangeInfo::getName); + return rabbitMqManagementClient.getAnalyzerExchangesInfo().stream().filter(supportCondition) + .min(Comparator.comparingInt(EXCHANGE_PRIORITY)).map(ExchangeInfo::getName); } private String getSuggestExchangeName() { - return resolveExchangeName(DOES_SUPPORT_SUGGEST) - .orElseThrow(() -> new ReportPortalException(ErrorType.UNABLE_INTERACT_WITH_INTEGRATION, - "There are no analyzer services with suggest items support deployed." - )); + return resolveExchangeName(DOES_SUPPORT_SUGGEST).orElseThrow(() -> new ReportPortalException( + ErrorType.UNABLE_INTERACT_WITH_INTEGRATION, + "There are no analyzer services with suggest items support deployed." + )); } private void analyze(IndexLaunch rq, Map> resultMap, ExchangeInfo exchangeInfo) { - List result = rabbitTemplate.convertSendAndReceiveAsType(exchangeInfo.getName(), - ANALYZE_ROUTE, - Collections.singletonList(rq), - new ParameterizedTypeReference<>() { - } - ); + List result = + rabbitTemplate.convertSendAndReceiveAsType(exchangeInfo.getName(), ANALYZE_ROUTE, + Collections.singletonList(rq), new ParameterizedTypeReference<>() { + } + ); if (!CollectionUtils.isEmpty(result)) { resultMap.put( (String) exchangeInfo.getArguments().getOrDefault(virtualHost, exchangeInfo.getName()), - result); + result + ); removeAnalyzedFromRq(rq, result); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/impl/IndexerServiceClientImpl.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/impl/IndexerServiceClientImpl.java index 6f5450f6e2..9f5547ab24 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/impl/IndexerServiceClientImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/impl/IndexerServiceClientImpl.java @@ -26,15 +26,13 @@ import com.epam.ta.reportportal.core.analyzer.auto.client.model.IndexDefectsUpdate; import com.epam.ta.reportportal.core.analyzer.auto.client.model.IndexItemsRemove; import com.epam.ta.reportportal.core.analyzer.auto.client.model.IndexLaunchRemove; -import com.epam.ta.reportportal.ws.model.analyzer.CleanIndexRq; +import com.epam.ta.reportportal.model.analyzer.CleanIndexRq; import com.epam.ta.reportportal.ws.model.analyzer.IndexLaunch; -import com.epam.ta.reportportal.ws.model.analyzer.IndexRs; import java.util.AbstractMap; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -80,91 +78,68 @@ public void index(List rq) { @Override public List indexDefectsUpdate(Long projectId, Map itemsForIndexUpdate) { - return rabbitMqManagementClient.getAnalyzerExchangesInfo() - .stream() - .filter(DOES_SUPPORT_INDEX) - .flatMap( - exchange -> ofNullable(rabbitTemplate.convertSendAndReceiveAsType(exchange.getName(), - DEFECT_UPDATE_ROUTE, + return rabbitMqManagementClient.getAnalyzerExchangesInfo().stream().filter(DOES_SUPPORT_INDEX) + .flatMap(exchange -> ofNullable( + rabbitTemplate.convertSendAndReceiveAsType(exchange.getName(), DEFECT_UPDATE_ROUTE, new IndexDefectsUpdate(projectId, itemsForIndexUpdate), new ParameterizedTypeReference>() { } - )).orElse(Collections.emptyList()).stream()) - .collect(toList()); + )).orElse(Collections.emptyList()).stream()).collect(toList()); } @Override public Integer indexItemsRemove(Long projectId, Collection itemsForIndexRemove) { - return rabbitMqManagementClient.getAnalyzerExchangesInfo() - .stream() - .filter(DOES_SUPPORT_INDEX) - .map(exchange -> ofNullable(rabbitTemplate.convertSendAndReceiveAsType(exchange.getName(), - ITEM_REMOVE_ROUTE, - new IndexItemsRemove(projectId, itemsForIndexRemove), - new ParameterizedTypeReference() { - } - )).orElse(0)) - .mapToInt(Integer::intValue) - .sum(); + return rabbitMqManagementClient.getAnalyzerExchangesInfo().stream().filter(DOES_SUPPORT_INDEX) + .map(exchange -> ofNullable( + rabbitTemplate.convertSendAndReceiveAsType(exchange.getName(), ITEM_REMOVE_ROUTE, + new IndexItemsRemove(projectId, itemsForIndexRemove), + new ParameterizedTypeReference() { + } + )).orElse(0)).mapToInt(Integer::intValue).sum(); } @Override public void indexItemsRemoveAsync(Long projectId, Collection itemsForIndexRemove) { - rabbitMqManagementClient.getAnalyzerExchangesInfo() - .stream() - .filter(DOES_SUPPORT_INDEX) - .forEach(exchange -> rabbitTemplate.convertAndSend(exchange.getName(), - ITEM_REMOVE_ROUTE, + rabbitMqManagementClient.getAnalyzerExchangesInfo().stream().filter(DOES_SUPPORT_INDEX).forEach( + exchange -> rabbitTemplate.convertAndSend(exchange.getName(), ITEM_REMOVE_ROUTE, new IndexItemsRemove(projectId, itemsForIndexRemove) )); } @Override public void indexLaunchesRemove(Long projectId, Collection launchesForIndexRemove) { - rabbitMqManagementClient.getAnalyzerExchangesInfo() - .stream() - .filter(DOES_SUPPORT_INDEX) - .forEach(exchange -> rabbitTemplate.convertAndSend(exchange.getName(), - LAUNCH_REMOVE_ROUTE, + rabbitMqManagementClient.getAnalyzerExchangesInfo().stream().filter(DOES_SUPPORT_INDEX).forEach( + exchange -> rabbitTemplate.convertAndSend(exchange.getName(), LAUNCH_REMOVE_ROUTE, new IndexLaunchRemove(projectId, launchesForIndexRemove) )); } @Override public Long cleanIndex(Long index, List ids) { - Map priorityToCleanedLogsCountMapping = rabbitMqManagementClient.getAnalyzerExchangesInfo() - .stream() - .collect(Collectors.toMap(EXCHANGE_PRIORITY::applyAsInt, - exchange -> rabbitTemplate.convertSendAndReceiveAsType(exchange.getName(), - CLEAN_ROUTE, - new CleanIndexRq(index, ids), - new ParameterizedTypeReference<>() { - } - ) - )); - return priorityToCleanedLogsCountMapping.entrySet() - .stream() - .min(Map.Entry.comparingByKey()) - .orElseGet(() -> new AbstractMap.SimpleEntry<>(0, 0L)) - .getValue(); + Map priorityToCleanedLogsCountMapping = + rabbitMqManagementClient.getAnalyzerExchangesInfo().stream().collect( + Collectors.toMap(EXCHANGE_PRIORITY::applyAsInt, + exchange -> rabbitTemplate.convertSendAndReceiveAsType(exchange.getName(), + CLEAN_ROUTE, new CleanIndexRq(index, ids), new ParameterizedTypeReference<>() { + } + ) + )); + return priorityToCleanedLogsCountMapping.entrySet().stream().min(Map.Entry.comparingByKey()) + .orElseGet(() -> new AbstractMap.SimpleEntry<>(0, 0L)).getValue(); } @Override public void deleteIndex(Long index) { - rabbitMqManagementClient.getAnalyzerExchangesInfo() - .stream() - .map(exchange -> rabbitTemplate.convertSendAndReceiveAsType(exchange.getName(), - DELETE_ROUTE, - index, - new ParameterizedTypeReference() { + rabbitMqManagementClient.getAnalyzerExchangesInfo().stream().map( + exchange -> rabbitTemplate.convertSendAndReceiveAsType(exchange.getName(), DELETE_ROUTE, + index, new ParameterizedTypeReference() { } - )) - .forEach(it -> { - if (DELETE_INDEX_SUCCESS_CODE.equals(it)) { - LOGGER.info("Successfully deleted index '{}'", index); - } else { - LOGGER.error("Error deleting index '{}'", index); - } - }); + )).forEach(it -> { + if (DELETE_INDEX_SUCCESS_CODE.equals(it)) { + LOGGER.info("Successfully deleted index '{}'", index); + } else { + LOGGER.error("Error deleting index '{}'", index); + } + }); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/impl/RabbitMqManagementClientTemplate.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/impl/RabbitMqManagementClientTemplate.java index 4ff216f06c..0ffbf0264b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/impl/RabbitMqManagementClientTemplate.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/impl/RabbitMqManagementClientTemplate.java @@ -22,8 +22,7 @@ import com.epam.ta.reportportal.core.analyzer.auto.client.RabbitMqManagementClient; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.fasterxml.jackson.core.JsonProcessingException; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.rabbitmq.http.client.Client; import com.rabbitmq.http.client.domain.ExchangeInfo; import java.util.List; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerServiceImpl.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerServiceImpl.java index 48e3aa4577..82a1890041 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerServiceImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerServiceImpl.java @@ -35,13 +35,13 @@ import com.epam.ta.reportportal.entity.item.issue.IssueEntity; import com.epam.ta.reportportal.entity.item.issue.IssueType; import com.epam.ta.reportportal.entity.launch.Launch; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.analyzer.AnalyzedItemRs; +import com.epam.ta.reportportal.model.analyzer.RelevantItemInfo; import com.epam.ta.reportportal.ws.converter.builders.IssueEntityBuilder; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; -import com.epam.ta.reportportal.ws.model.analyzer.AnalyzedItemRs; import com.epam.ta.reportportal.ws.model.analyzer.IndexLaunch; -import com.epam.ta.reportportal.ws.model.analyzer.RelevantItemInfo; import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import java.util.List; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerUtils.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerUtils.java index a3d048e25b..88cfaa150d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerUtils.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerUtils.java @@ -31,11 +31,11 @@ import com.epam.ta.reportportal.entity.log.LogFull; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectUtils; +import com.epam.ta.reportportal.model.analyzer.RelevantItemInfo; +import com.epam.ta.reportportal.model.project.UniqueErrorConfig; import com.epam.ta.reportportal.ws.model.analyzer.IndexLog; import com.epam.ta.reportportal.ws.model.analyzer.IndexTestItem; -import com.epam.ta.reportportal.ws.model.analyzer.RelevantItemInfo; import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; -import com.epam.ta.reportportal.ws.model.project.UniqueErrorConfig; import java.util.List; import java.util.Map; import java.util.Set; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/LogIndexerService.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/LogIndexerService.java index 429225b290..c48abaf808 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/LogIndexerService.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/LogIndexerService.java @@ -26,9 +26,9 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; import com.epam.ta.reportportal.ws.model.analyzer.IndexLaunch; import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Collection; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SearchLogServiceImpl.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SearchLogServiceImpl.java index 997f3f709c..ecbefb1bf8 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SearchLogServiceImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SearchLogServiceImpl.java @@ -42,14 +42,14 @@ import com.epam.ta.reportportal.entity.log.LogFull; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.analyzer.SearchRq; +import com.epam.ta.reportportal.model.analyzer.SearchRs; +import com.epam.ta.reportportal.model.log.SearchLogRq; +import com.epam.ta.reportportal.model.log.SearchLogRs; import com.epam.ta.reportportal.ws.converter.converters.IssueConverter; import com.epam.ta.reportportal.ws.converter.converters.TestItemConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.analyzer.SearchRq; -import com.epam.ta.reportportal.ws.model.analyzer.SearchRs; -import com.epam.ta.reportportal.ws.model.log.SearchLogRq; -import com.epam.ta.reportportal.ws.model.log.SearchLogRs; import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.time.temporal.ChronoUnit; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SuggestItemService.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SuggestItemService.java index 5547e2e220..5c57ab063b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SuggestItemService.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SuggestItemService.java @@ -17,7 +17,7 @@ import static com.epam.ta.reportportal.core.analyzer.auto.impl.AnalyzerUtils.getAnalyzerConfig; import static com.epam.ta.reportportal.entity.enums.LogLevel.ERROR_INT; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.core.analyzer.auto.client.AnalyzerServiceClient; @@ -37,8 +37,8 @@ import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.converter.converters.LogConverter; import com.epam.ta.reportportal.ws.converter.converters.TestItemConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.Collections; import java.util.List; import java.util.Objects; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SuggestedItem.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SuggestedItem.java index 5d956d6055..1d32af2d29 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SuggestedItem.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SuggestedItem.java @@ -13,11 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.analyzer.auto.impl; import com.epam.ta.reportportal.core.analyzer.auto.client.model.SuggestInfo; -import com.epam.ta.reportportal.ws.model.TestItemResource; -import com.epam.ta.reportportal.ws.model.log.LogResource; +import com.epam.ta.reportportal.model.log.LogResource; +import com.epam.ta.reportportal.ws.reporting.TestItemResource; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.Set; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/preparer/LaunchPreparerServiceImpl.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/preparer/LaunchPreparerServiceImpl.java index 665aa65692..e44c1e85f0 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/preparer/LaunchPreparerServiceImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/impl/preparer/LaunchPreparerServiceImpl.java @@ -24,10 +24,10 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; import com.epam.ta.reportportal.ws.model.analyzer.IndexLaunch; import com.epam.ta.reportportal.ws.model.analyzer.IndexTestItem; import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.time.LocalDateTime; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/indexer/BatchLogIndexer.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/indexer/BatchLogIndexer.java index 7a98614b1d..606b69f7d8 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/indexer/BatchLogIndexer.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/indexer/BatchLogIndexer.java @@ -99,7 +99,7 @@ private Long indexPartition(List itemIds, AnalyzerConfig analyzerConfig, L private Long countLogs(List indexLaunch) { return indexLaunch.stream() .flatMap(launch -> launch.getTestItems().stream()) - .mapToLong(item -> item.getLogs().size()) + .mapToLong(item -> item.getLogs() != null ? item.getLogs().size() : 0) .sum(); } diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/starter/decorator/ExistingAnalyzerStarter.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/starter/decorator/ExistingAnalyzerStarter.java index 0e9cdd30ee..ed32aa75ca 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/starter/decorator/ExistingAnalyzerStarter.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/starter/decorator/ExistingAnalyzerStarter.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.core.analyzer.auto.AnalyzerService; import com.epam.ta.reportportal.core.analyzer.auto.starter.LaunchAutoAnalysisStarter; import com.epam.ta.reportportal.core.analyzer.config.StartLaunchAutoAnalysisConfig; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.function.Predicate; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/strategy/analyze/AnalyzeItemsMode.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/strategy/analyze/AnalyzeItemsMode.java index 5f4897cdf1..717e5cba11 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/strategy/analyze/AnalyzeItemsMode.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/strategy/analyze/AnalyzeItemsMode.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.analyzer.auto.strategy.analyze; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Arrays; import java.util.stream.Collectors; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/strategy/search/FilterCollector.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/strategy/search/FilterCollector.java index f4dee7b67a..7c58409650 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/strategy/search/FilterCollector.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/auto/strategy/search/FilterCollector.java @@ -30,7 +30,7 @@ import com.epam.ta.reportportal.entity.filter.UserFilter; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Lists; import java.util.List; import java.util.stream.Collectors; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/config/AnalyzerType.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/config/AnalyzerType.java index a1894293c7..493f8018a6 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/config/AnalyzerType.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/config/AnalyzerType.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.analyzer.config; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Arrays; import java.util.stream.Collectors; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/handler/impl/ItemsPatternAnalyzerImpl.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/handler/impl/ItemsPatternAnalyzerImpl.java index 7f8b78d5ef..85834b9c9d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/handler/impl/ItemsPatternAnalyzerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/handler/impl/ItemsPatternAnalyzerImpl.java @@ -24,8 +24,8 @@ import com.epam.ta.reportportal.entity.pattern.PatternTemplate; import com.epam.ta.reportportal.entity.pattern.PatternTemplateTestItemPojo; import com.epam.ta.reportportal.entity.pattern.PatternTemplateType; +import com.epam.ta.reportportal.model.activity.PatternTemplateActivityResource; import com.epam.ta.reportportal.ws.converter.converters.PatternTemplateConverter; -import com.epam.ta.reportportal.ws.model.activity.PatternTemplateActivityResource; import java.util.List; import java.util.Map; import java.util.Optional; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/CreatePatternTemplateHandler.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/CreatePatternTemplateHandler.java index 340e80c187..915fc8e90a 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/CreatePatternTemplateHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/CreatePatternTemplateHandler.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.analyzer.pattern.service; import com.epam.ta.reportportal.entity.pattern.PatternTemplate; -import com.epam.ta.reportportal.ws.model.project.config.pattern.CreatePatternTemplateRQ; +import com.epam.ta.reportportal.model.project.config.pattern.CreatePatternTemplateRQ; /** * @author Ivan Budayeu diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/impl/CreatePatternTemplateHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/impl/CreatePatternTemplateHandlerImpl.java index ccac8df33b..3ed1fbe542 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/impl/CreatePatternTemplateHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/impl/CreatePatternTemplateHandlerImpl.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.analyzer.pattern.service.impl; import static com.epam.ta.reportportal.commons.Predicates.equalTo; @@ -21,9 +22,9 @@ import com.epam.ta.reportportal.core.analyzer.pattern.service.CreatePatternTemplateHandler; import com.epam.ta.reportportal.dao.PatternTemplateRepository; import com.epam.ta.reportportal.entity.pattern.PatternTemplate; +import com.epam.ta.reportportal.model.project.config.pattern.CreatePatternTemplateRQ; import com.epam.ta.reportportal.ws.converter.builders.PatternTemplateBuilder; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.project.config.pattern.CreatePatternTemplateRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -44,14 +45,12 @@ public PatternTemplate createPatternTemplate(Long projectId, CreatePatternTemplateRQ createPatternTemplateRQ) { final String name = StringUtils.trim(createPatternTemplateRQ.getName()); BusinessRule.expect( - patternTemplateRepository.existsByProjectIdAndNameIgnoreCase(projectId, name), - equalTo(false)) - .verify(ErrorType.RESOURCE_ALREADY_EXISTS, name); - PatternTemplate patternTemplate = new PatternTemplateBuilder().withCreateRequest( - createPatternTemplateRQ) - .withName(name) - .withProjectId(projectId) - .get(); + patternTemplateRepository.existsByProjectIdAndNameIgnoreCase(projectId, name), + equalTo(false) + ).verify(ErrorType.RESOURCE_ALREADY_EXISTS, name); + PatternTemplate patternTemplate = + new PatternTemplateBuilder().withCreateRequest(createPatternTemplateRQ).withName(name) + .withProjectId(projectId).get(); return patternTemplateRepository.save(patternTemplate); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/impl/CreateRegexPatternTemplateHandler.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/impl/CreateRegexPatternTemplateHandler.java index 6474044932..1f8320af42 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/impl/CreateRegexPatternTemplateHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/impl/CreateRegexPatternTemplateHandler.java @@ -20,8 +20,8 @@ import com.epam.ta.reportportal.dao.PatternTemplateRepository; import com.epam.ta.reportportal.entity.pattern.PatternTemplate; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.project.config.pattern.CreatePatternTemplateRQ; +import com.epam.ta.reportportal.model.project.config.pattern.CreatePatternTemplateRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import javax.persistence.PersistenceException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -45,7 +45,8 @@ public PatternTemplate createPatternTemplate(Long projectId, } catch (PersistenceException ex) { throw new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, Suppliers.formattedSupplier("Provided regex pattern - '{}' is invalid", - createPatternTemplateRQ.getValue()).get() + createPatternTemplateRQ.getValue() + ).get() ); } return super.createPatternTemplate(projectId, createPatternTemplateRQ); diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/impl/LaunchPatternAnalyzerImpl.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/impl/LaunchPatternAnalyzerImpl.java index c4bb9a1643..6ec0c5a307 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/impl/LaunchPatternAnalyzerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/pattern/service/impl/LaunchPatternAnalyzerImpl.java @@ -31,7 +31,7 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Collections; import java.util.List; import java.util.Set; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/AbstractLaunchAnalysisStrategy.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/AbstractLaunchAnalysisStrategy.java index 4a58a81262..572f83b20b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/AbstractLaunchAnalysisStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/AbstractLaunchAnalysisStrategy.java @@ -18,8 +18,8 @@ import static com.epam.ta.reportportal.commons.Predicates.equalTo; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; -import static com.epam.ta.reportportal.ws.model.ErrorType.FORBIDDEN_OPERATION; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FORBIDDEN_OPERATION; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.validation.Suppliers; diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchAnalysisStrategy.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchAnalysisStrategy.java index 38dec9a63a..5cd04f7dfe 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchAnalysisStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchAnalysisStrategy.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.analyzer.strategy; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.launch.AnalyzeLaunchRQ; +import com.epam.ta.reportportal.model.launch.AnalyzeLaunchRQ; /** * @author Ivan Budayeu diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchAutoAnalysisStrategy.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchAutoAnalysisStrategy.java index 55213d6bbc..b65596ac41 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchAutoAnalysisStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchAutoAnalysisStrategy.java @@ -17,9 +17,9 @@ package com.epam.ta.reportportal.core.analyzer.strategy; import static com.epam.ta.reportportal.core.analyzer.auto.impl.AnalyzerUtils.getAnalyzerConfig; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.core.analyzer.auto.starter.LaunchAutoAnalysisStarter; @@ -31,7 +31,7 @@ import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.launch.AnalyzeLaunchRQ; +import com.epam.ta.reportportal.model.launch.AnalyzeLaunchRQ; import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; import java.util.LinkedHashSet; import java.util.Set; @@ -49,8 +49,7 @@ public class LaunchAutoAnalysisStrategy extends AbstractLaunchAnalysisStrategy { @Autowired public LaunchAutoAnalysisStrategy(ProjectRepository projectRepository, - LaunchRepository launchRepository, - LaunchAutoAnalysisStarter manualAnalysisStarter) { + LaunchRepository launchRepository, LaunchAutoAnalysisStarter manualAnalysisStarter) { super(projectRepository, launchRepository); this.manualAnalysisStarter = manualAnalysisStarter; } @@ -71,27 +70,20 @@ public void analyze(AnalyzeLaunchRQ analyzeRQ, ReportPortalUser.ProjectDetails p .orElseThrow(() -> new ReportPortalException(LAUNCH_NOT_FOUND, analyzeRQ.getLaunchId())); validateLaunch(launch, projectDetails); - Project project = projectRepository.findById(projectDetails.getProjectId()) - .orElseThrow( - () -> new ReportPortalException(PROJECT_NOT_FOUND, projectDetails.getProjectId())); + Project project = projectRepository.findById(projectDetails.getProjectId()).orElseThrow( + () -> new ReportPortalException(PROJECT_NOT_FOUND, projectDetails.getProjectId())); AnalyzerConfig analyzerConfig = getAnalyzerConfig(project); analyzerConfig.setAnalyzerMode(analyzeMode.getValue()); - final StartLaunchAutoAnalysisConfig autoAnalysisConfig = StartLaunchAutoAnalysisConfig.of( - launch.getId(), - analyzerConfig, - analyzeItemsModes, - user - ); + final StartLaunchAutoAnalysisConfig autoAnalysisConfig = + StartLaunchAutoAnalysisConfig.of(launch.getId(), analyzerConfig, analyzeItemsModes, user); manualAnalysisStarter.start(autoAnalysisConfig); } private LinkedHashSet getAnalyzeItemsModes(AnalyzeLaunchRQ analyzeRQ) { - return analyzeRQ.getAnalyzeItemsModes() - .stream() - .map(AnalyzeItemsMode::fromString) + return analyzeRQ.getAnalyzeItemsModes().stream().map(AnalyzeItemsMode::fromString) .collect(Collectors.toCollection(LinkedHashSet::new)); } diff --git a/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchPatternAnalysisStrategy.java b/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchPatternAnalysisStrategy.java index 91ecb49023..0160c2706f 100644 --- a/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchPatternAnalysisStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchPatternAnalysisStrategy.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.analyzer.strategy; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_NOT_FOUND; import static java.util.stream.Collectors.toSet; import com.epam.ta.reportportal.commons.ReportPortalUser; @@ -27,8 +27,8 @@ import com.epam.ta.reportportal.dao.ProjectRepository; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.launch.AnalyzeLaunchRQ; +import com.epam.ta.reportportal.model.launch.AnalyzeLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -44,8 +44,7 @@ public class LaunchPatternAnalysisStrategy extends AbstractLaunchAnalysisStrateg @Autowired public LaunchPatternAnalysisStrategy(ProjectRepository projectRepository, - LaunchRepository launchRepository, - LaunchPatternAnalyzer launchPatternAnalyzer) { + LaunchRepository launchRepository, LaunchPatternAnalyzer launchPatternAnalyzer) { super(projectRepository, launchRepository); this.launchPatternAnalyzer = launchPatternAnalyzer; } @@ -53,13 +52,13 @@ public LaunchPatternAnalysisStrategy(ProjectRepository projectRepository, public void analyze(AnalyzeLaunchRQ analyzeRQ, ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { - Set analyzeItemsModes = analyzeRQ.getAnalyzeItemsModes() - .stream() - .map(AnalyzeItemsMode::fromString) - .collect(toSet()); + Set analyzeItemsModes = + analyzeRQ.getAnalyzeItemsModes().stream().map(AnalyzeItemsMode::fromString) + .collect(toSet()); expect(analyzeItemsModes, CollectionUtils::isNotEmpty).verify(ErrorType.PATTERN_ANALYSIS_ERROR, - "No analyze item mode specified."); + "No analyze item mode specified." + ); Launch launch = launchRepository.findById(analyzeRQ.getLaunchId()) .orElseThrow(() -> new ReportPortalException(LAUNCH_NOT_FOUND, analyzeRQ.getLaunchId())); diff --git a/src/main/java/com/epam/ta/reportportal/core/bts/handler/impl/CreateTicketHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/bts/handler/impl/CreateTicketHandlerImpl.java index ac925d43f3..b16233c57e 100644 --- a/src/main/java/com/epam/ta/reportportal/core/bts/handler/impl/CreateTicketHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/bts/handler/impl/CreateTicketHandlerImpl.java @@ -19,8 +19,8 @@ import static com.epam.ta.reportportal.commons.Predicates.notNull; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.ws.converter.converters.TestItemConverter.TO_ACTIVITY_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; -import static com.epam.ta.reportportal.ws.model.ErrorType.UNABLE_POST_TICKET; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.UNABLE_POST_TICKET; import static java.util.Optional.ofNullable; import com.epam.reportportal.extension.bugtracking.BtsConstants; @@ -36,7 +36,7 @@ import com.epam.ta.reportportal.entity.integration.Integration; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; import com.epam.ta.reportportal.ws.model.externalsystem.PostTicketRQ; import com.epam.ta.reportportal.ws.model.externalsystem.Ticket; import java.util.Collections; @@ -61,8 +61,7 @@ public class CreateTicketHandlerImpl implements CreateTicketHandler { @Autowired public CreateTicketHandlerImpl(TestItemRepository testItemRepository, PluginBox pluginBox, - MessageBus messageBus, - GetIntegrationHandler getIntegrationHandler) { + MessageBus messageBus, GetIntegrationHandler getIntegrationHandler) { this.testItemRepository = testItemRepository; this.pluginBox = pluginBox; this.messageBus = messageBus; @@ -71,32 +70,28 @@ public CreateTicketHandlerImpl(TestItemRepository testItemRepository, PluginBox @Override public Ticket createIssue(PostTicketRQ postTicketRQ, Long integrationId, - ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user) { + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { validatePostTicketRQ(postTicketRQ); List testItems = ofNullable(postTicketRQ.getBackLinks()).map( - links -> testItemRepository.findAllById(links.keySet())) - .orElseGet(Collections::emptyList); - List before = testItems.stream() - .map(it -> TO_ACTIVITY_RESOURCE.apply(it, projectDetails.getProjectId())) - .collect(Collectors.toList()); + links -> testItemRepository.findAllById(links.keySet())).orElseGet(Collections::emptyList); + List before = + testItems.stream().map(it -> TO_ACTIVITY_RESOURCE.apply(it, projectDetails.getProjectId())) + .collect(Collectors.toList()); - Integration integration = getIntegrationHandler.getEnabledBtsIntegration(projectDetails, - integrationId); + Integration integration = + getIntegrationHandler.getEnabledBtsIntegration(projectDetails, integrationId); expect(BtsConstants.DEFECT_FORM_FIELDS.getParam(integration.getParams()), notNull()).verify( - BAD_REQUEST_ERROR, - "There aren't any submitted BTS fields!" - ); + BAD_REQUEST_ERROR, "There aren't any submitted BTS fields!"); - BtsExtension btsExtension = pluginBox.getInstance(integration.getType().getName(), - BtsExtension.class) - .orElseThrow(() -> new ReportPortalException(BAD_REQUEST_ERROR, - Suppliers.formattedSupplier("BugTracking plugin for {} isn't installed", - BtsConstants.PROJECT.getParam(integration.getParams()) - ).get() - )); + BtsExtension btsExtension = + pluginBox.getInstance(integration.getType().getName(), BtsExtension.class).orElseThrow( + () -> new ReportPortalException(BAD_REQUEST_ERROR, + Suppliers.formattedSupplier("BugTracking plugin for {} isn't installed", + BtsConstants.PROJECT.getParam(integration.getParams()) + ).get() + )); Ticket ticket = btsExtension.submitTicket(postTicketRQ, integration); @@ -112,7 +107,8 @@ public Ticket createIssue(PostTicketRQ postTicketRQ, Long integrationId, */ private void validatePostTicketRQ(PostTicketRQ postTicketRQ) { if (postTicketRQ.getIsIncludeLogs() || postTicketRQ.getIsIncludeScreenshots()) { - expect(postTicketRQ.getBackLinks(), notNull()).verify(UNABLE_POST_TICKET, + expect(postTicketRQ.getBackLinks(), notNull()).verify( + UNABLE_POST_TICKET, "Test item id should be specified, when logs required in ticket description." ); } diff --git a/src/main/java/com/epam/ta/reportportal/core/bts/handler/impl/GetBugTrackingSystemHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/bts/handler/impl/GetBugTrackingSystemHandlerImpl.java index 8557f75b7f..3caac7493d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/bts/handler/impl/GetBugTrackingSystemHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/bts/handler/impl/GetBugTrackingSystemHandlerImpl.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.dao.IntegrationRepository; import com.epam.ta.reportportal.entity.enums.IntegrationGroupEnum; import com.epam.ta.reportportal.entity.integration.Integration; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/core/bts/handler/impl/GetTicketHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/bts/handler/impl/GetTicketHandlerImpl.java index fa6ea54a0b..cd99ff241e 100644 --- a/src/main/java/com/epam/ta/reportportal/core/bts/handler/impl/GetTicketHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/bts/handler/impl/GetTicketHandlerImpl.java @@ -16,7 +16,8 @@ package com.epam.ta.reportportal.core.bts.handler.impl; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; + +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; import com.epam.reportportal.extension.bugtracking.BtsExtension; import com.epam.ta.reportportal.commons.ReportPortalUser; @@ -26,9 +27,9 @@ import com.epam.ta.reportportal.core.plugin.PluginBox; import com.epam.ta.reportportal.entity.integration.Integration; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; import com.epam.ta.reportportal.ws.model.externalsystem.PostFormField; import com.epam.ta.reportportal.ws.model.externalsystem.Ticket; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/core/configs/MvcConfig.java b/src/main/java/com/epam/ta/reportportal/core/configs/MvcConfig.java index 2d084bd336..15f1c18c83 100644 --- a/src/main/java/com/epam/ta/reportportal/core/configs/MvcConfig.java +++ b/src/main/java/com/epam/ta/reportportal/core/configs/MvcConfig.java @@ -45,6 +45,7 @@ import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.MediaType; +import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; @@ -120,6 +121,7 @@ public void addArgumentResolvers(List argumentRes @Override public void configureMessageConverters(List> converters) { converters.clear(); + converters.add(byteArrayConverter()); converters.add(jsonConverter()); converters.add(openMetricsTextStringConverter()); converters.add(stringConverter()); @@ -179,6 +181,11 @@ public StringHttpMessageConverter openMetricsTextStringConverter() { return converter; } + @Bean + public ByteArrayHttpMessageConverter byteArrayConverter() { + return new ByteArrayHttpMessageConverter(); + } + @Bean HttpMessageConverters httpMessageConverters() { return new HttpMessageConverters(converters); diff --git a/src/main/java/com/epam/ta/reportportal/core/configs/SpringDocConfiguration.java b/src/main/java/com/epam/ta/reportportal/core/configs/SpringDocConfiguration.java new file mode 100644 index 0000000000..99c1c6c98a --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/core/configs/SpringDocConfiguration.java @@ -0,0 +1,237 @@ +/* + * Copyright 2024 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.core.configs; + +import static com.epam.ta.reportportal.commons.querygen.constant.ProjectCriteriaConstant.CRITERIA_PROJECT_ATTRIBUTE_NAME; + +import com.epam.ta.reportportal.commons.ReportPortalUser; +import com.epam.ta.reportportal.commons.querygen.CriteriaHolder; +import com.epam.ta.reportportal.commons.querygen.Filter; +import com.epam.ta.reportportal.commons.querygen.FilterTarget; +import com.epam.ta.reportportal.commons.querygen.Queryable; +import com.epam.ta.reportportal.core.statistics.StatisticsHelper; +import com.epam.ta.reportportal.entity.item.TestItem; +import com.epam.ta.reportportal.entity.launch.Launch; +import com.epam.ta.reportportal.entity.user.UserRole; +import com.epam.ta.reportportal.util.SchemaFactory; +import com.epam.ta.reportportal.ws.resolver.FilterFor; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.info.Contact; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.info.License; +import io.swagger.v3.oas.models.media.IntegerSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.security.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.servers.Server; +import io.swagger.v3.oas.models.tags.Tag; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.stream.Collectors; +import javax.servlet.ServletContext; +import org.springdoc.core.SpringDocUtils; +import org.springdoc.core.customizers.OpenApiCustomiser; +import org.springdoc.core.customizers.OperationCustomizer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.MethodParameter; +import org.springframework.data.domain.Pageable; +import org.springframework.security.core.annotation.AuthenticationPrincipal; + +/** + * @author Andrei Piankouski + */ +@Configuration +@ComponentScan(basePackages = "com.epam.ta.reportportal.ws.controller") +public class SpringDocConfiguration { + + static { + SpringDocUtils.getConfig().addAnnotationsToIgnore(AuthenticationPrincipal.class); + SpringDocUtils.getConfig().addRequestWrapperToIgnore(Pageable.class, Queryable.class, + ReportPortalUser.class, UserRole.class); + SpringDocUtils.getConfig().replaceWithClass(Iterable.class, List.class); + } + + private static final Set hiddenParams = ImmutableSet.builder() + .add(CRITERIA_PROJECT_ATTRIBUTE_NAME).build(); + + @Autowired + private ServletContext servletContext; + + @Value("${spring.application.name}") + private String applicationName; + + @Value("${info.build.version}") + private String buildVersion; + + @Bean + public OpenAPI openAPI() { + final String securitySchemeName = "bearerAuth"; + return new OpenAPI() + .info(new Info().title("Report Portal") + .description("Report Portal API documentation") + .version(buildVersion) + .contact(new Contact() + .name("Support") + .email("support@reportportal.io") + ) + .license(new License().name("Apache 2.0") + .url("http://www.apache.org/licenses/LICENSE-2.0"))) + .addSecurityItem(new SecurityRequirement().addList(securitySchemeName)) + .components( + new Components() + .addSecuritySchemes(securitySchemeName, + new SecurityScheme() + .name(securitySchemeName) + .type(SecurityScheme.Type.HTTP) + .scheme("bearer") + .bearerFormat("JWT") + ) + ) + .addServersItem(new Server().url("/" + applicationName)); + } + + @Bean + public OpenApiCustomiser sortSchemasAlphabetically() { + return openApi -> { + Map schemas = openApi.getComponents().getSchemas(); + openApi.getComponents().setSchemas(new TreeMap<>(schemas)); + }; + } + + @Bean + public OpenApiCustomiser sortTagsAlphabetically() { + return openApi -> { + List sortedTags = openApi.getTags().stream() + .sorted(Comparator.comparing(Tag::getName)) + .collect(Collectors.toList()); + openApi.setTags(sortedTags); + }; + } + + @Bean + public OperationCustomizer apiSummaryCustomizer() { + return (operation, handlerMethod) -> { + if (operation.getSummary() == null || operation.getSummary().isEmpty()) { + String methodName = handlerMethod.getMethod().getName(); + String summary = convertMethodNameToTitle(methodName); + operation.setSummary(summary); + } + return operation; + }; + } + + private String convertMethodNameToTitle(String methodName) { + StringBuilder title = new StringBuilder(methodName.replaceAll("([A-Z])", " $1")); + return title.substring(0, 1).toUpperCase(Locale.ROOT) + title.substring(1).trim(); + } + + @Bean + public OperationCustomizer customizeParameters() { + return (operation, handlerMethod) -> { + for (MethodParameter parameter : handlerMethod.getMethodParameters()) { + Class parameterType = parameter.getParameterType(); + + if (parameterType == Filter.class) { + FilterFor filterClass = parameter.getParameterAnnotation(FilterFor.class); + + List defaultParams = Lists.newArrayList(); + if (filterClass != null && (filterClass.value() == TestItem.class + || filterClass.value() == Launch.class)) { + defaultParams = StatisticsHelper.defaultStatisticsFields() + .map(this::buildFilterParameters) + .collect(Collectors.toList()); + } + + List criteriaList = FilterTarget.findByClass(filterClass.value()) + .getCriteriaHolders(); + Set filterParams = criteriaList.stream() + .filter(ch -> !hiddenParams.contains(ch.getFilterCriteria())) + .map(this::buildFilterParameters) + .collect(Collectors.toSet()); + filterParams.addAll(defaultParams); + setParameters(operation, filterParams); + } else if (parameterType == Pageable.class) { + setParameters(operation, buildPageParameters()); + } + } + return operation; + }; + } + + private Parameter buildFilterParameters(String parameter) { + return new Parameter() + .in(ParameterIn.QUERY.toString()) + .name("filter.eq." + parameter) + .schema(new IntegerSchema()) + .description("Filters by '" + parameter + "'"); + } + + private Parameter buildFilterParameters(CriteriaHolder criteriaHolder) { + Schema schema = SchemaFactory.createSchemaForType(criteriaHolder.getDataType()); + + return new Parameter() + .in(ParameterIn.QUERY.toString()) + .name("filter.eq." + criteriaHolder.getFilterCriteria()) + .schema(schema) + .description("Filters by '" + criteriaHolder.getFilterCriteria() + "'"); + } + + private List buildPageParameters() { + List pageParams = new ArrayList<>(); + pageParams.add(new Parameter() + .in(ParameterIn.QUERY.toString()) + .name("page.page") + .schema(new IntegerSchema()) + .description("Results page you want to retrieve (0..N)")); + pageParams.add(new Parameter() + .in(ParameterIn.QUERY.toString()) + .name("page.size") + .schema(new IntegerSchema()) + .description("Number of records per page")); + pageParams.add(new Parameter() + .in(ParameterIn.QUERY.toString()) + .name("page.sort") + .schema(new StringSchema()) + .description("Sorting criteria in the format: property, (asc|desc). " + + "Default sort order is ascending. " + + "Multiple sort criteria are supported.")); + return pageParams; + } + + private void setParameters(Operation operation, Collection parameters) { + for (Parameter parameter : parameters) { + operation.addParametersItem(parameter); + } + } +} diff --git a/src/main/java/com/epam/ta/reportportal/core/configs/Swagger2Configuration.java b/src/main/java/com/epam/ta/reportportal/core/configs/Swagger2Configuration.java deleted file mode 100644 index 82271717dc..0000000000 --- a/src/main/java/com/epam/ta/reportportal/core/configs/Swagger2Configuration.java +++ /dev/null @@ -1,304 +0,0 @@ -/* - * Copyright 2019 EPAM Systems - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.core.configs; - -import static com.epam.ta.reportportal.commons.querygen.constant.ProjectCriteriaConstant.CRITERIA_PROJECT_ATTRIBUTE_NAME; -import static com.google.common.base.Predicates.not; -import static com.google.common.base.Predicates.or; -import static com.google.common.collect.Lists.newArrayList; -import static springfox.documentation.builders.RequestHandlerSelectors.basePackage; -import static springfox.documentation.spi.schema.contexts.ModelContext.inputParam; - -import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.commons.querygen.CriteriaHolder; -import com.epam.ta.reportportal.commons.querygen.Filter; -import com.epam.ta.reportportal.commons.querygen.FilterTarget; -import com.epam.ta.reportportal.commons.querygen.Queryable; -import com.epam.ta.reportportal.core.statistics.StatisticsHelper; -import com.epam.ta.reportportal.entity.item.TestItem; -import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.entity.user.UserRole; -import com.epam.ta.reportportal.ws.resolver.FilterFor; -import com.fasterxml.classmate.ResolvedType; -import com.fasterxml.classmate.TypeResolver; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import java.sql.Timestamp; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; -import javax.servlet.ServletContext; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Conditional; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Component; -import springfox.documentation.PathProvider; -import springfox.documentation.builders.ParameterBuilder; -import springfox.documentation.schema.ModelReference; -import springfox.documentation.schema.ResolvedTypes; -import springfox.documentation.schema.TypeNameExtractor; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.service.Contact; -import springfox.documentation.service.Parameter; -import springfox.documentation.service.ResolvedMethodParameter; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spi.schema.contexts.ModelContext; -import springfox.documentation.spi.service.OperationBuilderPlugin; -import springfox.documentation.spi.service.contexts.OperationContext; -import springfox.documentation.spi.service.contexts.ParameterContext; -import springfox.documentation.spring.web.paths.RelativePathProvider; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger.web.UiConfiguration; -import springfox.documentation.swagger.web.UiConfigurationBuilder; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -/** - * SWAGGER 2.0 UI page configuration for Report Portal application - * - * @author dzmitry_kavalets - * @author Andrei_Ramanchuk - * @author Andrei Varabyeu - */ -@Configuration -@Conditional(Conditions.NotTestCondition.class) -@EnableSwagger2 -@ComponentScan(basePackages = "com.epam.ta.reportportal.ws.controller") -public class Swagger2Configuration { - - private static final Set hiddenParams = ImmutableSet.builder() - .add(CRITERIA_PROJECT_ATTRIBUTE_NAME).build(); - - @Autowired - private ServletContext servletContext; - - @Value("${spring.application.name}") - private String applicationName; - - @Value("${info.build.version}") - private String buildVersion; - - @Bean - public Docket docket() { - /* For more information see default params at {@link ApiInfo} */ - ApiInfo rpInfo = new ApiInfo( - "Report Portal", - "Report Portal API documentation", - buildVersion, - null, - new Contact("Support", null, "Support Report Portal "), - "Apache 2.0", - "http://www.apache.org/licenses/LICENSE-2.0", - Collections.emptyList() - ); - - // @formatter:off - Docket rpDocket = new Docket(DocumentationType.SWAGGER_2) - .ignoredParameterTypes(ReportPortalUser.class, Filter.class, Queryable.class, - Pageable.class, UserRole.class) - .pathProvider(rpPathProvider()) - .useDefaultResponseMessages(false) - /* remove default endpoints from listing */ - .select().apis(not(or( - basePackage("org.springframework.boot"), - basePackage("org.springframework.cloud")))) - .build(); - //@formatter:on - - rpDocket.apiInfo(rpInfo); - return rpDocket; - } - - @Bean - public PathProvider rpPathProvider() { - return new RelativePathProvider(servletContext) { - @Override - public String getApplicationBasePath() { - if (super.getApplicationBasePath().contains(applicationName)) { - return super.getApplicationBasePath(); - } - return "/" + applicationName + super.getApplicationBasePath(); - } - }; - } - - @Bean - OperationPageableParameterReader pageableParameterBuilderPlugin(TypeNameExtractor nameExtractor, - TypeResolver resolver) { - return new OperationPageableParameterReader(nameExtractor, resolver); - } - - @Bean - public UiConfiguration uiConfig() { - return UiConfigurationBuilder.builder().build(); - } - - @Component - public class OperationPageableParameterReader implements OperationBuilderPlugin { - - private final TypeNameExtractor nameExtractor; - private final TypeResolver resolver; - - private final ResolvedType pageableType; - private final ResolvedType filterType; - - @Autowired - public OperationPageableParameterReader(TypeNameExtractor nameExtractor, - TypeResolver resolver) { - this.nameExtractor = nameExtractor; - this.resolver = resolver; - this.pageableType = resolver.resolve(Pageable.class); - this.filterType = resolver.resolve(Filter.class); - } - - @Override - public void apply(OperationContext context) { - List methodParameters = context.getParameters(); - List parameters = newArrayList(); - - for (ResolvedMethodParameter methodParameter : methodParameters) { - ResolvedType resolvedType = methodParameter.getParameterType(); - ParameterContext parameterContext = new ParameterContext( - methodParameter, - new ParameterBuilder(), - context.getDocumentationContext(), - context.getGenericsNamingStrategy(), - context - ); - Function factory = createModelRefFactory( - parameterContext); - ModelReference stringModel = factory.apply(resolver.resolve(List.class, String.class)); - - if (pageableType.equals(resolvedType)) { - - ModelReference intModel = factory.apply(resolver.resolve(Integer.TYPE)); - - parameters.add(new ParameterBuilder().parameterType("query") - .name("page.page") - .modelRef(intModel) - .description("Results page you want to retrieve (0..N)") - .build()); - parameters.add(new ParameterBuilder().parameterType("query") - .name("page.size") - .modelRef(intModel) - .description("Number of records per page") - .build()); - parameters.add(new ParameterBuilder().parameterType("query") - .name("page.sort") - .modelRef(stringModel) - .allowMultiple(true) - .description("Sorting criteria in the format: property, (asc|desc). " - + "Default sort order is ascending. " - + "Multiple sort criteria are supported.") - .build()); - context.operationBuilder().parameters(parameters); - - } else if (filterType.equals(resolvedType)) { - FilterFor filterClass = methodParameter.findAnnotation(FilterFor.class).get(); - - List defaultParams = Lists.newArrayList(); - if (filterClass.value() == TestItem.class || filterClass.value() == Launch.class) { - defaultParams = StatisticsHelper.defaultStatisticsFields() - .map(it -> buildParameters(parameterContext, factory, it)) - .collect(Collectors.toList()); - } - - List criteriaList = FilterTarget.findByClass(filterClass.value()) - .getCriteriaHolders(); - List params = criteriaList.stream() - .filter(ch -> !hiddenParams.contains(ch.getFilterCriteria())) - .map(it -> buildParameters(parameterContext, factory, it)) - /* if type is not a collection and first letter is not capital (all known to swagger types start from lower case) */ - .filter(p -> !(null == p.getModelRef().getItemType() && Character.isUpperCase( - p.getModelRef() - .getType() - .toCharArray()[0]))) - .collect(Collectors.toList()); - - params.addAll(defaultParams); - context.operationBuilder().parameters(params); - } - } - } - - private Parameter buildParameters(ParameterContext parameterContext, - Function factory, - CriteriaHolder criteriaHolder) { - return parameterContext.parameterBuilder() - .parameterType("query") - .name("filter.eq." + criteriaHolder.getFilterCriteria()) - .allowMultiple(true) - .modelRef(factory.apply(resolver.resolve( - criteriaHolder.getDataType() == Timestamp.class ? Date.class - : criteriaHolder.getDataType()))) - .description("Filters by '" + criteriaHolder.getFilterCriteria() + "'") - .build(); - } - - private Parameter buildParameters(ParameterContext parameterContext, - Function factory, - String parameter) { - return parameterContext.parameterBuilder() - .parameterType("query") - .name("filter.eq." + parameter) - .allowMultiple(true) - .modelRef(factory.apply(resolver.resolve(Long.class))) - .description("Filters by '" + parameter + "'") - .build(); - } - - @Override - public boolean supports(DocumentationType delimiter) { - return true; - } - - private Function createModelRefFactory( - ParameterContext context) { - ModelContext modelContext = inputParam( - Docket.DEFAULT_GROUP_NAME, - context.resolvedMethodParameter().getParameterType().getErasedType(), - context.getDocumentationType(), - context.getAlternateTypeProvider(), - context.getGenericNamingStrategy(), - context.getIgnorableParameterTypes() - ); - return ResolvedTypes.modelRefFactory(modelContext, nameExtractor); - } - } - - @SuppressWarnings("unused") - private static class RPPathProvider extends RelativePathProvider { - - private String gatewayPath; - - RPPathProvider(ServletContext servletContext, String gatewayPath) { - super(servletContext); - this.gatewayPath = gatewayPath; - } - - @Override - protected String applicationPath() { - return "/" + gatewayPath + super.applicationPath(); - } - } -} diff --git a/src/main/java/com/epam/ta/reportportal/core/configs/rabbit/AnalyzerRabbitMqConfiguration.java b/src/main/java/com/epam/ta/reportportal/core/configs/rabbit/AnalyzerRabbitMqConfiguration.java index 89ba9e755e..bec5b510ce 100644 --- a/src/main/java/com/epam/ta/reportportal/core/configs/rabbit/AnalyzerRabbitMqConfiguration.java +++ b/src/main/java/com/epam/ta/reportportal/core/configs/rabbit/AnalyzerRabbitMqConfiguration.java @@ -20,7 +20,7 @@ import com.epam.ta.reportportal.core.analyzer.auto.client.impl.RabbitMqManagementClientTemplate; import com.epam.ta.reportportal.core.configs.Conditions; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.rabbitmq.http.client.Client; import java.net.URI; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; diff --git a/src/main/java/com/epam/ta/reportportal/core/configs/rabbit/RabbitMqConfiguration.java b/src/main/java/com/epam/ta/reportportal/core/configs/rabbit/RabbitMqConfiguration.java index c82aeb9509..4c24f4c214 100644 --- a/src/main/java/com/epam/ta/reportportal/core/configs/rabbit/RabbitMqConfiguration.java +++ b/src/main/java/com/epam/ta/reportportal/core/configs/rabbit/RabbitMqConfiguration.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.core.configs.Conditions; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.fasterxml.jackson.databind.ObjectMapper; import com.rabbitmq.http.client.Client; import java.net.URI; diff --git a/src/main/java/com/epam/ta/reportportal/core/configs/resource/ResourceAttributeHandlerConfig.java b/src/main/java/com/epam/ta/reportportal/core/configs/resource/ResourceAttributeHandlerConfig.java index 7361307741..ef1fed6cdf 100644 --- a/src/main/java/com/epam/ta/reportportal/core/configs/resource/ResourceAttributeHandlerConfig.java +++ b/src/main/java/com/epam/ta/reportportal/core/configs/resource/ResourceAttributeHandlerConfig.java @@ -28,7 +28,7 @@ import com.epam.ta.reportportal.ws.converter.resource.handler.attribute.matcher.PredicateItemAttributeTypeMatcher; import com.epam.ta.reportportal.ws.converter.resource.handler.attribute.resolver.ItemAttributeTypeResolver; import com.epam.ta.reportportal.ws.converter.resource.handler.attribute.resolver.ItemAttributeTypeResolverDelegate; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; import com.google.common.collect.ImmutableMap; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/dashboard/CreateDashboardHandler.java b/src/main/java/com/epam/ta/reportportal/core/dashboard/CreateDashboardHandler.java index 994d2ed7cf..508f680142 100644 --- a/src/main/java/com/epam/ta/reportportal/core/dashboard/CreateDashboardHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/dashboard/CreateDashboardHandler.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.core.dashboard; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.dashboard.CreateDashboardRQ; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.dashboard.CreateDashboardRQ; /** * @author Pavel Bortnik diff --git a/src/main/java/com/epam/ta/reportportal/core/dashboard/DeleteDashboardHandler.java b/src/main/java/com/epam/ta/reportportal/core/dashboard/DeleteDashboardHandler.java index 44a2ac46ed..b186045bce 100644 --- a/src/main/java/com/epam/ta/reportportal/core/dashboard/DeleteDashboardHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/dashboard/DeleteDashboardHandler.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.dashboard; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * @author Pavel Bortnik diff --git a/src/main/java/com/epam/ta/reportportal/core/dashboard/GetDashboardHandler.java b/src/main/java/com/epam/ta/reportportal/core/dashboard/GetDashboardHandler.java index 2b9f95f44d..793237548b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/dashboard/GetDashboardHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/dashboard/GetDashboardHandler.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Filter; -import com.epam.ta.reportportal.ws.model.dashboard.DashboardResource; +import com.epam.ta.reportportal.model.dashboard.DashboardResource; import org.springframework.data.domain.Pageable; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/dashboard/UpdateDashboardHandler.java b/src/main/java/com/epam/ta/reportportal/core/dashboard/UpdateDashboardHandler.java index 9fa2d7fcb8..d49ccc80ef 100644 --- a/src/main/java/com/epam/ta/reportportal/core/dashboard/UpdateDashboardHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/dashboard/UpdateDashboardHandler.java @@ -17,10 +17,9 @@ package com.epam.ta.reportportal.core.dashboard; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.commons.querygen.Filter; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.dashboard.AddWidgetRq; -import com.epam.ta.reportportal.ws.model.dashboard.UpdateDashboardRQ; +import com.epam.ta.reportportal.model.dashboard.AddWidgetRq; +import com.epam.ta.reportportal.model.dashboard.UpdateDashboardRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * @author Pavel Bortnik diff --git a/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/CreateDashboardHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/CreateDashboardHandlerImpl.java index 62960aa97c..368275fb74 100644 --- a/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/CreateDashboardHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/CreateDashboardHandlerImpl.java @@ -16,6 +16,8 @@ package com.epam.ta.reportportal.core.dashboard.impl; +import static com.epam.ta.reportportal.ws.converter.converters.DashboardConverter.TO_ACTIVITY_RESOURCE; + import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.commons.validation.Suppliers; @@ -24,52 +26,55 @@ import com.epam.ta.reportportal.core.events.activity.DashboardCreatedEvent; import com.epam.ta.reportportal.dao.DashboardRepository; import com.epam.ta.reportportal.entity.dashboard.Dashboard; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.dashboard.CreateDashboardRQ; import com.epam.ta.reportportal.ws.converter.builders.DashboardBuilder; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.dashboard.CreateDashboardRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.apache.commons.lang3.BooleanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import static com.epam.ta.reportportal.ws.converter.converters.DashboardConverter.TO_ACTIVITY_RESOURCE; - /** * @author Pavel Bortnik */ @Service public class CreateDashboardHandlerImpl implements CreateDashboardHandler { - private final DashboardRepository dashboardRepository; - private final MessageBus messageBus; + private final DashboardRepository dashboardRepository; + private final MessageBus messageBus; - private final static int DASHBOARD_LIMIT = 300; + private final static int DASHBOARD_LIMIT = 300; - @Autowired - public CreateDashboardHandlerImpl(DashboardRepository dashboardRepository, MessageBus messageBus) { - this.dashboardRepository = dashboardRepository; - this.messageBus = messageBus; - } + @Autowired + public CreateDashboardHandlerImpl(DashboardRepository dashboardRepository, + MessageBus messageBus) { + this.dashboardRepository = dashboardRepository; + this.messageBus = messageBus; + } - @Override - public EntryCreatedRS createDashboard(ReportPortalUser.ProjectDetails projectDetails, CreateDashboardRQ rq, ReportPortalUser user) { + @Override + public EntryCreatedRS createDashboard(ReportPortalUser.ProjectDetails projectDetails, + CreateDashboardRQ rq, ReportPortalUser user) { - BusinessRule.expect(dashboardRepository.findAllByProjectId(projectDetails.getProjectId()).size() >= DASHBOARD_LIMIT, - BooleanUtils::isFalse).verify(ErrorType.DASHBOARD_UPDATE_ERROR, Suppliers.formattedSupplier( - "The limit of {} dashboards has been reached. To create a new one you need to delete at least one created previously.", - DASHBOARD_LIMIT - )); - BusinessRule.expect(dashboardRepository.existsByNameAndOwnerAndProjectId(rq.getName(), - user.getUsername(), - projectDetails.getProjectId() - ), BooleanUtils::isFalse).verify(ErrorType.RESOURCE_ALREADY_EXISTS, rq.getName()); + BusinessRule.expect(dashboardRepository.findAllByProjectId(projectDetails.getProjectId()).size() + >= DASHBOARD_LIMIT, BooleanUtils::isFalse) + .verify(ErrorType.DASHBOARD_UPDATE_ERROR, Suppliers.formattedSupplier( + "The limit of {} dashboards has been reached. To create a new one you need to delete at least one created previously.", + DASHBOARD_LIMIT + )); + BusinessRule.expect( + dashboardRepository.existsByNameAndOwnerAndProjectId(rq.getName(), user.getUsername(), + projectDetails.getProjectId() + ), BooleanUtils::isFalse).verify(ErrorType.RESOURCE_ALREADY_EXISTS, rq.getName()); - Dashboard dashboard = new DashboardBuilder().addDashboardRq(rq) - .addProject(projectDetails.getProjectId()) - .addOwner(user.getUsername()) - .get(); - dashboardRepository.save(dashboard); - messageBus.publishActivity(new DashboardCreatedEvent(TO_ACTIVITY_RESOURCE.apply(dashboard), user.getUserId(), user.getUsername())); - return new EntryCreatedRS(dashboard.getId()); - } + Dashboard dashboard = + new DashboardBuilder().addDashboardRq(rq).addProject(projectDetails.getProjectId()) + .addOwner(user.getUsername()).get(); + dashboardRepository.save(dashboard); + messageBus.publishActivity( + new DashboardCreatedEvent(TO_ACTIVITY_RESOURCE.apply(dashboard), user.getUserId(), + user.getUsername() + )); + return new EntryCreatedRS(dashboard.getId()); + } } diff --git a/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/DeleteDashboardHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/DeleteDashboardHandlerImpl.java index f0a1ef557c..c3eca2be71 100644 --- a/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/DeleteDashboardHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/DeleteDashboardHandlerImpl.java @@ -16,6 +16,9 @@ package com.epam.ta.reportportal.core.dashboard.impl; +import static com.epam.ta.reportportal.ws.converter.converters.DashboardConverter.TO_ACTIVITY_RESOURCE; +import static java.util.stream.Collectors.toSet; + import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.core.dashboard.DeleteDashboardHandler; import com.epam.ta.reportportal.core.events.MessageBus; @@ -28,18 +31,14 @@ import com.epam.ta.reportportal.entity.dashboard.DashboardWidget; import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Service; - +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.List; import java.util.Set; import java.util.stream.Collectors; - -import static com.epam.ta.reportportal.ws.converter.converters.DashboardConverter.TO_ACTIVITY_RESOURCE; -import static java.util.stream.Collectors.toSet; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; /** * @author Pavel Bortnik diff --git a/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/GetDashboardHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/GetDashboardHandlerImpl.java index e51389181e..f088dc0d6c 100644 --- a/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/GetDashboardHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/GetDashboardHandlerImpl.java @@ -23,10 +23,10 @@ import com.epam.ta.reportportal.dao.DashboardRepository; import com.epam.ta.reportportal.entity.dashboard.Dashboard; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.dashboard.DashboardResource; import com.epam.ta.reportportal.ws.converter.PagedResourcesAssembler; import com.epam.ta.reportportal.ws.converter.converters.DashboardConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.dashboard.DashboardResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/UpdateDashboardHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/UpdateDashboardHandlerImpl.java index 2229472d22..a84e8b725f 100644 --- a/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/UpdateDashboardHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/dashboard/impl/UpdateDashboardHandlerImpl.java @@ -16,6 +16,8 @@ package com.epam.ta.reportportal.core.dashboard.impl; +import static com.epam.ta.reportportal.ws.converter.converters.DashboardConverter.TO_ACTIVITY_RESOURCE; + import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.commons.validation.Suppliers; @@ -31,13 +33,13 @@ import com.epam.ta.reportportal.entity.dashboard.DashboardWidget; import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.activity.DashboardActivityResource; +import com.epam.ta.reportportal.model.dashboard.AddWidgetRq; +import com.epam.ta.reportportal.model.dashboard.UpdateDashboardRQ; import com.epam.ta.reportportal.ws.converter.builders.DashboardBuilder; import com.epam.ta.reportportal.ws.converter.converters.WidgetConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.activity.DashboardActivityResource; -import com.epam.ta.reportportal.ws.model.dashboard.AddWidgetRq; -import com.epam.ta.reportportal.ws.model.dashboard.UpdateDashboardRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.BooleanUtils; @@ -46,8 +48,6 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; -import static com.epam.ta.reportportal.ws.converter.converters.DashboardConverter.TO_ACTIVITY_RESOURCE; - /** * @author Pavel Bortnik */ diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/AssignUserEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/AssignUserEvent.java index c262f722d0..c6db29515e 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/AssignUserEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/AssignUserEvent.java @@ -26,7 +26,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; +import com.epam.ta.reportportal.model.activity.UserActivityResource; public class AssignUserEvent extends AbstractEvent implements ActivityEvent { @@ -51,19 +51,13 @@ public void setUserActivityResource(UserActivityResource userActivityResource) { @Override public Activity toActivity() { - return new ActivityBuilder() - .addCreatedNow() - .addAction(EventAction.ASSIGN) - .addEventName(ASSIGN_USER.getValue()) - .addPriority(EventPriority.HIGH) - .addObjectId(userActivityResource.getId()) - .addObjectName(userActivityResource.getFullName()) - .addObjectType(EventObject.USER) - .addProjectId(userActivityResource.getDefaultProjectId()) + return new ActivityBuilder().addCreatedNow().addAction(EventAction.ASSIGN) + .addEventName(ASSIGN_USER.getValue()).addPriority(EventPriority.HIGH) + .addObjectId(userActivityResource.getId()).addObjectName(userActivityResource.getFullName()) + .addObjectType(EventObject.USER).addProjectId(userActivityResource.getDefaultProjectId()) .addSubjectId(isSystemEvent ? null : getUserId()) .addSubjectName(isSystemEvent ? RP_SUBJECT_NAME : getUserLogin()) - .addSubjectType(isSystemEvent ? EventSubject.APPLICATION : EventSubject.USER) - .get(); + .addSubjectType(isSystemEvent ? EventSubject.APPLICATION : EventSubject.USER).get(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/ChangeRoleEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/ChangeRoleEvent.java index 923f170a72..0b957a4391 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/ChangeRoleEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/ChangeRoleEvent.java @@ -25,7 +25,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; +import com.epam.ta.reportportal.model.activity.UserActivityResource; public class ChangeRoleEvent extends AbstractEvent implements ActivityEvent { @@ -54,20 +54,12 @@ public void setUserActivityResource(UserActivityResource userActivityResource) { @Override public Activity toActivity() { - return new ActivityBuilder() - .addCreatedNow() - .addAction(EventAction.CHANGE_ROLE) - .addEventName(CHANGE_ROLE.getValue()) - .addPriority(EventPriority.HIGH) - .addObjectId(userActivityResource.getId()) - .addObjectName(userActivityResource.getFullName()) - .addObjectType(EventObject.USER) - .addProjectId(userActivityResource.getDefaultProjectId()) - .addSubjectId(getUserId()) - .addSubjectName(getUserLogin()) - .addSubjectType(EventSubject.USER) - .addHistoryField("projectRole", oldRole, newRole) - .get(); + return new ActivityBuilder().addCreatedNow().addAction(EventAction.CHANGE_ROLE) + .addEventName(CHANGE_ROLE.getValue()).addPriority(EventPriority.HIGH) + .addObjectId(userActivityResource.getId()).addObjectName(userActivityResource.getFullName()) + .addObjectType(EventObject.USER).addProjectId(userActivityResource.getDefaultProjectId()) + .addSubjectId(getUserId()).addSubjectName(getUserLogin()).addSubjectType(EventSubject.USER) + .addHistoryField("projectRole", oldRole, newRole).get(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/DashboardCreatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/DashboardCreatedEvent.java index 6042e7027c..52627302ea 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/DashboardCreatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/DashboardCreatedEvent.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.DashboardActivityResource; +import com.epam.ta.reportportal.model.activity.DashboardActivityResource; /** * @author pavel_bortnik diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/DashboardDeletedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/DashboardDeletedEvent.java index 859200ce72..dd6bf8eef5 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/DashboardDeletedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/DashboardDeletedEvent.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.DashboardActivityResource; +import com.epam.ta.reportportal.model.activity.DashboardActivityResource; /** * @author pavel_bortnik diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/DashboardUpdatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/DashboardUpdatedEvent.java index 4a46ee66b6..d0ba5a8c32 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/DashboardUpdatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/DashboardUpdatedEvent.java @@ -26,7 +26,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.DashboardActivityResource; +import com.epam.ta.reportportal.model.activity.DashboardActivityResource; /** * @author Andrei Varabyeu diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/DefectTypeCreatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/DefectTypeCreatedEvent.java index be91c72767..2ceb54b366 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/DefectTypeCreatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/DefectTypeCreatedEvent.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.events.activity; import com.epam.ta.reportportal.builder.ActivityBuilder; @@ -23,7 +24,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.IssueTypeActivityResource; +import com.epam.ta.reportportal.model.activity.IssueTypeActivityResource; /** * @author Andrei Varabyeu @@ -61,18 +62,11 @@ public void setProjectId(Long projectId) { @Override public Activity toActivity() { - return new ActivityBuilder() - .addCreatedNow() - .addAction(EventAction.CREATE) - .addEventName(ActivityAction.CREATE_DEFECT.getValue()) - .addPriority(EventPriority.LOW) + return new ActivityBuilder().addCreatedNow().addAction(EventAction.CREATE) + .addEventName(ActivityAction.CREATE_DEFECT.getValue()).addPriority(EventPriority.LOW) .addObjectId(issueTypeActivityResource.getId()) .addObjectName(issueTypeActivityResource.getLongName()) - .addObjectType(EventObject.DEFECT_TYPE) - .addProjectId(projectId) - .addSubjectId(getUserId()) - .addSubjectName(getUserLogin()) - .addSubjectType(EventSubject.USER) - .get(); + .addObjectType(EventObject.DEFECT_TYPE).addProjectId(projectId).addSubjectId(getUserId()) + .addSubjectName(getUserLogin()).addSubjectType(EventSubject.USER).get(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/DefectTypeDeletedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/DefectTypeDeletedEvent.java index 519898cd01..9d49e4dc92 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/DefectTypeDeletedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/DefectTypeDeletedEvent.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.events.activity; import com.epam.ta.reportportal.builder.ActivityBuilder; @@ -23,13 +24,13 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.IssueTypeActivityResource; +import com.epam.ta.reportportal.model.activity.IssueTypeActivityResource; /** * @author Andrei Varabyeu */ -public class DefectTypeDeletedEvent extends BeforeEvent implements - ActivityEvent { +public class DefectTypeDeletedEvent extends BeforeEvent + implements ActivityEvent { private Long projectId; @@ -52,18 +53,10 @@ public void setProjectId(Long projectId) { @Override public Activity toActivity() { - return new ActivityBuilder() - .addCreatedNow() - .addAction(EventAction.DELETE) - .addEventName(ActivityAction.DELETE_DEFECT.getValue()) - .addPriority(EventPriority.MEDIUM) - .addObjectId(getBefore().getId()) - .addObjectName(getBefore().getLongName()) - .addObjectType(EventObject.DEFECT_TYPE) - .addProjectId(projectId) - .addSubjectId(getUserId()) - .addSubjectName(getUserLogin()) - .addSubjectType(EventSubject.USER) - .get(); + return new ActivityBuilder().addCreatedNow().addAction(EventAction.DELETE) + .addEventName(ActivityAction.DELETE_DEFECT.getValue()).addPriority(EventPriority.MEDIUM) + .addObjectId(getBefore().getId()).addObjectName(getBefore().getLongName()) + .addObjectType(EventObject.DEFECT_TYPE).addProjectId(projectId).addSubjectId(getUserId()) + .addSubjectName(getUserLogin()).addSubjectType(EventSubject.USER).get(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/DefectTypeUpdatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/DefectTypeUpdatedEvent.java index 86289b32f5..7f304014b3 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/DefectTypeUpdatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/DefectTypeUpdatedEvent.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.events.activity; import com.epam.ta.reportportal.builder.ActivityBuilder; @@ -23,7 +24,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.IssueTypeActivityResource; +import com.epam.ta.reportportal.model.activity.IssueTypeActivityResource; /** * @author Andrei Varabyeu @@ -61,18 +62,11 @@ public void setProjectId(Long projectId) { @Override public Activity toActivity() { - return new ActivityBuilder() - .addCreatedNow() - .addAction(EventAction.UPDATE) - .addEventName(ActivityAction.UPDATE_DEFECT.getValue()) - .addPriority(EventPriority.LOW) + return new ActivityBuilder().addCreatedNow().addAction(EventAction.UPDATE) + .addEventName(ActivityAction.UPDATE_DEFECT.getValue()).addPriority(EventPriority.LOW) .addObjectId(issueTypeActivityResource.getId()) .addObjectName(issueTypeActivityResource.getLongName()) - .addObjectType(EventObject.DEFECT_TYPE) - .addProjectId(projectId) - .addSubjectId(getUserId()) - .addSubjectName(getUserLogin()) - .addSubjectType(EventSubject.USER) - .get(); + .addObjectType(EventObject.DEFECT_TYPE).addProjectId(projectId).addSubjectId(getUserId()) + .addSubjectName(getUserLogin()).addSubjectType(EventSubject.USER).get(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/FilterCreatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/FilterCreatedEvent.java index 1e3e7963bf..193272f7f3 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/FilterCreatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/FilterCreatedEvent.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.UserFilterActivityResource; +import com.epam.ta.reportportal.model.activity.UserFilterActivityResource; /** * @author pavel_bortnik @@ -52,18 +52,11 @@ public void setUserFilterActivityResource(UserFilterActivityResource userFilterA @Override public Activity toActivity() { - return new ActivityBuilder() - .addCreatedNow() - .addAction(EventAction.CREATE) - .addEventName(ActivityAction.CREATE_FILTER.getValue()) - .addPriority(EventPriority.LOW) + return new ActivityBuilder().addCreatedNow().addAction(EventAction.CREATE) + .addEventName(ActivityAction.CREATE_FILTER.getValue()).addPriority(EventPriority.LOW) .addObjectId(userFilterActivityResource.getId()) - .addObjectName(userFilterActivityResource.getName()) - .addObjectType(EventObject.FILTER) - .addProjectId(userFilterActivityResource.getProjectId()) - .addSubjectId(getUserId()) - .addSubjectName(getUserLogin()) - .addSubjectType(EventSubject.USER) - .get(); + .addObjectName(userFilterActivityResource.getName()).addObjectType(EventObject.FILTER) + .addProjectId(userFilterActivityResource.getProjectId()).addSubjectId(getUserId()) + .addSubjectName(getUserLogin()).addSubjectType(EventSubject.USER).get(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/FilterDeletedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/FilterDeletedEvent.java index 38e644d15f..b3b3614460 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/FilterDeletedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/FilterDeletedEvent.java @@ -24,13 +24,13 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.UserFilterActivityResource; +import com.epam.ta.reportportal.model.activity.UserFilterActivityResource; /** * @author pavel_bortnik */ -public class FilterDeletedEvent extends BeforeEvent implements - ActivityEvent { +public class FilterDeletedEvent extends BeforeEvent + implements ActivityEvent { public FilterDeletedEvent() { } @@ -41,18 +41,11 @@ public FilterDeletedEvent(UserFilterActivityResource before, Long userId, String @Override public Activity toActivity() { - return new ActivityBuilder() - .addCreatedNow() - .addAction(EventAction.DELETE) - .addEventName(ActivityAction.DELETE_FILTER.getValue()) - .addPriority(EventPriority.LOW) - .addObjectId(getBefore().getId()) - .addObjectName(getBefore().getName()) - .addObjectType(EventObject.FILTER) - .addProjectId(getBefore().getProjectId()) - .addSubjectId(getUserId()) - .addSubjectName(getUserLogin()) - .addSubjectType(EventSubject.USER) + return new ActivityBuilder().addCreatedNow().addAction(EventAction.DELETE) + .addEventName(ActivityAction.DELETE_FILTER.getValue()).addPriority(EventPriority.LOW) + .addObjectId(getBefore().getId()).addObjectName(getBefore().getName()) + .addObjectType(EventObject.FILTER).addProjectId(getBefore().getProjectId()) + .addSubjectId(getUserId()).addSubjectName(getUserLogin()).addSubjectType(EventSubject.USER) .get(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/FilterUpdatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/FilterUpdatedEvent.java index 9b58cc01c5..83eeaadfe8 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/FilterUpdatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/FilterUpdatedEvent.java @@ -27,13 +27,13 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.UserFilterActivityResource; +import com.epam.ta.reportportal.model.activity.UserFilterActivityResource; /** * @author Pavel Bortnik */ -public class FilterUpdatedEvent extends AroundEvent implements - ActivityEvent { +public class FilterUpdatedEvent extends AroundEvent + implements ActivityEvent { public FilterUpdatedEvent() { } @@ -45,21 +45,12 @@ public FilterUpdatedEvent(UserFilterActivityResource before, UserFilterActivityR @Override public Activity toActivity() { - return new ActivityBuilder() - .addCreatedNow() - .addAction(EventAction.UPDATE) - .addEventName(ActivityAction.UPDATE_FILTER.getValue()) - .addPriority(EventPriority.LOW) - .addObjectId(getAfter().getId()) - .addObjectName(getAfter().getName()) - .addObjectType(EventObject.FILTER) - .addProjectId(getAfter().getProjectId()) - .addSubjectId(getUserId()) - .addSubjectName(getUserLogin()) - .addSubjectType(EventSubject.USER) - .addHistoryField(processName(getBefore().getName(), getAfter().getName())) - .addHistoryField( - processDescription(getBefore().getDescription(), getAfter().getDescription())) - .get(); + return new ActivityBuilder().addCreatedNow().addAction(EventAction.UPDATE) + .addEventName(ActivityAction.UPDATE_FILTER.getValue()).addPriority(EventPriority.LOW) + .addObjectId(getAfter().getId()).addObjectName(getAfter().getName()) + .addObjectType(EventObject.FILTER).addProjectId(getAfter().getProjectId()) + .addSubjectId(getUserId()).addSubjectName(getUserLogin()).addSubjectType(EventSubject.USER) + .addHistoryField(processName(getBefore().getName(), getAfter().getName())).addHistoryField( + processDescription(getBefore().getDescription(), getAfter().getDescription())).get(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/IntegrationCreatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/IntegrationCreatedEvent.java index c24c9f8fcb..60d8ec2a74 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/IntegrationCreatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/IntegrationCreatedEvent.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.IntegrationActivityResource; +import com.epam.ta.reportportal.model.activity.IntegrationActivityResource; import java.util.Optional; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/IntegrationDeletedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/IntegrationDeletedEvent.java index c44a0782af..e74e784d33 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/IntegrationDeletedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/IntegrationDeletedEvent.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.IntegrationActivityResource; +import com.epam.ta.reportportal.model.activity.IntegrationActivityResource; import java.util.Optional; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/IntegrationUpdatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/IntegrationUpdatedEvent.java index 37b2c4bf72..dd21e96b17 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/IntegrationUpdatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/IntegrationUpdatedEvent.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.IntegrationActivityResource; +import com.epam.ta.reportportal.model.activity.IntegrationActivityResource; import java.util.Optional; import org.apache.commons.lang3.StringUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/ItemIssueTypeDefinedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/ItemIssueTypeDefinedEvent.java index 0d270efe27..ed0f1c0505 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/ItemIssueTypeDefinedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/ItemIssueTypeDefinedEvent.java @@ -30,8 +30,8 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; -import com.epam.ta.reportportal.ws.model.analyzer.RelevantItemInfo; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.analyzer.RelevantItemInfo; import java.util.Optional; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/LaunchDeletedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/LaunchDeletedEvent.java index c9405dd887..721297aca4 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/LaunchDeletedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/LaunchDeletedEvent.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.LaunchActivityResource; +import com.epam.ta.reportportal.model.activity.LaunchActivityResource; /** * @author Andrei Varabyeu diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/LaunchStartedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/LaunchStartedEvent.java index 8e2875a6bd..8a0fb1cfe0 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/LaunchStartedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/LaunchStartedEvent.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.LaunchActivityResource; +import com.epam.ta.reportportal.model.activity.LaunchActivityResource; /** * @author Andrei Varabyeu diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/LinkTicketEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/LinkTicketEvent.java index 523feb06c3..faedefed2b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/LinkTicketEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/LinkTicketEvent.java @@ -25,7 +25,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; import com.google.common.base.Strings; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/NotificationsConfigUpdatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/NotificationsConfigUpdatedEvent.java index 4084376563..b39f592b2b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/NotificationsConfigUpdatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/NotificationsConfigUpdatedEvent.java @@ -30,9 +30,9 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.project.ProjectResource; -import com.epam.ta.reportportal.ws.model.project.email.ProjectNotificationConfigDTO; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.model.project.ProjectResource; +import com.epam.ta.reportportal.model.project.email.ProjectNotificationConfigDTO; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternCreatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternCreatedEvent.java index 4b4bbf664d..db45873ff8 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternCreatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternCreatedEvent.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.PatternTemplateActivityResource; +import com.epam.ta.reportportal.model.activity.PatternTemplateActivityResource; /** * @author Ivan Budayeu diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternDeletedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternDeletedEvent.java index e356482d7d..2c1b71e746 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternDeletedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternDeletedEvent.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.PatternTemplateActivityResource; +import com.epam.ta.reportportal.model.activity.PatternTemplateActivityResource; /** * @author Ivan Budayeu diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternMatchedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternMatchedEvent.java index 7b69c44512..560761d21c 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternMatchedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternMatchedEvent.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.PatternTemplateActivityResource; +import com.epam.ta.reportportal.model.activity.PatternTemplateActivityResource; import java.util.Optional; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternUpdatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternUpdatedEvent.java index 247302bff2..b77b1591eb 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternUpdatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/PatternUpdatedEvent.java @@ -28,7 +28,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.PatternTemplateActivityResource; +import com.epam.ta.reportportal.model.activity.PatternTemplateActivityResource; /** * @author Ivan Budayeu diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/PluginDeletedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/PluginDeletedEvent.java index 007dad31b7..42cd91e805 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/PluginDeletedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/PluginDeletedEvent.java @@ -8,7 +8,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.PluginActivityResource; +import com.epam.ta.reportportal.model.activity.PluginActivityResource; public class PluginDeletedEvent extends BeforeEvent implements ActivityEvent { diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/PluginUpdatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/PluginUpdatedEvent.java index 7409588a9e..f193604e3d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/PluginUpdatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/PluginUpdatedEvent.java @@ -12,7 +12,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.PluginActivityResource; +import com.epam.ta.reportportal.model.activity.PluginActivityResource; public class PluginUpdatedEvent extends AroundEvent implements ActivityEvent { diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/PluginUploadedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/PluginUploadedEvent.java index b50fa31d9a..4c3180be89 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/PluginUploadedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/PluginUploadedEvent.java @@ -8,7 +8,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.PluginActivityResource; +import com.epam.ta.reportportal.model.activity.PluginActivityResource; public class PluginUploadedEvent extends AbstractEvent implements ActivityEvent { @@ -17,7 +17,8 @@ public class PluginUploadedEvent extends AbstractEvent implements ActivityEvent public PluginUploadedEvent() { } - public PluginUploadedEvent(PluginActivityResource pluginActivityResource, Long userId, String userLogin) { + public PluginUploadedEvent(PluginActivityResource pluginActivityResource, Long userId, + String userLogin) { super(userId, userLogin); this.pluginActivityResource = pluginActivityResource; } @@ -33,9 +34,9 @@ public void setPluginActivityResource(PluginActivityResource pluginActivityResou @Override public Activity toActivity() { return new ActivityBuilder().addCreatedNow().addAction(EventAction.CREATE) - .addEventName(ActivityAction.CREATE_PLUGIN.getValue()).addObjectId(pluginActivityResource.getId()) - .addObjectName(pluginActivityResource.getName()).addObjectType(EventObject.PLUGIN) - .addSubjectId(getUserId()).addSubjectName(getUserLogin()).addSubjectType(EventSubject.USER) - .addPriority(EventPriority.CRITICAL).get(); + .addEventName(ActivityAction.CREATE_PLUGIN.getValue()) + .addObjectId(pluginActivityResource.getId()).addObjectName(pluginActivityResource.getName()) + .addObjectType(EventObject.PLUGIN).addSubjectId(getUserId()).addSubjectName(getUserLogin()) + .addSubjectType(EventSubject.USER).addPriority(EventPriority.CRITICAL).get(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/ProjectAnalyzerConfigEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/ProjectAnalyzerConfigEvent.java index 9fb9d8d0aa..8a7c0b91c3 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/ProjectAnalyzerConfigEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/ProjectAnalyzerConfigEvent.java @@ -16,7 +16,6 @@ package com.epam.ta.reportportal.core.events.activity; -import static com.epam.ta.reportportal.core.events.activity.util.ActivityDetailsUtil.configEquals; import static com.epam.ta.reportportal.core.events.activity.util.ActivityDetailsUtil.processParameter; import static com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum.ALL_MESSAGES_SHOULD_MATCH; import static com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum.AUTO_ANALYZER_ENABLED; @@ -24,7 +23,6 @@ import static com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum.AUTO_UNIQUE_ERROR_ANALYZER_ENABLED; import static com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum.MIN_SHOULD_MATCH; import static com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum.NUMBER_OF_LOG_LINES; -import static com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum.Prefix; import static com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum.SEARCH_LOGS_MIN_SHOULD_MATCH; import static com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum.UNIQUE_ERROR_ANALYZER_REMOVE_NUMBERS; @@ -36,22 +34,21 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.ProjectAttributesActivityResource; +import com.epam.ta.reportportal.model.activity.ProjectAttributesActivityResource; import java.util.Map; import java.util.stream.Stream; /** * @author Pavel Bortnik */ -public class ProjectAnalyzerConfigEvent extends - AroundEvent implements ActivityEvent { +public class ProjectAnalyzerConfigEvent extends AroundEvent + implements ActivityEvent { public ProjectAnalyzerConfigEvent() { } public ProjectAnalyzerConfigEvent(ProjectAttributesActivityResource before, - ProjectAttributesActivityResource after, Long userId, - String userLogin) { + ProjectAttributesActivityResource after, Long userId, String userLogin) { super(userId, userLogin, before, after); } @@ -63,27 +60,17 @@ public Activity toActivity() { final Map oldConfig = before.getConfig(); final Map newConfig = after.getConfig(); - final ActivityBuilder activityBuilder = new ActivityBuilder() - .addCreatedNow() - .addAction(EventAction.UPDATE) - .addEventName(ActivityAction.UPDATE_ANALYZER.getValue()) - .addPriority(EventPriority.LOW) - .addObjectId(before.getProjectId()) - .addObjectName("analyzer") - .addObjectType(EventObject.PROJECT) - .addProjectId(before.getProjectId()) - .addSubjectId(getUserId()) - .addSubjectName(getUserLogin()) - .addSubjectType(EventSubject.USER); + final ActivityBuilder activityBuilder = + new ActivityBuilder().addCreatedNow().addAction(EventAction.UPDATE) + .addEventName(ActivityAction.UPDATE_ANALYZER.getValue()).addPriority(EventPriority.LOW) + .addObjectId(before.getProjectId()).addObjectName("analyzer") + .addObjectType(EventObject.PROJECT).addProjectId(before.getProjectId()) + .addSubjectId(getUserId()).addSubjectName(getUserLogin()) + .addSubjectType(EventSubject.USER); - Stream.of(AUTO_ANALYZER_MODE, - MIN_SHOULD_MATCH, - SEARCH_LOGS_MIN_SHOULD_MATCH, - NUMBER_OF_LOG_LINES, - AUTO_ANALYZER_ENABLED, - AUTO_UNIQUE_ERROR_ANALYZER_ENABLED, - UNIQUE_ERROR_ANALYZER_REMOVE_NUMBERS, - ALL_MESSAGES_SHOULD_MATCH + Stream.of(AUTO_ANALYZER_MODE, MIN_SHOULD_MATCH, SEARCH_LOGS_MIN_SHOULD_MATCH, + NUMBER_OF_LOG_LINES, AUTO_ANALYZER_ENABLED, AUTO_UNIQUE_ERROR_ANALYZER_ENABLED, + UNIQUE_ERROR_ANALYZER_REMOVE_NUMBERS, ALL_MESSAGES_SHOULD_MATCH ).map(type -> processParameter(oldConfig, newConfig, type.getAttribute())) .forEach(activityBuilder::addHistoryField); diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/ProjectPatternAnalyzerUpdateEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/ProjectPatternAnalyzerUpdateEvent.java index f525f112e1..9e3b3fbad8 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/ProjectPatternAnalyzerUpdateEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/ProjectPatternAnalyzerUpdateEvent.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.events.activity; import static com.epam.ta.reportportal.core.events.activity.util.ActivityDetailsUtil.processParameter; @@ -26,22 +27,20 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.ProjectAttributesActivityResource; +import com.epam.ta.reportportal.model.activity.ProjectAttributesActivityResource; import java.util.Map; /** * @author Pavel Bortnik */ -public class ProjectPatternAnalyzerUpdateEvent extends - AroundEvent implements - ActivityEvent { +public class ProjectPatternAnalyzerUpdateEvent + extends AroundEvent implements ActivityEvent { public ProjectPatternAnalyzerUpdateEvent() { } public ProjectPatternAnalyzerUpdateEvent(ProjectAttributesActivityResource before, - ProjectAttributesActivityResource after, Long userId, - String userLogin) { + ProjectAttributesActivityResource after, Long userId, String userLogin) { super(userId, userLogin, before, after); } @@ -52,20 +51,14 @@ public Activity toActivity() { final Map oldConfig = before.getConfig(); final Map newConfig = after.getConfig(); - final ActivityBuilder activityBuilder = new ActivityBuilder() - .addCreatedNow() - .addAction(EventAction.UPDATE) - .addEventName(ActivityAction.UPDATE_PATTERN_ANALYZER.getValue()) - .addPriority(EventPriority.LOW) - .addObjectId(before.getProjectId()) - .addObjectName("pattern") - .addObjectType(EventObject.PROJECT) - .addProjectId(before.getProjectId()) - .addSubjectId(getUserId()) - .addSubjectName(getUserLogin()) - .addSubjectType(EventSubject.USER) - .addHistoryField( - processParameter(oldConfig, newConfig, AUTO_PATTERN_ANALYZER_ENABLED.getAttribute())); + final ActivityBuilder activityBuilder = + new ActivityBuilder().addCreatedNow().addAction(EventAction.UPDATE) + .addEventName(ActivityAction.UPDATE_PATTERN_ANALYZER.getValue()) + .addPriority(EventPriority.LOW).addObjectId(before.getProjectId()) + .addObjectName("pattern").addObjectType(EventObject.PROJECT) + .addProjectId(before.getProjectId()).addSubjectId(getUserId()) + .addSubjectName(getUserLogin()).addSubjectType(EventSubject.USER).addHistoryField( + processParameter(oldConfig, newConfig, AUTO_PATTERN_ANALYZER_ENABLED.getAttribute())); return activityBuilder.get(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/ProjectUpdatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/ProjectUpdatedEvent.java index c314131bc9..67162ac282 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/ProjectUpdatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/ProjectUpdatedEvent.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.events.activity; import static com.epam.ta.reportportal.core.events.activity.util.ActivityDetailsUtil.processParameter; @@ -29,49 +30,40 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.ProjectAttributesActivityResource; +import com.epam.ta.reportportal.model.activity.ProjectAttributesActivityResource; /** * Being triggered on after project update * * @author Andrei Varabyeu */ -public class ProjectUpdatedEvent extends AroundEvent implements - ActivityEvent { +public class ProjectUpdatedEvent extends AroundEvent + implements ActivityEvent { public ProjectUpdatedEvent() { } public ProjectUpdatedEvent(ProjectAttributesActivityResource before, - ProjectAttributesActivityResource after, Long userId, - String userLogin) { + ProjectAttributesActivityResource after, Long userId, String userLogin) { super(userId, userLogin, before, after); } @Override public Activity toActivity() { - return new ActivityBuilder().addCreatedNow() - .addAction(EventAction.UPDATE) - .addEventName(ActivityAction.UPDATE_PROJECT.getValue()) - .addPriority(EventPriority.HIGH) - .addObjectId(getBefore().getProjectId()) - .addObjectName(getBefore().getProjectName()) - .addObjectType(EventObject.PROJECT) - .addProjectId(getBefore().getProjectId()) - .addSubjectId(getUserId()) - .addSubjectName(getUserLogin()) - .addSubjectType(EventSubject.USER) - .addHistoryField(processParameter(getBefore().getConfig(), - getAfter().getConfig(), - INTERRUPT_JOB_TIME.getAttribute() - )) - .addHistoryField(processParameter(getBefore().getConfig(), getAfter().getConfig(), - KEEP_SCREENSHOTS.getAttribute())) - .addHistoryField(processParameter(getBefore().getConfig(), getAfter().getConfig(), - KEEP_LOGS.getAttribute())) - .addHistoryField(processParameter(getBefore().getConfig(), getAfter().getConfig(), - KEEP_LAUNCHES.getAttribute())) - .get(); + return new ActivityBuilder().addCreatedNow().addAction(EventAction.UPDATE) + .addEventName(ActivityAction.UPDATE_PROJECT.getValue()).addPriority(EventPriority.HIGH) + .addObjectId(getBefore().getProjectId()).addObjectName(getBefore().getProjectName()) + .addObjectType(EventObject.PROJECT).addProjectId(getBefore().getProjectId()) + .addSubjectId(getUserId()).addSubjectName(getUserLogin()).addSubjectType(EventSubject.USER) + .addHistoryField(processParameter(getBefore().getConfig(), getAfter().getConfig(), + INTERRUPT_JOB_TIME.getAttribute() + )).addHistoryField(processParameter(getBefore().getConfig(), getAfter().getConfig(), + KEEP_SCREENSHOTS.getAttribute() + )).addHistoryField(processParameter(getBefore().getConfig(), getAfter().getConfig(), + KEEP_LOGS.getAttribute() + )).addHistoryField(processParameter(getBefore().getConfig(), getAfter().getConfig(), + KEEP_LAUNCHES.getAttribute() + )).get(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/TicketPostedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/TicketPostedEvent.java index 06f6cc4b6b..08953bb08b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/TicketPostedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/TicketPostedEvent.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.events.activity; import static com.epam.ta.reportportal.core.events.activity.util.ActivityDetailsUtil.EMPTY_STRING; @@ -26,7 +27,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; import com.epam.ta.reportportal.ws.model.externalsystem.Ticket; import com.google.common.base.Strings; @@ -66,26 +67,18 @@ public void setTestItemActivityResource(TestItemActivityResource testItemActivit @Override public Activity toActivity() { - return new ActivityBuilder().addCreatedNow() - .addAction(EventAction.POST) - .addEventName(ActivityAction.POST_ISSUE.getValue()) - .addPriority(EventPriority.LOW) + return new ActivityBuilder().addCreatedNow().addAction(EventAction.POST) + .addEventName(ActivityAction.POST_ISSUE.getValue()).addPriority(EventPriority.LOW) .addObjectId(testItemActivityResource.getId()) - .addObjectName(testItemActivityResource.getName()) - .addObjectType(EventObject.ITEM_ISSUE) - .addProjectId(testItemActivityResource.getProjectId()) - .addSubjectId(getUserId()) - .addSubjectName(getUserLogin()) - .addSubjectType(EventSubject.USER) - .addHistoryField( - TICKET_ID, - Strings.isNullOrEmpty(testItemActivityResource.getTickets()) ? EMPTY_STRING - : testItemActivityResource.getTickets(), + .addObjectName(testItemActivityResource.getName()).addObjectType(EventObject.ITEM_ISSUE) + .addProjectId(testItemActivityResource.getProjectId()).addSubjectId(getUserId()) + .addSubjectName(getUserLogin()).addSubjectType(EventSubject.USER).addHistoryField( + TICKET_ID, Strings.isNullOrEmpty(testItemActivityResource.getTickets()) ? EMPTY_STRING : + testItemActivityResource.getTickets(), Strings.isNullOrEmpty(testItemActivityResource.getTickets()) ? ticket.getId() + ":" + ticket.getTicketUrl() : testItemActivityResource.getTickets() + "," + ticket.getId() + ":" + ticket.getTicketUrl() - ) - .get(); + ).get(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/UnassignUserEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/UnassignUserEvent.java index b323e36465..dedd684a71 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/UnassignUserEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/UnassignUserEvent.java @@ -26,7 +26,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; +import com.epam.ta.reportportal.model.activity.UserActivityResource; public class UnassignUserEvent extends AbstractEvent implements ActivityEvent { @@ -70,19 +70,13 @@ public void setSystemEvent(boolean systemEvent) { @Override public Activity toActivity() { - return new ActivityBuilder() - .addCreatedNow() - .addAction(EventAction.UNASSIGN) - .addEventName(UNASSIGN_USER.getValue()) - .addPriority(EventPriority.MEDIUM) - .addObjectId(userActivityResource.getId()) - .addObjectName(userActivityResource.getFullName()) - .addObjectType(EventObject.USER) - .addProjectId(userActivityResource.getDefaultProjectId()) + return new ActivityBuilder().addCreatedNow().addAction(EventAction.UNASSIGN) + .addEventName(UNASSIGN_USER.getValue()).addPriority(EventPriority.MEDIUM) + .addObjectId(userActivityResource.getId()).addObjectName(userActivityResource.getFullName()) + .addObjectType(EventObject.USER).addProjectId(userActivityResource.getDefaultProjectId()) .addSubjectId(isSystemEvent ? null : getUserId()) .addSubjectName(isSystemEvent ? RP_SUBJECT_NAME : getUserLogin()) - .addSubjectType(isSystemEvent ? EventSubject.APPLICATION : EventSubject.USER) - .get(); + .addSubjectType(isSystemEvent ? EventSubject.APPLICATION : EventSubject.USER).get(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/UserCreatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/UserCreatedEvent.java index 7576388859..801a630f14 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/UserCreatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/UserCreatedEvent.java @@ -25,7 +25,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; +import com.epam.ta.reportportal.model.activity.UserActivityResource; /** * @author Andrei Varabyeu diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/UserDeletedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/UserDeletedEvent.java index f0ae526e05..b644d85137 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/UserDeletedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/UserDeletedEvent.java @@ -8,7 +8,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; +import com.epam.ta.reportportal.model.activity.UserActivityResource; public class UserDeletedEvent extends BeforeEvent implements ActivityEvent { diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/UsersDeletedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/UsersDeletedEvent.java index ff9a106fd0..fb4427397c 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/UsersDeletedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/UsersDeletedEvent.java @@ -8,7 +8,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; +import com.epam.ta.reportportal.model.activity.UserActivityResource; public class UsersDeletedEvent extends BeforeEvent implements ActivityEvent { diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/WidgetCreatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/WidgetCreatedEvent.java index 8c3b515a80..eb3a59f0ba 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/WidgetCreatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/WidgetCreatedEvent.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.WidgetActivityResource; +import com.epam.ta.reportportal.model.activity.WidgetActivityResource; /** * @author pavel_bortnik @@ -52,18 +52,11 @@ public void setWidgetActivityResource(WidgetActivityResource widgetActivityResou @Override public Activity toActivity() { - return new ActivityBuilder() - .addCreatedNow() - .addAction(EventAction.CREATE) - .addEventName(ActivityAction.CREATE_WIDGET.getValue()) - .addPriority(EventPriority.LOW) - .addObjectId(widgetActivityResource.getId()) - .addObjectName(widgetActivityResource.getName()) - .addObjectType(EventObject.WIDGET) - .addProjectId(widgetActivityResource.getProjectId()) - .addSubjectId(getUserId()) - .addSubjectName(getUserLogin()) - .addSubjectType(EventSubject.USER) + return new ActivityBuilder().addCreatedNow().addAction(EventAction.CREATE) + .addEventName(ActivityAction.CREATE_WIDGET.getValue()).addPriority(EventPriority.LOW) + .addObjectId(widgetActivityResource.getId()).addObjectName(widgetActivityResource.getName()) + .addObjectType(EventObject.WIDGET).addProjectId(widgetActivityResource.getProjectId()) + .addSubjectId(getUserId()).addSubjectName(getUserLogin()).addSubjectType(EventSubject.USER) .get(); } diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/WidgetDeletedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/WidgetDeletedEvent.java index a9cd80baa4..3f564b8cc1 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/WidgetDeletedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/WidgetDeletedEvent.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.WidgetActivityResource; +import com.epam.ta.reportportal.model.activity.WidgetActivityResource; /** * @author pavel_bortnik diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/WidgetUpdatedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/WidgetUpdatedEvent.java index 80353e0bb9..f634b86e7f 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/WidgetUpdatedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/WidgetUpdatedEvent.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.events.activity; import static com.epam.ta.reportportal.core.events.activity.util.ActivityDetailsUtil.CONTENT_FIELDS; @@ -30,15 +31,16 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.WidgetActivityResource; +import com.epam.ta.reportportal.model.activity.WidgetActivityResource; import java.util.Optional; import java.util.Set; /** * @author Andrei Varabyeu */ -public class WidgetUpdatedEvent extends AroundEvent implements - ActivityEvent { + +public class WidgetUpdatedEvent extends AroundEvent + implements ActivityEvent { private String widgetOptionsBefore; private String widgetOptionsAfter; @@ -47,8 +49,7 @@ public WidgetUpdatedEvent() { } public WidgetUpdatedEvent(WidgetActivityResource before, WidgetActivityResource after, - String widgetOptionsBefore, - String widgetOptionsAfter, Long userId, String userLogin) { + String widgetOptionsBefore, String widgetOptionsAfter, Long userId, String userLogin) { super(userId, userLogin, before, after); this.widgetOptionsBefore = widgetOptionsBefore; this.widgetOptionsAfter = widgetOptionsAfter; @@ -72,19 +73,12 @@ public void setWidgetOptionsAfter(String widgetOptionsAfter) { @Override public Activity toActivity() { - return new ActivityBuilder().addCreatedNow() - .addAction(EventAction.UPDATE) - .addEventName(ActivityAction.UPDATE_WIDGET.getValue()) - .addPriority(EventPriority.LOW) - .addObjectId(getAfter().getId()) - .addObjectName(getAfter().getName()) - .addObjectType(EventObject.WIDGET) - .addProjectId(getAfter().getProjectId()) - .addSubjectId(getUserId()) - .addSubjectName(getUserLogin()) - .addSubjectType(EventSubject.USER) - .addHistoryField(processName(getBefore().getName(), getAfter().getName())) - .addHistoryField( + return new ActivityBuilder().addCreatedNow().addAction(EventAction.UPDATE) + .addEventName(ActivityAction.UPDATE_WIDGET.getValue()).addPriority(EventPriority.LOW) + .addObjectId(getAfter().getId()).addObjectName(getAfter().getName()) + .addObjectType(EventObject.WIDGET).addProjectId(getAfter().getProjectId()) + .addSubjectId(getUserId()).addSubjectName(getUserLogin()).addSubjectType(EventSubject.USER) + .addHistoryField(processName(getBefore().getName(), getAfter().getName())).addHistoryField( processDescription(getBefore().getDescription(), getAfter().getDescription())) .addHistoryField(processItemsCount(getBefore().getItemsCount(), getAfter().getItemsCount())) .addHistoryField( diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/item/TestItemStatusChangedEvent.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/item/TestItemStatusChangedEvent.java index 2a622b1295..e5c378bbd7 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/item/TestItemStatusChangedEvent.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/item/TestItemStatusChangedEvent.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; /** * @author Ihar Kahadouski diff --git a/src/main/java/com/epam/ta/reportportal/core/events/activity/util/IntegrationActivityPriorityResolver.java b/src/main/java/com/epam/ta/reportportal/core/events/activity/util/IntegrationActivityPriorityResolver.java index d37df54a70..8e01e8eef4 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/activity/util/IntegrationActivityPriorityResolver.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/activity/util/IntegrationActivityPriorityResolver.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.events.activity.util; import com.epam.ta.reportportal.entity.activity.EventPriority; -import com.epam.ta.reportportal.ws.model.activity.IntegrationActivityResource; +import com.epam.ta.reportportal.model.activity.IntegrationActivityResource; /** * @author Pavel Bortnik diff --git a/src/main/java/com/epam/ta/reportportal/core/events/annotations/WidgetLimitRange.java b/src/main/java/com/epam/ta/reportportal/core/events/annotations/WidgetLimitRange.java new file mode 100644 index 0000000000..d547f45436 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/core/events/annotations/WidgetLimitRange.java @@ -0,0 +1,21 @@ +package com.epam.ta.reportportal.core.events.annotations; + +import javax.validation.Constraint; +import java.lang.annotation.*; + +/** + * @author Pavel Bortnik + */ +@Documented +@Constraint(validatedBy = { WidgetLimitRangeValidator.class}) +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE, ElementType.PARAMETER }) +public @interface WidgetLimitRange { + String message() default "The provided limit is not allowed for the widget"; + + Class[] groups() default {}; + + Class[] payload() default {}; + + String[] allowedValues() default {}; +} diff --git a/src/main/java/com/epam/ta/reportportal/core/events/annotations/WidgetLimitRangeValidator.java b/src/main/java/com/epam/ta/reportportal/core/events/annotations/WidgetLimitRangeValidator.java new file mode 100644 index 0000000000..429961640c --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/core/events/annotations/WidgetLimitRangeValidator.java @@ -0,0 +1,41 @@ +package com.epam.ta.reportportal.core.events.annotations; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_WIDGET_LIMIT; +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_WIDGET_LIMIT; + +import com.epam.ta.reportportal.model.BaseEntityRQ; +import com.epam.ta.reportportal.model.widget.MaterializedWidgetType; +import com.epam.ta.reportportal.model.widget.WidgetRQ; +import java.util.Arrays; +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +/** + * @author Pavel Bortnik + */ +public class WidgetLimitRangeValidator + implements ConstraintValidator { + + @Override + public boolean isValid(BaseEntityRQ value, ConstraintValidatorContext context) { + if (value instanceof WidgetRQ) { + WidgetRQ widgetRQ = (WidgetRQ) value; + int limit = widgetRQ.getContentParameters().getItemsCount(); + if (Arrays.stream(MaterializedWidgetType.values()) + .anyMatch(it -> it.getType().equalsIgnoreCase(widgetRQ.getWidgetType()))) { + return limit >= MIN_WIDGET_LIMIT; + } + updateValidationMessage( + "Widget item limit size must be between " + MIN_WIDGET_LIMIT + " and " + MAX_WIDGET_LIMIT, + context + ); + return limit >= MIN_WIDGET_LIMIT && limit <= MAX_WIDGET_LIMIT; + } + return false; + } + + public void updateValidationMessage(String message, ConstraintValidatorContext context) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(message).addConstraintViolation(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/core/events/handler/AttachDefaultPhotoEventHandler.java b/src/main/java/com/epam/ta/reportportal/core/events/handler/AttachDefaultPhotoEventHandler.java index d771363a12..b9bfd0e0a2 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/handler/AttachDefaultPhotoEventHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/handler/AttachDefaultPhotoEventHandler.java @@ -58,8 +58,6 @@ public AttachDefaultPhotoEventHandler(UserRepository userRepository, public void handleContextRefresh(ContextRefreshedEvent event) { userRepository.findByLogin("superadmin") .ifPresent(it -> attachPhoto(it, "image/superAdminPhoto.jpg")); - userRepository.findByLogin("default") - .ifPresent(it -> attachPhoto(it, "image/defaultUserPhoto.jpg")); } private void attachPhoto(User user, String photoPath) { diff --git a/src/main/java/com/epam/ta/reportportal/core/events/handler/DefectTypeDeletedHandler.java b/src/main/java/com/epam/ta/reportportal/core/events/handler/DefectTypeDeletedHandler.java index 190f6abe39..5eff3bd3fc 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/handler/DefectTypeDeletedHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/handler/DefectTypeDeletedHandler.java @@ -29,7 +29,7 @@ import com.epam.ta.reportportal.dao.ProjectRepository; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.cache.Cache; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.retry.annotation.Backoff; diff --git a/src/main/java/com/epam/ta/reportportal/core/events/handler/GenerateWidgetViewEventHandler.java b/src/main/java/com/epam/ta/reportportal/core/events/handler/GenerateWidgetViewEventHandler.java index cfa1d63959..33d65c9187 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/handler/GenerateWidgetViewEventHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/handler/GenerateWidgetViewEventHandler.java @@ -14,7 +14,7 @@ import com.epam.ta.reportportal.dao.WidgetRepository; import com.epam.ta.reportportal.entity.widget.WidgetType; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Map; import org.apache.commons.lang3.BooleanUtils; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/main/java/com/epam/ta/reportportal/core/events/handler/item/TestItemUniqueErrorAnalysisRunner.java b/src/main/java/com/epam/ta/reportportal/core/events/handler/item/TestItemUniqueErrorAnalysisRunner.java index f281499da6..907ddc28ed 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/handler/item/TestItemUniqueErrorAnalysisRunner.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/handler/item/TestItemUniqueErrorAnalysisRunner.java @@ -24,8 +24,8 @@ import com.epam.ta.reportportal.core.launch.cluster.ClusterGenerator; import com.epam.ta.reportportal.core.launch.cluster.config.ClusterEntityContext; import com.epam.ta.reportportal.core.launch.cluster.config.GenerateClustersConfig; +import com.epam.ta.reportportal.model.project.UniqueErrorConfig; import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; -import com.epam.ta.reportportal.ws.model.project.UniqueErrorConfig; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Qualifier; @@ -35,8 +35,8 @@ * @author Ivan Budayeu */ @Service -public class TestItemUniqueErrorAnalysisRunner implements - ConfigurableEventHandler> { +public class TestItemUniqueErrorAnalysisRunner + implements ConfigurableEventHandler> { private final ClusterGenerator clusterGenerator; @@ -57,10 +57,10 @@ public void handle(IssueResolvedEvent event, Map projectConfig) final AnalyzerConfig analyzerConfig = getAnalyzerConfig(projectConfig); clustersConfig.setAnalyzerConfig(analyzerConfig); - final ClusterEntityContext entityContext = ClusterEntityContext.of(event.getLaunchId(), - event.getProjectId(), - List.of(event.getItemId()) - ); + final ClusterEntityContext entityContext = + ClusterEntityContext.of(event.getLaunchId(), event.getProjectId(), + List.of(event.getItemId()) + ); clustersConfig.setEntityContext(entityContext); clusterGenerator.generate(clustersConfig); diff --git a/src/main/java/com/epam/ta/reportportal/core/events/handler/launch/LaunchNotificationRunner.java b/src/main/java/com/epam/ta/reportportal/core/events/handler/launch/LaunchNotificationRunner.java index 21f6530d54..05cb79e5ea 100644 --- a/src/main/java/com/epam/ta/reportportal/core/events/handler/launch/LaunchNotificationRunner.java +++ b/src/main/java/com/epam/ta/reportportal/core/events/handler/launch/LaunchNotificationRunner.java @@ -43,8 +43,8 @@ import com.epam.ta.reportportal.util.email.EmailService; import com.epam.ta.reportportal.util.email.MailServiceFactory; import com.epam.ta.reportportal.ws.converter.converters.NotificationConfigConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.annotations.VisibleForTesting; import java.util.Map; import java.util.Objects; @@ -109,8 +109,6 @@ public void handle(LaunchFinishedEvent launchFinishedEvent, Map /** * Try to send email when it is needed * - * @param launch Launch to be used - * @param project Project * @param emailService Mail Service */ private void sendEmail(LaunchFinishedEvent launchFinishedEvent, EmailService emailService) { diff --git a/src/main/java/com/epam/ta/reportportal/core/file/DeleteFilesHandler.java b/src/main/java/com/epam/ta/reportportal/core/file/DeleteFilesHandler.java index 49161f40a1..ff9d747a3b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/file/DeleteFilesHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/file/DeleteFilesHandler.java @@ -6,8 +6,8 @@ import com.epam.ta.reportportal.core.events.MessageBus; import com.epam.ta.reportportal.core.events.attachment.DeleteAttachmentEvent; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.api.client.util.Lists; import com.opencsv.CSVParser; import com.opencsv.CSVParserBuilder; diff --git a/src/main/java/com/epam/ta/reportportal/core/file/impl/GetFileHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/file/impl/GetFileHandlerImpl.java index 3bc74f859e..479885dbde 100644 --- a/src/main/java/com/epam/ta/reportportal/core/file/impl/GetFileHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/file/impl/GetFileHandlerImpl.java @@ -29,7 +29,7 @@ import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.function.Predicate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/core/filter/DeleteUserFilterHandler.java b/src/main/java/com/epam/ta/reportportal/core/filter/DeleteUserFilterHandler.java index 81bbd11ada..770347ac00 100644 --- a/src/main/java/com/epam/ta/reportportal/core/filter/DeleteUserFilterHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/filter/DeleteUserFilterHandler.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.filter; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * Delete complex filter handler diff --git a/src/main/java/com/epam/ta/reportportal/core/filter/GetUserFilterHandler.java b/src/main/java/com/epam/ta/reportportal/core/filter/GetUserFilterHandler.java index e2918400fa..80ba1be427 100644 --- a/src/main/java/com/epam/ta/reportportal/core/filter/GetUserFilterHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/filter/GetUserFilterHandler.java @@ -19,11 +19,10 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.entity.filter.UserFilter; -import com.epam.ta.reportportal.ws.model.OwnedEntityResource; -import com.epam.ta.reportportal.ws.model.filter.UserFilterResource; -import org.springframework.data.domain.Pageable; - +import com.epam.ta.reportportal.model.OwnedEntityResource; +import com.epam.ta.reportportal.model.filter.UserFilterResource; import java.util.List; +import org.springframework.data.domain.Pageable; /** * Get filter handler @@ -32,47 +31,49 @@ */ public interface GetUserFilterHandler { - /** - * Get {@link UserFilterResource} by provided id - * - * @param id Provided id - * @param projectDetails Projcet details - * @return {@link UserFilterResource} - */ - UserFilterResource getUserFilter(Long id, ReportPortalUser.ProjectDetails projectDetails); + /** + * Get {@link UserFilterResource} by provided id + * + * @param id Provided id + * @param projectDetails Projcet details + * @return {@link UserFilterResource} + */ + UserFilterResource getUserFilter(Long id, ReportPortalUser.ProjectDetails projectDetails); - /** - * Get {@link UserFilterResource} objects - * - * @param projectName Project Name - * @param pageable Page request - * @param filter Filter representation - * @param user Report Portal User - * @return {@link Iterable} - */ - Iterable getUserFilters(String projectName, Pageable pageable, Filter filter, ReportPortalUser user); + /** + * Get {@link UserFilterResource} objects + * + * @param projectName Project Name + * @param pageable Page request + * @param filter Filter representation + * @param user Report Portal User + * @return {@link Iterable} + */ + Iterable getUserFilters(String projectName, Pageable pageable, Filter filter, + ReportPortalUser user); - /** - * Get all {@link com.epam.ta.reportportal.entity.filter.UserFilter}'s names - * - * @param projectDetails Project details - * @param pageable Page request - * @param filter Filter representation - * @param user Report Portal user - * @return List of {@link OwnedEntityResource} - */ - Iterable getFiltersNames(ReportPortalUser.ProjectDetails projectDetails, Pageable pageable, Filter filter, - ReportPortalUser user); + /** + * Get all {@link com.epam.ta.reportportal.entity.filter.UserFilter}'s names + * + * @param projectDetails Project details + * @param pageable Page request + * @param filter Filter representation + * @param user Report Portal user + * @return List of {@link OwnedEntityResource} + */ + Iterable getFiltersNames(ReportPortalUser.ProjectDetails projectDetails, + Pageable pageable, Filter filter, ReportPortalUser user); - /** - * Get all - * {@link com.epam.ta.reportportal.ws.model.filter.UserFilterResource} - * objects - * - * @param ids Filter IDs - * @param projectDetails Project details - * @param user Report Portal user - * @return Found filters - */ - List getFiltersById(Long[] ids, ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user); + /** + * Get all + * {@link UserFilterResource} + * objects + * + * @param ids Filter IDs + * @param projectDetails Project details + * @param user Report Portal user + * @return Found filters + */ + List getFiltersById(Long[] ids, ReportPortalUser.ProjectDetails projectDetails, + ReportPortalUser user); } diff --git a/src/main/java/com/epam/ta/reportportal/core/filter/SearchCriteriaService.java b/src/main/java/com/epam/ta/reportportal/core/filter/SearchCriteriaService.java index cfb5c93d17..f26ee8fead 100644 --- a/src/main/java/com/epam/ta/reportportal/core/filter/SearchCriteriaService.java +++ b/src/main/java/com/epam/ta/reportportal/core/filter/SearchCriteriaService.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.commons.querygen.Queryable; import com.epam.ta.reportportal.core.filter.predefined.PredefinedFilterType; -import com.epam.ta.reportportal.ws.model.SearchCriteriaRQ; +import com.epam.ta.reportportal.model.SearchCriteriaRQ; /** * Service for converting SearchCriteria to Filter. @@ -27,7 +27,7 @@ */ public interface SearchCriteriaService { - Queryable createFilterBySearchCriteria(SearchCriteriaRQ searchCriteriaRQ, - Class target, PredefinedFilterType predefinedFilterType); + Queryable createFilterBySearchCriteria(SearchCriteriaRQ searchCriteriaRQ, Class target, + PredefinedFilterType predefinedFilterType); } diff --git a/src/main/java/com/epam/ta/reportportal/core/filter/UpdateUserFilterHandler.java b/src/main/java/com/epam/ta/reportportal/core/filter/UpdateUserFilterHandler.java index 2374c0eb67..be378c31b1 100644 --- a/src/main/java/com/epam/ta/reportportal/core/filter/UpdateUserFilterHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/filter/UpdateUserFilterHandler.java @@ -17,14 +17,11 @@ package com.epam.ta.reportportal.core.filter; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.entity.filter.UserFilter; -import com.epam.ta.reportportal.ws.model.CollectionsRQ; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.filter.BulkUpdateFilterRQ; -import com.epam.ta.reportportal.ws.model.filter.UpdateUserFilterRQ; - -import java.util.Collection; +import com.epam.ta.reportportal.model.CollectionsRQ; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.filter.BulkUpdateFilterRQ; +import com.epam.ta.reportportal.model.filter.UpdateUserFilterRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.List; /** @@ -42,7 +39,8 @@ public interface UpdateUserFilterHandler { * @param user The {@link ReportPortalUser} who is creating the filter * @return An {@link EntryCreatedRS} instance containing the created filter's ID */ - EntryCreatedRS createFilter(UpdateUserFilterRQ createFilterRQ, String projectName, ReportPortalUser user); + EntryCreatedRS createFilter(UpdateUserFilterRQ createFilterRQ, String projectName, + ReportPortalUser user); /** * Update user filter with specified id @@ -53,18 +51,18 @@ public interface UpdateUserFilterHandler { * @param user User * @return {@link OperationCompletionRS} */ - OperationCompletionRS updateUserFilter(Long userFilterId, UpdateUserFilterRQ updateRQ, ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user); + OperationCompletionRS updateUserFilter(Long userFilterId, UpdateUserFilterRQ updateRQ, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user); /** * Update user filter * - * @param updateRQ Request for filter update - * @param projectDetails {@link ReportPortalUser.ProjectDetails} - * @param user {@link ReportPortalUser} filter's owner + * @param updateRQ Request for filter update + * @param projectDetails {@link ReportPortalUser.ProjectDetails} + * @param user {@link ReportPortalUser} filter's owner * @return List of {@link OperationCompletionRS} */ - List updateUserFilter(CollectionsRQ updateRQ, ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user); + List updateUserFilter(CollectionsRQ updateRQ, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user); } \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/core/filter/impl/DeleteUserFilterHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/filter/impl/DeleteUserFilterHandlerImpl.java index bb1a88f3a3..2ff17ccb60 100644 --- a/src/main/java/com/epam/ta/reportportal/core/filter/impl/DeleteUserFilterHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/filter/impl/DeleteUserFilterHandlerImpl.java @@ -16,6 +16,10 @@ package com.epam.ta.reportportal.core.filter.impl; +import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; +import static com.epam.ta.reportportal.ws.converter.converters.UserFilterConverter.TO_ACTIVITY_RESOURCE; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.USER_FILTER_NOT_FOUND; + import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.core.events.MessageBus; import com.epam.ta.reportportal.core.events.activity.FilterDeletedEvent; @@ -23,17 +27,12 @@ import com.epam.ta.reportportal.dao.UserFilterRepository; import com.epam.ta.reportportal.entity.filter.UserFilter; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import java.util.function.Predicate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.util.function.Predicate; - -import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; -import static com.epam.ta.reportportal.ws.converter.converters.UserFilterConverter.TO_ACTIVITY_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.USER_FILTER_NOT_FOUND; - @Service public class DeleteUserFilterHandlerImpl implements DeleteUserFilterHandler { diff --git a/src/main/java/com/epam/ta/reportportal/core/filter/impl/GetUserFilterHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/filter/impl/GetUserFilterHandlerImpl.java index d106551e61..2a84b9a07e 100644 --- a/src/main/java/com/epam/ta/reportportal/core/filter/impl/GetUserFilterHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/filter/impl/GetUserFilterHandlerImpl.java @@ -23,12 +23,12 @@ import com.epam.ta.reportportal.dao.UserFilterRepository; import com.epam.ta.reportportal.entity.filter.UserFilter; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.OwnedEntityResource; +import com.epam.ta.reportportal.model.filter.UserFilterResource; import com.epam.ta.reportportal.util.ProjectExtractor; import com.epam.ta.reportportal.ws.converter.PagedResourcesAssembler; import com.epam.ta.reportportal.ws.converter.converters.UserFilterConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OwnedEntityResource; -import com.epam.ta.reportportal.ws.model.filter.UserFilterResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Lists; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; @@ -37,8 +37,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.util.List; - /** * @author Pavel Bortnik */ @@ -59,38 +57,45 @@ public void setFilterRepository(UserFilterRepository filterRepository) { this.filterRepository = filterRepository; } - @Override - public UserFilterResource getUserFilter(Long id, ReportPortalUser.ProjectDetails projectDetails) { - final UserFilter userFilter = filterRepository.findByIdAndProjectId(id, projectDetails.getProjectId()) - .orElseThrow(() -> new ReportPortalException(ErrorType.USER_FILTER_NOT_FOUND_IN_PROJECT, - id, - projectDetails.getProjectName() - )); - return UserFilterConverter.TO_FILTER_RESOURCE.apply(userFilter); - } + @Override + public UserFilterResource getUserFilter(Long id, ReportPortalUser.ProjectDetails projectDetails) { + final UserFilter userFilter = + filterRepository.findByIdAndProjectId(id, projectDetails.getProjectId()).orElseThrow( + () -> new ReportPortalException(ErrorType.USER_FILTER_NOT_FOUND_IN_PROJECT, id, + projectDetails.getProjectName() + )); + return UserFilterConverter.TO_FILTER_RESOURCE.apply(userFilter); + } @Override - public Iterable getUserFilters(String projectName, Pageable pageable, Filter filter, - ReportPortalUser user) { - ReportPortalUser.ProjectDetails projectDetails = projectExtractor.extractProjectDetails(user, - projectName); - Page userFilters = filterRepository.findByFilter(ProjectFilter.of(filter, projectDetails.getProjectId()), pageable); - return PagedResourcesAssembler.pageConverter(UserFilterConverter.TO_FILTER_RESOURCE).apply(userFilters); + public Iterable getUserFilters(String projectName, Pageable pageable, + Filter filter, ReportPortalUser user) { + ReportPortalUser.ProjectDetails projectDetails = + projectExtractor.extractProjectDetails(user, projectName); + Page userFilters = + filterRepository.findByFilter(ProjectFilter.of(filter, projectDetails.getProjectId()), + pageable + ); + return PagedResourcesAssembler.pageConverter(UserFilterConverter.TO_FILTER_RESOURCE) + .apply(userFilters); } @Override - public Iterable getFiltersNames(ReportPortalUser.ProjectDetails projectDetails, Pageable pageable, Filter filter, - ReportPortalUser user) { - final Page userFilters = filterRepository.findByFilter( - ProjectFilter.of(filter, projectDetails.getProjectId()), - pageable - ); + public Iterable getFiltersNames( + ReportPortalUser.ProjectDetails projectDetails, Pageable pageable, Filter filter, + ReportPortalUser user) { + final Page userFilters = + filterRepository.findByFilter(ProjectFilter.of(filter, projectDetails.getProjectId()), + pageable + ); return PagedResourcesAssembler.pageConverter(UserFilterConverter.TO_OWNED_ENTITY_RESOURCE) .apply(userFilters); } @Override - public List getFiltersById(Long[] ids, ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { - return filterRepository.findAllByIdInAndProjectId(Lists.newArrayList(ids), projectDetails.getProjectId()); - } + public List getFiltersById(Long[] ids, ReportPortalUser.ProjectDetails projectDetails, + ReportPortalUser user) { + return filterRepository.findAllByIdInAndProjectId( + Lists.newArrayList(ids), projectDetails.getProjectId()); + } } diff --git a/src/main/java/com/epam/ta/reportportal/core/filter/impl/SearchCriteriaServiceImpl.java b/src/main/java/com/epam/ta/reportportal/core/filter/impl/SearchCriteriaServiceImpl.java index 02205d6242..f9c010d51f 100644 --- a/src/main/java/com/epam/ta/reportportal/core/filter/impl/SearchCriteriaServiceImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/filter/impl/SearchCriteriaServiceImpl.java @@ -25,12 +25,11 @@ import com.epam.ta.reportportal.core.filter.predefined.PredefinedFilterType; import com.epam.ta.reportportal.core.filter.predefined.PredefinedFilters; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.SearchCriteria; -import com.epam.ta.reportportal.ws.model.SearchCriteriaRQ; +import com.epam.ta.reportportal.model.SearchCriteria; +import com.epam.ta.reportportal.model.SearchCriteriaRQ; import com.google.common.collect.Lists; import java.util.List; import java.util.Optional; -import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; import org.jooq.Operator; @@ -47,8 +46,8 @@ public class SearchCriteriaServiceImpl implements SearchCriteriaService { private static final String PREDEFINED_FILTER = "predefinedFilter"; @Override - public Queryable createFilterBySearchCriteria(SearchCriteriaRQ searchCriteriaRQ, - Class target, PredefinedFilterType predefinedFilterType) { + public Queryable createFilterBySearchCriteria(SearchCriteriaRQ searchCriteriaRQ, Class target, + PredefinedFilterType predefinedFilterType) { Filter filter = new Filter(target, Lists.newArrayList()); @@ -60,26 +59,22 @@ public Queryable createFilterBySearchCriteria(SearchCriteriaRQ searchCriteriaRQ, Optional predefinedFilter = getPredefinedFilterIfExist(searchCriteriaRQ); - return predefinedFilter.isPresent() - ? createCompositeFilter(predefinedFilterType, filter, predefinedFilter.get()) - : filter; + return predefinedFilter.isPresent() ? + createCompositeFilter(predefinedFilterType, filter, predefinedFilter.get()) : filter; } private List collectConditions(SearchCriteriaRQ searchCriteriaRQ) { return searchCriteriaRQ.getCriteriaList().stream() .filter(criteria -> !PREDEFINED_FILTER.equalsIgnoreCase(criteria.getFilterKey())) - .map(this::mapCriteriaToCondition) - .collect(Collectors.toList()); + .map(this::mapCriteriaToCondition).collect(Collectors.toList()); } private ConvertibleCondition mapCriteriaToCondition(SearchCriteria searchCriteria) { - return FilterOperation.fromString(searchCriteria.getOperation()) - .map(operation -> operation.getConditionBuilder() - .withSearchCriteria(searchCriteria.getFilterKey()) - .withValue(searchCriteria.getValue()) - .build()) - .orElseThrow(() -> new ReportPortalException( - String.format("Can not convert operation type %s.", searchCriteria.getOperation()))); + return FilterOperation.fromString(searchCriteria.getOperation()).map( + operation -> operation.getConditionBuilder() + .withSearchCriteria(searchCriteria.getFilterKey()).withValue(searchCriteria.getValue()) + .build()).orElseThrow(() -> new ReportPortalException( + String.format("Can not convert operation type %s.", searchCriteria.getOperation()))); } private Optional getPredefinedFilterIfExist(SearchCriteriaRQ searchCriteriaRQ) { @@ -90,9 +85,9 @@ private Optional getPredefinedFilterIfExist(SearchCriteriaRQ sea private CompositeFilter createCompositeFilter(PredefinedFilterType predefinedFilterType, Filter filter, SearchCriteria predefinedFilter) { - String[] params = {predefinedFilter.getValue()}; - Queryable activityPredefinedFilter = PredefinedFilters - .buildFilter(predefinedFilterType, params); + String[] params = { predefinedFilter.getValue() }; + Queryable activityPredefinedFilter = + PredefinedFilters.buildFilter(predefinedFilterType, params); return new CompositeFilter(Operator.AND, filter, activityPredefinedFilter); } diff --git a/src/main/java/com/epam/ta/reportportal/core/filter/impl/UpdateUserFilterHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/filter/impl/UpdateUserFilterHandlerImpl.java index 83911724ef..8afa6180c0 100644 --- a/src/main/java/com/epam/ta/reportportal/core/filter/impl/UpdateUserFilterHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/filter/impl/UpdateUserFilterHandlerImpl.java @@ -19,7 +19,7 @@ import static com.epam.ta.reportportal.commons.Preconditions.NOT_EMPTY_COLLECTION; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.ws.converter.converters.UserFilterConverter.TO_ACTIVITY_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.USER_FILTER_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.USER_FILTER_NOT_FOUND; import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Condition; @@ -35,20 +35,16 @@ import com.epam.ta.reportportal.entity.filter.ObjectType; import com.epam.ta.reportportal.entity.filter.UserFilter; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.CollectionsRQ; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.activity.UserFilterActivityResource; +import com.epam.ta.reportportal.model.filter.BulkUpdateFilterRQ; +import com.epam.ta.reportportal.model.filter.UpdateUserFilterRQ; import com.epam.ta.reportportal.util.ProjectExtractor; import com.epam.ta.reportportal.ws.converter.builders.UserFilterBuilder; -import com.epam.ta.reportportal.ws.model.CollectionsRQ; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.epam.ta.reportportal.ws.model.ValidationConstraints; -import com.epam.ta.reportportal.ws.model.activity.UserFilterActivityResource; -import com.epam.ta.reportportal.ws.model.filter.BulkUpdateFilterRQ; -import com.epam.ta.reportportal.ws.model.filter.UpdateUserFilterRQ; -import org.apache.commons.lang3.BooleanUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - import java.util.List; import java.util.Optional; import java.util.function.Predicate; @@ -59,84 +55,84 @@ @Service public class UpdateUserFilterHandlerImpl implements UpdateUserFilterHandler { - private final static String KEY_AND_VALUE_DELIMITER = ":"; + private final static String KEY_AND_VALUE_DELIMITER = ":"; - private final static String ATTRIBUTES_DELIMITER = ","; - private final ProjectExtractor projectExtractor; - private final UserFilterRepository userFilterRepository; - private final MessageBus messageBus; + private final static String ATTRIBUTES_DELIMITER = ","; + private final ProjectExtractor projectExtractor; + private final UserFilterRepository userFilterRepository; + private final MessageBus messageBus; - @Autowired - public UpdateUserFilterHandlerImpl(ProjectExtractor projectExtractor, UserFilterRepository userFilterRepository, + @Autowired + public UpdateUserFilterHandlerImpl(ProjectExtractor projectExtractor, + UserFilterRepository userFilterRepository, - MessageBus messageBus) { - this.projectExtractor = projectExtractor; - this.userFilterRepository = userFilterRepository; - this.messageBus = messageBus; - } + MessageBus messageBus) { + this.projectExtractor = projectExtractor; + this.userFilterRepository = userFilterRepository; + this.messageBus = messageBus; + } @Override public EntryCreatedRS createFilter(UpdateUserFilterRQ createFilterRQ, String projectName, ReportPortalUser user) { - ReportPortalUser.ProjectDetails projectDetails = projectExtractor.extractProjectDetails(user, - projectName); + ReportPortalUser.ProjectDetails projectDetails = + projectExtractor.extractProjectDetails(user, projectName); validateFilterRq(createFilterRQ); - BusinessRule.expect(userFilterRepository.existsByNameAndOwnerAndProjectId(createFilterRQ.getName(), - user.getUsername(), - projectDetails.getProjectId() - ), BooleanUtils::isFalse) - .verify(ErrorType.USER_FILTER_ALREADY_EXISTS, createFilterRQ.getName(), user.getUsername(), projectName); + BusinessRule.expect( + userFilterRepository.existsByNameAndOwnerAndProjectId(createFilterRQ.getName(), + user.getUsername(), projectDetails.getProjectId() + ), BooleanUtils::isFalse) + .verify(ErrorType.USER_FILTER_ALREADY_EXISTS, createFilterRQ.getName(), user.getUsername(), + projectName + ); UserFilter filter = new UserFilterBuilder().addFilterRq(createFilterRQ) - .addProject(projectDetails.getProjectId()) - .addOwner(user.getUsername()) - .get(); - - userFilterRepository.save(filter); - messageBus.publishActivity(new FilterCreatedEvent(TO_ACTIVITY_RESOURCE.apply(filter), user.getUserId(), user.getUsername())); - return new EntryCreatedRS(filter.getId()); - } - - @Override - public OperationCompletionRS updateUserFilter(Long userFilterId, UpdateUserFilterRQ updateRQ, - ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { - validateFilterRq(updateRQ); - UserFilter userFilter = userFilterRepository.findByIdAndProjectId(userFilterId, projectDetails.getProjectId()) - .orElseThrow(() -> new ReportPortalException(ErrorType.USER_FILTER_NOT_FOUND_IN_PROJECT, - userFilterId, - projectDetails.getProjectName() - )); - expect(userFilter.getProject().getId(), Predicate.isEqual(projectDetails.getProjectId())).verify(USER_FILTER_NOT_FOUND, - userFilterId, - projectDetails.getProjectId(), - user.getUserId() - ); + .addProject(projectDetails.getProjectId()).addOwner(user.getUsername()).get(); + + userFilterRepository.save(filter); + messageBus.publishActivity( + new FilterCreatedEvent(TO_ACTIVITY_RESOURCE.apply(filter), user.getUserId(), + user.getUsername() + )); + return new EntryCreatedRS(filter.getId()); + } + + @Override + public OperationCompletionRS updateUserFilter(Long userFilterId, UpdateUserFilterRQ updateRQ, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { + validateFilterRq(updateRQ); + UserFilter userFilter = + userFilterRepository.findByIdAndProjectId(userFilterId, projectDetails.getProjectId()) + .orElseThrow(() -> new ReportPortalException(ErrorType.USER_FILTER_NOT_FOUND_IN_PROJECT, + userFilterId, projectDetails.getProjectName() + )); + expect( + userFilter.getProject().getId(), Predicate.isEqual(projectDetails.getProjectId())).verify( + USER_FILTER_NOT_FOUND, userFilterId, projectDetails.getProjectId(), user.getUserId()); if (!userFilter.getName().equals(updateRQ.getName())) { - BusinessRule.expect(userFilterRepository.existsByNameAndOwnerAndProjectId(updateRQ.getName(), - userFilter.getOwner(), - projectDetails.getProjectId() - ), BooleanUtils::isFalse) - .verify(ErrorType.USER_FILTER_ALREADY_EXISTS, - updateRQ.getName(), - userFilter.getOwner(), - projectDetails.getProjectName() - ); - } + BusinessRule.expect( + userFilterRepository.existsByNameAndOwnerAndProjectId(updateRQ.getName(), + userFilter.getOwner(), projectDetails.getProjectId() + ), BooleanUtils::isFalse) + .verify(ErrorType.USER_FILTER_ALREADY_EXISTS, updateRQ.getName(), userFilter.getOwner(), + projectDetails.getProjectName() + ); + } UserFilterActivityResource before = TO_ACTIVITY_RESOURCE.apply(userFilter); UserFilter updated = new UserFilterBuilder(userFilter).addFilterRq(updateRQ).get(); - messageBus.publishActivity(new FilterUpdatedEvent(before, - TO_ACTIVITY_RESOURCE.apply(updated), - user.getUserId(), - user.getUsername() - )); - return new OperationCompletionRS("User filter with ID = '" + updated.getId() + "' successfully updated."); - } + messageBus.publishActivity( + new FilterUpdatedEvent(before, TO_ACTIVITY_RESOURCE.apply(updated), user.getUserId(), + user.getUsername() + )); + return new OperationCompletionRS( + "User filter with ID = '" + updated.getId() + "' successfully updated."); + } @Override public List updateUserFilter(CollectionsRQ updateRQ, @@ -145,15 +141,14 @@ public List updateUserFilter(CollectionsRQ new ReportPortalException(ErrorType.INCORRECT_FILTER_PARAMETERS, Suppliers.formattedSupplier("Filter parameter '{}' is not defined", - it.getFilteringField()).get() + it.getFilteringField() + ).get() )); - Condition condition = Condition.findByMarker(it.getCondition()) - .orElseThrow(() -> new ReportPortalException(ErrorType.INCORRECT_FILTER_PARAMETERS, it.getCondition())); - boolean isNegative = Condition.isNegative(it.getCondition()); - String value = cutAttributesToMaxLength(it.getValue()); + Condition condition = Condition.findByMarker(it.getCondition()).orElseThrow( + () -> new ReportPortalException(ErrorType.INCORRECT_FILTER_PARAMETERS, + it.getCondition() + )); + boolean isNegative = Condition.isNegative(it.getCondition()); + String value = cutAttributesToMaxLength(it.getValue()); - condition.validate(criteriaHolder, value, isNegative, ErrorType.INCORRECT_FILTER_PARAMETERS); - condition.castValue(criteriaHolder, value, ErrorType.INCORRECT_FILTER_PARAMETERS); - it.setValue(value); - }); + condition.validate(criteriaHolder, value, isNegative, ErrorType.INCORRECT_FILTER_PARAMETERS); + condition.castValue(criteriaHolder, value, ErrorType.INCORRECT_FILTER_PARAMETERS); + it.setValue(value); + }); //order conditions validation - updateFilerRq.getOrders() - .forEach(order -> BusinessRule.expect( - filterTarget.getCriteriaByFilter(order.getSortingColumnName()), Optional::isPresent) - .verify(ErrorType.INCORRECT_SORTING_PARAMETERS, - "Unable to find sort parameter '" + order.getSortingColumnName() + "'" - )); + updateFilerRq.getOrders().forEach( + order -> BusinessRule.expect(filterTarget.getCriteriaByFilter(order.getSortingColumnName()), + Optional::isPresent + ).verify(ErrorType.INCORRECT_SORTING_PARAMETERS, + "Unable to find sort parameter '" + order.getSortingColumnName() + "'" + )); + } + + private String cutAttributesToMaxLength(String keyAndValue) { + if (keyAndValue == null || keyAndValue.isEmpty()) { + return keyAndValue; + } + String[] attributeArray = keyAndValue.split(ATTRIBUTES_DELIMITER); + if (attributeArray.length == 0) { + return cutAttributeToLength(keyAndValue, ValidationConstraints.MAX_ATTRIBUTE_LENGTH); + } + StringBuilder result = new StringBuilder(); + for (int i = 0; i < attributeArray.length; i++) { + String attribute = attributeArray[i]; + attribute = cutAttributeToLength(attribute, ValidationConstraints.MAX_ATTRIBUTE_LENGTH); + result.append(attribute); + if (i != attributeArray.length - 1) { + result.append(ATTRIBUTES_DELIMITER); + } + } + return result.toString(); } - private String cutAttributesToMaxLength(String keyAndValue) { - if (keyAndValue == null || keyAndValue.isEmpty()) { - return keyAndValue; - } - String[] attributeArray = keyAndValue.split(ATTRIBUTES_DELIMITER); - if (attributeArray.length == 0) { - return cutAttributeToLength(keyAndValue, ValidationConstraints.MAX_ATTRIBUTE_LENGTH); - } - StringBuilder result = new StringBuilder(); - for (int i = 0; i < attributeArray.length; i++) { - String attribute = attributeArray[i]; - attribute = cutAttributeToLength(attribute, ValidationConstraints.MAX_ATTRIBUTE_LENGTH); - result.append(attribute); - if (i != attributeArray.length - 1){ - result.append(ATTRIBUTES_DELIMITER); - } - } - return result.toString(); - } - - private String cutAttributeToLength(String attribute, int length){ - String[] keyAndValueArray = attribute.split(KEY_AND_VALUE_DELIMITER); - if (keyAndValueArray.length == 0) { - attribute = cutStringToLength(attribute, length); - } else { - if (keyAndValueArray.length == 1) { - if (attribute.contains(KEY_AND_VALUE_DELIMITER)) { - attribute = cutStringToLength(keyAndValueArray[0], length) + KEY_AND_VALUE_DELIMITER; - } else { - attribute = cutStringToLength(attribute, length); - } - } else { - String key = cutStringToLength(keyAndValueArray[0], length); - String value = cutStringToLength(keyAndValueArray[1], length); - attribute = key + KEY_AND_VALUE_DELIMITER + value; - } - } - return attribute; - } - - private String cutStringToLength(String string, int length) { - if (string.length() > length) { - string = string.substring(0, length); - } - - return string; - } + private String cutAttributeToLength(String attribute, int length) { + String[] keyAndValueArray = attribute.split(KEY_AND_VALUE_DELIMITER); + if (keyAndValueArray.length == 0) { + attribute = cutStringToLength(attribute, length); + } else { + if (keyAndValueArray.length == 1) { + if (attribute.contains(KEY_AND_VALUE_DELIMITER)) { + attribute = cutStringToLength(keyAndValueArray[0], length) + KEY_AND_VALUE_DELIMITER; + } else { + attribute = cutStringToLength(attribute, length); + } + } else { + String key = cutStringToLength(keyAndValueArray[0], length); + String value = cutStringToLength(keyAndValueArray[1], length); + attribute = key + KEY_AND_VALUE_DELIMITER + value; + } + } + return attribute; + } + + private String cutStringToLength(String string, int length) { + if (string.length() > length) { + string = string.substring(0, length); + } + + return string; + } } diff --git a/src/main/java/com/epam/ta/reportportal/core/filter/predefined/PredefinedFilterBuilder.java b/src/main/java/com/epam/ta/reportportal/core/filter/predefined/PredefinedFilterBuilder.java index 60404bfa17..c97103ef88 100644 --- a/src/main/java/com/epam/ta/reportportal/core/filter/predefined/PredefinedFilterBuilder.java +++ b/src/main/java/com/epam/ta/reportportal/core/filter/predefined/PredefinedFilterBuilder.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.commons.querygen.Queryable; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; /** * @author Andrei Varabyeu diff --git a/src/main/java/com/epam/ta/reportportal/core/hierarchy/AbstractFinishHierarchyHandler.java b/src/main/java/com/epam/ta/reportportal/core/hierarchy/AbstractFinishHierarchyHandler.java index 716405f69f..af0a352df8 100644 --- a/src/main/java/com/epam/ta/reportportal/core/hierarchy/AbstractFinishHierarchyHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/hierarchy/AbstractFinishHierarchyHandler.java @@ -25,7 +25,7 @@ import static com.epam.ta.reportportal.entity.enums.StatusEnum.SKIPPED; import static com.epam.ta.reportportal.entity.enums.TestItemIssueGroup.TO_INVESTIGATE; import static com.epam.ta.reportportal.entity.enums.TestItemTypeEnum.SUITE; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; import static java.util.Optional.ofNullable; import com.epam.ta.reportportal.commons.ReportPortalUser; diff --git a/src/main/java/com/epam/ta/reportportal/core/imprt/ImportLaunchHandler.java b/src/main/java/com/epam/ta/reportportal/core/imprt/ImportLaunchHandler.java index 9ff51786e5..c102362e2a 100644 --- a/src/main/java/com/epam/ta/reportportal/core/imprt/ImportLaunchHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/imprt/ImportLaunchHandler.java @@ -13,11 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.imprt; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.launch.LaunchImportRQ; +import com.epam.ta.reportportal.model.launch.LaunchImportRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import org.springframework.web.multipart.MultipartFile; /** @@ -37,6 +38,5 @@ public interface ImportLaunchHandler { * @return OperationCompletionRS */ OperationCompletionRS importLaunch(ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user, String format, MultipartFile file, String baseUrl, - LaunchImportRQ rq); + ReportPortalUser user, String format, MultipartFile file, String baseUrl, LaunchImportRQ rq); } \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/core/imprt/ImportLaunchHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/imprt/ImportLaunchHandlerImpl.java index e92d83e3fd..0476ea0170 100644 --- a/src/main/java/com/epam/ta/reportportal/core/imprt/ImportLaunchHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/imprt/ImportLaunchHandlerImpl.java @@ -20,7 +20,7 @@ import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.core.imprt.FileExtensionConstant.XML_EXTENSION; import static com.epam.ta.reportportal.core.imprt.FileExtensionConstant.ZIP_EXTENSION; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; import static org.apache.commons.io.FileUtils.ONE_MB; import com.epam.ta.reportportal.commons.ReportPortalUser; @@ -31,11 +31,11 @@ import com.epam.ta.reportportal.core.imprt.impl.ImportType; import com.epam.ta.reportportal.dao.LaunchRepository; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.LaunchImportCompletionRS; -import com.epam.ta.reportportal.ws.model.LaunchImportData; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.launch.LaunchImportRQ; +import com.epam.ta.reportportal.model.LaunchImportCompletionRS; +import com.epam.ta.reportportal.model.LaunchImportData; +import com.epam.ta.reportportal.model.launch.LaunchImportRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.io.File; import java.io.IOException; import java.util.Optional; @@ -53,7 +53,6 @@ public class ImportLaunchHandlerImpl implements ImportLaunchHandler { private final MessageBus messageBus; private final LaunchRepository launchRepository; - @Autowired public ImportLaunchHandlerImpl(ImportStrategyFactory importStrategyFactory, MessageBus messageBus, LaunchRepository launchRepository) { @@ -64,25 +63,24 @@ public ImportLaunchHandlerImpl(ImportStrategyFactory importStrategyFactory, Mess @Override public OperationCompletionRS importLaunch(ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user, String format, - MultipartFile file, String baseUrl, LaunchImportRQ rq) { + ReportPortalUser user, String format, MultipartFile file, String baseUrl, LaunchImportRQ rq) { validate(file); rq = getBackCompatibleRq(rq); - ImportType type = ImportType.fromValue(format) - .orElseThrow(() -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, - "Unknown import type - " + format)); + ImportType type = ImportType.fromValue(format).orElseThrow( + () -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, + "Unknown import type - " + format + )); File tempFile = transferToTempFile(file); - ImportStrategy strategy = importStrategyFactory.getImportStrategy(type, - file.getOriginalFilename()); + ImportStrategy strategy = + importStrategyFactory.getImportStrategy(type, file.getOriginalFilename()); String launchId = strategy.importLaunch(projectDetails, user, tempFile, baseUrl, rq); - messageBus.publishActivity(new ImportFinishedEvent(user.getUserId(), - user.getUsername(), - projectDetails.getProjectId(), - file.getOriginalFilename() - )); + messageBus.publishActivity( + new ImportFinishedEvent(user.getUserId(), user.getUsername(), projectDetails.getProjectId(), + file.getOriginalFilename() + )); return prepareLaunchImportResponse(launchId); } @@ -92,21 +90,25 @@ private LaunchImportRQ getBackCompatibleRq(LaunchImportRQ rq) { } private void validate(MultipartFile file) { - expect(file.getOriginalFilename(), notNull()).verify(ErrorType.INCORRECT_REQUEST, - "File name should be not empty."); + expect(file.getOriginalFilename(), notNull()).verify(INCORRECT_REQUEST, + "File name should be not empty." + ); expect(file.getOriginalFilename(), - it -> it.endsWith(ZIP_EXTENSION) || it.endsWith(XML_EXTENSION)).verify(INCORRECT_REQUEST, + it -> it.endsWith(ZIP_EXTENSION) || it.endsWith(XML_EXTENSION) + ).verify(INCORRECT_REQUEST, "Should be a zip archive or an xml file " + file.getOriginalFilename() ); expect(file.getSize(), size -> size <= MAX_FILE_SIZE).verify(INCORRECT_REQUEST, - "File size is more than 32 Mb."); + "File size is more than 32 Mb." + ); } private File transferToTempFile(MultipartFile file) { try { File tmp = File.createTempFile(file.getOriginalFilename(), - "." + FilenameUtils.getExtension(file.getOriginalFilename())); + "." + FilenameUtils.getExtension(file.getOriginalFilename()) + ); file.transferTo(tmp); return tmp; } catch (IOException e) { diff --git a/src/main/java/com/epam/ta/reportportal/core/imprt/impl/AbstractImportStrategy.java b/src/main/java/com/epam/ta/reportportal/core/imprt/impl/AbstractImportStrategy.java index 9cc95fde08..61cbffc9fb 100644 --- a/src/main/java/com/epam/ta/reportportal/core/imprt/impl/AbstractImportStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/imprt/impl/AbstractImportStrategy.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.imprt.impl; import static java.util.Optional.ofNullable; @@ -24,12 +25,12 @@ import com.epam.ta.reportportal.entity.enums.StatusEnum; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributesRQ; -import com.epam.ta.reportportal.ws.model.launch.LaunchImportRQ; -import com.epam.ta.reportportal.ws.model.launch.Mode; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; +import com.epam.ta.reportportal.model.launch.LaunchImportRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; +import com.epam.ta.reportportal.ws.reporting.ItemAttributesRQ; +import com.epam.ta.reportportal.ws.reporting.Mode; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; import com.google.common.collect.Sets; import java.time.LocalDateTime; import java.util.Arrays; @@ -90,16 +91,14 @@ protected String startLaunch(ReportPortalUser.ProjectDetails projectDetails, StartLaunchRQ startLaunchRQ = new StartLaunchRQ(); startLaunchRQ.setStartTime(ofNullable(rq.getStartTime()).orElse(initialStartTime)); startLaunchRQ.setName(ofNullable(rq.getName()).orElse(launchName)); - ofNullable(rq.getDescription()) - .ifPresent(startLaunchRQ::setDescription); + ofNullable(rq.getDescription()).ifPresent(startLaunchRQ::setDescription); startLaunchRQ.setMode(ofNullable(rq.getMode()).orElse(Mode.DEFAULT)); startLaunchRQ.setAttributes(ofNullable(rq.getAttributes()).orElse(Sets.newHashSet())); return startLaunchHandler.startLaunch(user, projectDetails, startLaunchRQ).getId(); } protected void finishLaunch(String launchId, ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user, - ParseResults results, String baseUrl) { + ReportPortalUser user, ParseResults results, String baseUrl) { FinishExecutionRQ finishExecutionRQ = new FinishExecutionRQ(); finishExecutionRQ.setEndTime(results.getEndTime()); finishLaunchHandler.finishLaunch(launchId, finishExecutionRQ, projectDetails, user, baseUrl); @@ -110,11 +109,10 @@ protected void finishLaunch(String launchId, ReportPortalUser.ProjectDetails pro } protected Boolean isSkippedNotIssue(Set attributes) { - return ofNullable(attributes).orElse(Collections.emptySet()).stream() - .filter( + return ofNullable(attributes).orElse(Collections.emptySet()).stream().filter( attribute -> SKIPPED_IS_NOT_ISSUE.equals(attribute.getKey()) && attribute.isSystem()) - .findAny() - .filter(itemAttributesRQ -> Boolean.parseBoolean(itemAttributesRQ.getValue())).isPresent(); + .findAny().filter(itemAttributesRQ -> Boolean.parseBoolean(itemAttributesRQ.getValue())) + .isPresent(); } /** diff --git a/src/main/java/com/epam/ta/reportportal/core/imprt/impl/ImportStrategy.java b/src/main/java/com/epam/ta/reportportal/core/imprt/impl/ImportStrategy.java index 20c7e1911c..057f4a193d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/imprt/impl/ImportStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/imprt/impl/ImportStrategy.java @@ -16,7 +16,7 @@ package com.epam.ta.reportportal.core.imprt.impl; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.launch.LaunchImportRQ; +import com.epam.ta.reportportal.model.launch.LaunchImportRQ; import java.io.File; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/imprt/impl/XmlImportStrategy.java b/src/main/java/com/epam/ta/reportportal/core/imprt/impl/XmlImportStrategy.java index c1bd76a038..d6165f31c1 100644 --- a/src/main/java/com/epam/ta/reportportal/core/imprt/impl/XmlImportStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/imprt/impl/XmlImportStrategy.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.imprt.impl; import static com.epam.ta.reportportal.core.imprt.FileExtensionConstant.XML_EXTENSION; @@ -21,8 +22,8 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.core.imprt.impl.junit.XunitParseJob; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.launch.LaunchImportRQ; +import com.epam.ta.reportportal.model.launch.LaunchImportRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; @@ -59,11 +60,13 @@ private String processXmlFile(File xml, ReportPortalUser.ProjectDetails projectD String savedLaunchId = null; try (InputStream xmlStream = new FileInputStream(xml)) { String launchId = startLaunch(projectDetails, user, - xml.getName().substring(0, xml.getName().indexOf("." + XML_EXTENSION)), rq); + xml.getName().substring(0, xml.getName().indexOf("." + XML_EXTENSION)), rq + ); savedLaunchId = launchId; XunitParseJob job = xmlParseJobProvider.get() .withParameters(projectDetails, launchId, user, xmlStream, - isSkippedNotIssue(rq.getAttributes())); + isSkippedNotIssue(rq.getAttributes()) + ); ParseResults parseResults = job.call(); finishLaunch(launchId, projectDetails, user, parseResults, baseUrl); return launchId; diff --git a/src/main/java/com/epam/ta/reportportal/core/imprt/impl/ZipImportStrategy.java b/src/main/java/com/epam/ta/reportportal/core/imprt/impl/ZipImportStrategy.java index b6b83ac8b4..2301355ad5 100644 --- a/src/main/java/com/epam/ta/reportportal/core/imprt/impl/ZipImportStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/imprt/impl/ZipImportStrategy.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.imprt.impl; import static com.epam.ta.reportportal.core.imprt.FileExtensionConstant.XML_EXTENSION; @@ -22,8 +23,8 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.core.imprt.impl.junit.XunitParseJob; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.launch.LaunchImportRQ; +import com.epam.ta.reportportal.model.launch.LaunchImportRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -42,8 +43,8 @@ public class ZipImportStrategy extends AbstractImportStrategy { private static final Predicate isFile = zipEntry -> !zipEntry.isDirectory(); - private static final Predicate isXml = zipEntry -> zipEntry.getName() - .endsWith(XML_EXTENSION); + private static final Predicate isXml = + zipEntry -> zipEntry.getName().endsWith(XML_EXTENSION); @Autowired private Provider xmlParseJobProvider; @@ -68,12 +69,14 @@ private String processZipFile(File zip, ReportPortalUser.ProjectDetails projectD String savedLaunchId = null; try (ZipFile zipFile = new ZipFile(zip)) { String launchId = startLaunch(projectDetails, user, - zip.getName().substring(0, zip.getName().indexOf("." + ZIP_EXTENSION)), rq); + zip.getName().substring(0, zip.getName().indexOf("." + ZIP_EXTENSION)), rq + ); savedLaunchId = launchId; CompletableFuture[] futures = zipFile.stream().filter(isFile.and(isXml)).map(zipEntry -> { XunitParseJob job = xmlParseJobProvider.get() .withParameters(projectDetails, launchId, user, getEntryStream(zipFile, zipEntry), - isSkippedNotIssue(rq.getAttributes())); + isSkippedNotIssue(rq.getAttributes()) + ); return CompletableFuture.supplyAsync(job::call, service); }).toArray(CompletableFuture[]::new); ParseResults parseResults = processResults(futures); diff --git a/src/main/java/com/epam/ta/reportportal/core/imprt/impl/junit/XunitImportHandler.java b/src/main/java/com/epam/ta/reportportal/core/imprt/impl/junit/XunitImportHandler.java index 935263f9bd..2054053f5b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/imprt/impl/junit/XunitImportHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/imprt/impl/junit/XunitImportHandler.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.imprt.impl.junit; import static com.epam.ta.reportportal.core.imprt.impl.DateUtils.toMillis; @@ -26,10 +27,10 @@ import com.epam.ta.reportportal.entity.enums.LogLevel; import com.epam.ta.reportportal.entity.enums.StatusEnum; import com.epam.ta.reportportal.entity.enums.TestItemTypeEnum; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.issue.Issue; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.Issue; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; import com.google.common.base.Strings; import java.time.Instant; import java.time.LocalDateTime; @@ -57,168 +58,172 @@ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class XunitImportHandler extends DefaultHandler { - private static final Logger LOGGER = LoggerFactory.getLogger(XunitImportHandler.class); - - private final StartTestItemHandler startTestItemHandler; - - private final FinishTestItemHandler finishTestItemHandler; - - private final CreateLogHandler createLogHandler; - - private static final int MAX_LAUNCH_NAME_LENGTH = 256; - - @Autowired - public XunitImportHandler(StartTestItemHandler startTestItemHandler, FinishTestItemHandler finishTestItemHandler, - CreateLogHandler createLogHandler) { - this.startTestItemHandler = startTestItemHandler; - this.finishTestItemHandler = finishTestItemHandler; - this.createLogHandler = createLogHandler; - } - - //initial info - private ReportPortalUser.ProjectDetails projectDetails; - private ReportPortalUser user; - private String launchUuid; - private boolean isSkippedNotIssue = false; - - //need to know item's id to attach System.out/System.err logs - private String currentItemUuid; - - private LocalDateTime startSuiteTime; - - private long commonDuration; - private long currentDuration; - - //items structure ids - private Deque itemUuids; - private StatusEnum status; - private StringBuilder message; - private LocalDateTime startItemTime; - - @Override - public void startDocument() { - itemUuids = new ArrayDeque<>(); - message = new StringBuilder(); - startSuiteTime = LocalDateTime.now(); - } - - @Override - public void endDocument() { - } - - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) { - switch (XunitReportTag.fromString(qName)) { - case TESTSUITE: - if (itemUuids.isEmpty()) { - startRootItem(attributes.getValue(XunitReportTag.ATTR_NAME.getValue()), - attributes.getValue(XunitReportTag.TIMESTAMP.getValue()) - ); - } else { - startTestItem(attributes.getValue(XunitReportTag.ATTR_NAME.getValue())); - } - break; - case TESTCASE: - startStepItem(attributes.getValue(XunitReportTag.ATTR_NAME.getValue()), - attributes.getValue(XunitReportTag.START_TIME.getValue()), - attributes.getValue(XunitReportTag.ATTR_TIME.getValue()) - ); - break; - case ERROR: - case FAILURE: - message = new StringBuilder(); - status = StatusEnum.FAILED; - break; - case SKIPPED: - message = new StringBuilder(); - status = StatusEnum.SKIPPED; - break; - case SYSTEM_OUT: - case SYSTEM_ERR: - case WARNING: - message = new StringBuilder(); - break; - case UNKNOWN: - default: - LOGGER.warn("Unknown tag: {}", qName); - break; - } - } - - @Override - public void endElement(String uri, String localName, String qName) { - switch (XunitReportTag.fromString(qName)) { - case TESTSUITE: - finishRootItem(); - break; - case TESTCASE: - finishTestItem(); - break; - case SKIPPED: - case ERROR: - case FAILURE: - case SYSTEM_ERR: - attachLog(LogLevel.ERROR); - break; - case SYSTEM_OUT: - attachLog(LogLevel.INFO); - break; - case WARNING: - attachLog(LogLevel.WARN); - break; - case UNKNOWN: - default: - LOGGER.warn("Unknown tag: {}", qName); - break; - } - } - - @Override - public void characters(char[] ch, int start, int length) { - String msg = new String(ch, start, length); - if (!msg.isEmpty()) { - message.append(msg); - } - } - - private void startRootItem(String name, String timestamp) { - if (null != timestamp) { - startItemTime = parseTimeStamp(timestamp); - if (startSuiteTime.isAfter(startItemTime)) { - startSuiteTime = LocalDateTime.of(startItemTime.toLocalDate(), startItemTime.toLocalTime()); - } - } else { - startItemTime = LocalDateTime.now(); - } - StartTestItemRQ rq = buildStartTestRq(name); - String id = startTestItemHandler.startRootItem(user, projectDetails, rq).getId(); - itemUuids.push(id); - } + private static final Logger LOGGER = LoggerFactory.getLogger(XunitImportHandler.class); + + private final StartTestItemHandler startTestItemHandler; + + private final FinishTestItemHandler finishTestItemHandler; + + private final CreateLogHandler createLogHandler; + + private static final int MAX_LAUNCH_NAME_LENGTH = 256; + + @Autowired + public XunitImportHandler(StartTestItemHandler startTestItemHandler, + FinishTestItemHandler finishTestItemHandler, CreateLogHandler createLogHandler) { + this.startTestItemHandler = startTestItemHandler; + this.finishTestItemHandler = finishTestItemHandler; + this.createLogHandler = createLogHandler; + } + + //initial info + private ReportPortalUser.ProjectDetails projectDetails; + private ReportPortalUser user; + private String launchUuid; + private boolean isSkippedNotIssue = false; + + //need to know item's id to attach System.out/System.err logs + private String currentItemUuid; + + private LocalDateTime startSuiteTime; + + private long commonDuration; + private long currentDuration; + + private long currentSuiteDuration; + + //items structure ids + private Deque itemUuids; + private StatusEnum status; + private StringBuilder message; + private LocalDateTime startItemTime; + + @Override + public void startDocument() { + itemUuids = new ArrayDeque<>(); + message = new StringBuilder(); + startSuiteTime = LocalDateTime.now(); + } + + @Override + public void endDocument() { + } + + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) { + switch (XunitReportTag.fromString(qName)) { + case TESTSUITE: + if (itemUuids.isEmpty()) { + startRootItem(attributes.getValue(XunitReportTag.ATTR_NAME.getValue()), + attributes.getValue(XunitReportTag.START_TIME.getValue()), + attributes.getValue(XunitReportTag.TIMESTAMP.getValue()), + attributes.getValue(XunitReportTag.ATTR_TIME.getValue()) + ); + } else { + startTestItem(attributes.getValue(XunitReportTag.ATTR_NAME.getValue())); + } + break; + case TESTCASE: + startStepItem(attributes.getValue(XunitReportTag.ATTR_NAME.getValue()), + attributes.getValue(XunitReportTag.START_TIME.getValue()), + attributes.getValue(XunitReportTag.TIMESTAMP.getValue()), + attributes.getValue(XunitReportTag.ATTR_TIME.getValue()) + ); + break; + case ERROR: + case FAILURE: + message = new StringBuilder(); + status = StatusEnum.FAILED; + break; + case SKIPPED: + message = new StringBuilder(); + status = StatusEnum.SKIPPED; + break; + case SYSTEM_OUT: + case SYSTEM_ERR: + case WARNING: + message = new StringBuilder(); + break; + case UNKNOWN: + default: + LOGGER.warn("Unknown tag: {}", qName); + break; + } + } + + @Override + public void endElement(String uri, String localName, String qName) { + switch (XunitReportTag.fromString(qName)) { + case TESTSUITE: + finishRootItem(); + break; + case TESTCASE: + finishTestItem(); + break; + case SKIPPED: + case ERROR: + case FAILURE: + case SYSTEM_ERR: + attachLog(LogLevel.ERROR); + break; + case SYSTEM_OUT: + attachLog(LogLevel.INFO); + break; + case WARNING: + attachLog(LogLevel.WARN); + break; + case UNKNOWN: + default: + LOGGER.warn("Unknown tag: {}", qName); + break; + } + } + + @Override + public void characters(char[] ch, int start, int length) { + String msg = new String(ch, start, length); + if (!msg.isEmpty()) { + message.append(msg); + } + } + + private void startRootItem(String name, String startTime, String timestamp, String duration) { + if (null != timestamp) { + startItemTime = parseTimeStamp(timestamp); + if (startSuiteTime.isAfter(startItemTime)) { + startSuiteTime = LocalDateTime.of(startItemTime.toLocalDate(), startItemTime.toLocalTime()); + } + } else if (null != startTime) { + startItemTime = parseTimeStamp(startTime); + if (startSuiteTime.isAfter(startItemTime)) { + startSuiteTime = LocalDateTime.of(startItemTime.toLocalDate(), startItemTime.toLocalTime()); + } + } else { + startItemTime = LocalDateTime.now(); + startSuiteTime = LocalDateTime.now(); + } + currentSuiteDuration = toMillis(duration); + StartTestItemRQ rq = buildStartTestRq(name); + String id = startTestItemHandler.startRootItem(user, projectDetails, rq).getId(); + itemUuids.push(id); + } private LocalDateTime parseTimeStamp(String timestamp) { // try to parse datetime as Long, otherwise parse as timestamp try { - return LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(timestamp)), ZoneOffset.UTC); + return LocalDateTime.ofInstant( + Instant.ofEpochMilli(Long.parseLong(timestamp)), ZoneOffset.UTC); } catch (NumberFormatException ignored) { - DateTimeFormatter formatter = new DateTimeFormatterBuilder() - .appendOptional(DateTimeFormatter.RFC_1123_DATE_TIME) - .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME) - .appendOptional(DateTimeFormatter.ISO_LOCAL_DATE_TIME) - .optionalStart() - .appendOffsetId() - .appendZoneId() - .optionalEnd() - .optionalStart() - .appendLiteral(' ') - .parseCaseSensitive() - .appendZoneId() - .optionalEnd() - .toFormatter(); + DateTimeFormatter formatter = + new DateTimeFormatterBuilder().appendOptional(DateTimeFormatter.RFC_1123_DATE_TIME) + .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME) + .appendOptional(DateTimeFormatter.ISO_LOCAL_DATE_TIME).optionalStart() + .appendOffsetId().appendZoneId().optionalEnd().optionalStart().appendLiteral(' ') + .parseCaseSensitive().appendZoneId().optionalEnd().toFormatter(); TemporalAccessor temporalAccessor = formatter.parse(timestamp); if (isParsedTimeStampHasOffset(temporalAccessor)) { - return ZonedDateTime.from(temporalAccessor) - .withZoneSameInstant(ZoneOffset.UTC) + return ZonedDateTime.from(temporalAccessor).withZoneSameInstant(ZoneOffset.UTC) .toLocalDateTime(); } else { return LocalDateTime.from(temporalAccessor); @@ -227,88 +232,101 @@ private LocalDateTime parseTimeStamp(String timestamp) { } - private void startTestItem(String name) { - StartTestItemRQ rq = buildStartTestRq(name); - String id = startTestItemHandler.startChildItem(user, projectDetails, rq, itemUuids.peek()).getId(); - itemUuids.push(id); - } - - private void startStepItem(String name, String startTime, String duration) { - StartTestItemRQ rq = new StartTestItemRQ(); - rq.setLaunchUuid(launchUuid); - rq.setStartTime(EntityUtils.TO_DATE.apply(startTime != null ? parseTimeStamp(startTime) : startItemTime)); - rq.setType(TestItemTypeEnum.STEP.name()); - rq.setName(StringUtils.abbreviate(name, MAX_LAUNCH_NAME_LENGTH)); - String id = startTestItemHandler.startChildItem(user, projectDetails, rq, itemUuids.peek()).getId(); - currentDuration = toMillis(duration); - currentItemUuid = id; - itemUuids.push(id); - } - - private void finishRootItem() { - FinishTestItemRQ rq = new FinishTestItemRQ(); - markAsNotIssue(rq); - rq.setEndTime(EntityUtils.TO_DATE.apply(startItemTime)); - finishTestItemHandler.finishTestItem(user, projectDetails, itemUuids.poll(), rq); - status = null; - } - - private void finishTestItem() { - FinishTestItemRQ rq = new FinishTestItemRQ(); - markAsNotIssue(rq); - startItemTime = startItemTime.plus(currentDuration, ChronoUnit.MILLIS); - commonDuration += currentDuration; - rq.setEndTime(EntityUtils.TO_DATE.apply(startItemTime)); - rq.setStatus(Optional.ofNullable(status).orElse(StatusEnum.PASSED).name()); - currentItemUuid = itemUuids.poll(); - finishTestItemHandler.finishTestItem(user, projectDetails, currentItemUuid, rq); - status = null; - } - - private void markAsNotIssue(FinishTestItemRQ rq) { - if (StatusEnum.SKIPPED.equals(status) && isSkippedNotIssue) { - Issue issue = new Issue(); - issue.setIssueType(NOT_ISSUE_FLAG.getValue()); - rq.setIssue(issue); - } - } - - private void attachLog(LogLevel logLevel) { - if (null != message && message.length() != 0) { - SaveLogRQ saveLogRQ = new SaveLogRQ(); - saveLogRQ.setLevel(logLevel.name()); - saveLogRQ.setLogTime(EntityUtils.TO_DATE.apply(startItemTime)); - saveLogRQ.setMessage(message.toString().trim()); - saveLogRQ.setItemUuid(currentItemUuid); - createLogHandler.createLog(saveLogRQ, null, projectDetails); - } - } - - XunitImportHandler withParameters(ReportPortalUser.ProjectDetails projectDetails, String launchId, - ReportPortalUser user, boolean isSkippedNotIssue) { - this.projectDetails = projectDetails; - this.launchUuid = launchId; - this.user = user; - this.isSkippedNotIssue = isSkippedNotIssue; - return this; - } - - private StartTestItemRQ buildStartTestRq(String name) { - StartTestItemRQ rq = new StartTestItemRQ(); - rq.setLaunchUuid(launchUuid); - rq.setStartTime(EntityUtils.TO_DATE.apply(startItemTime)); - rq.setType(TestItemTypeEnum.TEST.name()); - rq.setName(Strings.isNullOrEmpty(name) ? "no_name" : name); - return rq; - } - - LocalDateTime getStartSuiteTime() { - return startSuiteTime; - } - - long getCommonDuration() { - return commonDuration; - } + private void startTestItem(String name) { + StartTestItemRQ rq = buildStartTestRq(name); + String id = + startTestItemHandler.startChildItem(user, projectDetails, rq, itemUuids.peek()).getId(); + itemUuids.push(id); + } + + private void startStepItem(String name, String startTime, String timestamp, String duration) { + StartTestItemRQ rq = new StartTestItemRQ(); + rq.setLaunchUuid(launchUuid); + rq.setType(TestItemTypeEnum.STEP.name()); + rq.setName(StringUtils.abbreviate(name, MAX_LAUNCH_NAME_LENGTH)); + + if (null != timestamp) { + startItemTime = parseTimeStamp(timestamp); + } else if (null != startTime) { + startItemTime = parseTimeStamp(startTime); + } else { + startItemTime = startSuiteTime; + } + + rq.setStartTime(EntityUtils.TO_DATE.apply(startItemTime)); + + String id = + startTestItemHandler.startChildItem(user, projectDetails, rq, itemUuids.peek()).getId(); + currentDuration = toMillis(duration); + currentItemUuid = id; + itemUuids.push(id); + } + + private void finishRootItem() { + FinishTestItemRQ rq = new FinishTestItemRQ(); + markAsNotIssue(rq); + rq.setEndTime( + EntityUtils.TO_DATE.apply(startSuiteTime.plus(currentSuiteDuration, ChronoUnit.MILLIS))); + finishTestItemHandler.finishTestItem(user, projectDetails, itemUuids.poll(), rq); + status = null; + } + + private void finishTestItem() { + FinishTestItemRQ rq = new FinishTestItemRQ(); + markAsNotIssue(rq); + LocalDateTime endTime = startItemTime.plus(currentDuration, ChronoUnit.MILLIS); + commonDuration += currentDuration; + rq.setEndTime(EntityUtils.TO_DATE.apply(endTime)); + rq.setStatus(Optional.ofNullable(status).orElse(StatusEnum.PASSED).name()); + currentItemUuid = itemUuids.poll(); + finishTestItemHandler.finishTestItem(user, projectDetails, currentItemUuid, rq); + status = null; + } + + private void markAsNotIssue(FinishTestItemRQ rq) { + if (StatusEnum.SKIPPED.equals(status) && isSkippedNotIssue) { + Issue issue = new Issue(); + issue.setIssueType(NOT_ISSUE_FLAG.getValue()); + rq.setIssue(issue); + } + } + + private void attachLog(LogLevel logLevel) { + if (null != message && message.length() != 0) { + SaveLogRQ saveLogRQ = new SaveLogRQ(); + saveLogRQ.setLevel(logLevel.name()); + saveLogRQ.setLogTime(EntityUtils.TO_DATE.apply(startItemTime)); + saveLogRQ.setMessage(message.toString().trim()); + saveLogRQ.setItemUuid(currentItemUuid); + createLogHandler.createLog(saveLogRQ, null, projectDetails); + } + } + + XunitImportHandler withParameters(ReportPortalUser.ProjectDetails projectDetails, String launchId, + ReportPortalUser user, boolean isSkippedNotIssue) { + this.projectDetails = projectDetails; + this.launchUuid = launchId; + this.user = user; + this.isSkippedNotIssue = isSkippedNotIssue; + return this; + } + + private StartTestItemRQ buildStartTestRq(String name) { + StartTestItemRQ rq = new StartTestItemRQ(); + rq.setLaunchUuid(launchUuid); + rq.setStartTime(EntityUtils.TO_DATE.apply(startItemTime)); + rq.setType(TestItemTypeEnum.TEST.name()); + rq.setName(Strings.isNullOrEmpty(name) ? "no_name" : name); + return rq; + } + + LocalDateTime getStartSuiteTime() { + return startSuiteTime; + } + + long getCommonDuration() { + return commonDuration; + } private boolean isParsedTimeStampHasOffset(TemporalAccessor temporalAccessor) { return temporalAccessor.query(TemporalQueries.offset()) != null; diff --git a/src/main/java/com/epam/ta/reportportal/core/imprt/impl/junit/XunitParseJob.java b/src/main/java/com/epam/ta/reportportal/core/imprt/impl/junit/XunitParseJob.java index 60880a5c9b..56d2158b6e 100644 --- a/src/main/java/com/epam/ta/reportportal/core/imprt/impl/junit/XunitParseJob.java +++ b/src/main/java/com/epam/ta/reportportal/core/imprt/impl/junit/XunitParseJob.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.core.imprt.impl.ParseResults; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/CreateIntegrationHandler.java b/src/main/java/com/epam/ta/reportportal/core/integration/CreateIntegrationHandler.java index 707984f395..ee52fbc877 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/CreateIntegrationHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/CreateIntegrationHandler.java @@ -18,9 +18,9 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.entity.integration.Integration; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.integration.IntegrationRQ; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.integration.IntegrationRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * @author Ivan Budayeu diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/DeleteIntegrationHandler.java b/src/main/java/com/epam/ta/reportportal/core/integration/DeleteIntegrationHandler.java index 924b57b745..87a2f88a51 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/DeleteIntegrationHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/DeleteIntegrationHandler.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.integration; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * @author Andrei Varabyeu diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/GetIntegrationHandler.java b/src/main/java/com/epam/ta/reportportal/core/integration/GetIntegrationHandler.java index e58315f011..ca13ff86d1 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/GetIntegrationHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/GetIntegrationHandler.java @@ -19,7 +19,7 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.entity.enums.IntegrationGroupEnum; import com.epam.ta.reportportal.entity.integration.Integration; -import com.epam.ta.reportportal.ws.model.integration.IntegrationResource; +import com.epam.ta.reportportal.model.integration.IntegrationResource; import java.util.List; import java.util.Optional; diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/impl/CreateIntegrationHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/integration/impl/CreateIntegrationHandlerImpl.java index 7bca6c9f23..ec13644052 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/impl/CreateIntegrationHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/impl/CreateIntegrationHandlerImpl.java @@ -33,11 +33,11 @@ import com.epam.ta.reportportal.entity.integration.IntegrationType; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.activity.IntegrationActivityResource; -import com.epam.ta.reportportal.ws.model.integration.IntegrationRQ; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.activity.IntegrationActivityResource; +import com.epam.ta.reportportal.model.integration.IntegrationRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.Map; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; @@ -65,11 +65,10 @@ public class CreateIntegrationHandlerImpl implements CreateIntegrationHandler { private final IntegrationService basicIntegrationService; @Autowired - public CreateIntegrationHandlerImpl( - @Qualifier("integrationServiceMapping") Map integrationServiceMapping, + public CreateIntegrationHandlerImpl(@Qualifier("integrationServiceMapping") + Map integrationServiceMapping, IntegrationRepository integrationRepository, ProjectRepository projectRepository, - ApplicationEventPublisher eventPublisher, - IntegrationTypeRepository integrationTypeRepository, + ApplicationEventPublisher eventPublisher, IntegrationTypeRepository integrationTypeRepository, @Qualifier("basicIntegrationServiceImpl") IntegrationService integrationService) { this.integrationServiceMapping = integrationServiceMapping; this.integrationRepository = integrationRepository; @@ -84,17 +83,18 @@ public EntryCreatedRS createGlobalIntegration(IntegrationRQ createRequest, Strin ReportPortalUser user) { IntegrationType integrationType = integrationTypeRepository.findByName(pluginName) .orElseThrow(() -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, pluginName)); - IntegrationService integrationService = integrationServiceMapping.getOrDefault( - integrationType.getName(), - this.basicIntegrationService - ); + IntegrationService integrationService = + integrationServiceMapping.getOrDefault(integrationType.getName(), + this.basicIntegrationService + ); - String integrationName = ofNullable(createRequest.getName()).map(String::toLowerCase) - .map(name -> { + String integrationName = + ofNullable(createRequest.getName()).map(String::toLowerCase).map(name -> { validateGlobalIntegrationName(name, integrationType); return name; }).orElseThrow(() -> new ReportPortalException(ErrorType.INCORRECT_INTEGRATION_NAME, - "Integration name should be not null")); + "Integration name should be not null" + )); createRequest.setName(integrationName); Integration integration = integrationService.createIntegration(createRequest, integrationType); @@ -109,8 +109,7 @@ public EntryCreatedRS createGlobalIntegration(IntegrationRQ createRequest, Strin @Override public EntryCreatedRS createProjectIntegration(String projectName, IntegrationRQ createRequest, - String pluginName, - ReportPortalUser user) { + String pluginName, ReportPortalUser user) { Project project = projectRepository.findByName(projectName) .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, projectName)); @@ -118,17 +117,18 @@ public EntryCreatedRS createProjectIntegration(String projectName, IntegrationRQ IntegrationType integrationType = integrationTypeRepository.findByName(pluginName) .orElseThrow(() -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, pluginName)); - IntegrationService integrationService = integrationServiceMapping.getOrDefault( - integrationType.getName(), - this.basicIntegrationService - ); + IntegrationService integrationService = + integrationServiceMapping.getOrDefault(integrationType.getName(), + this.basicIntegrationService + ); - String integrationName = ofNullable(createRequest.getName()).map(String::toLowerCase) - .map(name -> { + String integrationName = + ofNullable(createRequest.getName()).map(String::toLowerCase).map(name -> { validateProjectIntegrationName(name, integrationType, project); return name; }).orElseThrow(() -> new ReportPortalException(ErrorType.INCORRECT_INTEGRATION_NAME, - "Integration name should be not null")); + "Integration name should be not null" + )); createRequest.setName(integrationName); Integration integration = integrationService.createIntegration(createRequest, integrationType); @@ -158,13 +158,13 @@ public OperationCompletionRS updateGlobalIntegration(Long id, IntegrationRQ upda updateRequest.setName(name); }); - IntegrationService integrationService = integrationServiceMapping.getOrDefault( - integration.getType().getName(), - this.basicIntegrationService - ); + IntegrationService integrationService = + integrationServiceMapping.getOrDefault(integration.getType().getName(), + this.basicIntegrationService + ); - Integration updatedIntegration = integrationService.updateIntegration(integration, - updateRequest); + Integration updatedIntegration = + integrationService.updateIntegration(integration, updateRequest); integrationService.checkConnection(integration); integrationRepository.save(updatedIntegration); @@ -193,12 +193,12 @@ public OperationCompletionRS updateProjectIntegration(Long id, String projectNam updateRequest.setName(name); }); - IntegrationService integrationService = integrationServiceMapping.getOrDefault( - integration.getType().getName(), - this.basicIntegrationService - ); - Integration updatedIntegration = integrationService.updateIntegration(integration, - updateRequest); + IntegrationService integrationService = + integrationServiceMapping.getOrDefault(integration.getType().getName(), + this.basicIntegrationService + ); + Integration updatedIntegration = + integrationService.updateIntegration(integration, updateRequest); updatedIntegration.setProject(project); integrationService.checkConnection(integration); @@ -215,17 +215,14 @@ private void validateGlobalIntegrationName(String integrationName, BusinessRule.expect(integrationName, StringUtils::isNotBlank) .verify(ErrorType.INCORRECT_INTEGRATION_NAME, "Integration name should be not empty"); BusinessRule.expect( - integrationRepository.existsByNameAndTypeIdAndProjectIdIsNull(integrationName, - integrationType.getId()), - BooleanUtils::isFalse + integrationRepository.existsByNameAndTypeIdAndProjectIdIsNull(integrationName, + integrationType.getId() + ), BooleanUtils::isFalse).verify(ErrorType.INTEGRATION_ALREADY_EXISTS, + Suppliers.formattedSupplier( + "Global integration of type = '{}' with name = '{}' already exists", + integrationType.getName(), integrationName ) - .verify(ErrorType.INTEGRATION_ALREADY_EXISTS, - Suppliers.formattedSupplier( - "Global integration of type = '{}' with name = '{}' already exists", - integrationType.getName(), - integrationName - ) - ); + ); } private void validateProjectIntegrationName(String integrationName, @@ -233,34 +230,28 @@ private void validateProjectIntegrationName(String integrationName, BusinessRule.expect(integrationName, StringUtils::isNotBlank) .verify(ErrorType.INCORRECT_INTEGRATION_NAME, "Integration name should be not empty"); BusinessRule.expect(integrationRepository.existsByNameAndTypeIdAndProjectId(integrationName, - integrationType.getId(), - project.getId() - ), BooleanUtils::isFalse) - .verify(ErrorType.INTEGRATION_ALREADY_EXISTS, - Suppliers.formattedSupplier( - "Project integration of type = '{}' with name = '{}' already exists on project = '{}'", - integrationType.getName(), - integrationName, - project.getName() - ) - ); + integrationType.getId(), project.getId() + ), BooleanUtils::isFalse).verify(ErrorType.INTEGRATION_ALREADY_EXISTS, + Suppliers.formattedSupplier( + "Project integration of type = '{}' with name = '{}' already exists on project = '{}'", + integrationType.getName(), integrationName, project.getName() + ) + ); } private void publishUpdateActivity(ReportPortalUser user, - IntegrationActivityResource beforeUpdate, - Integration updatedIntegration) { - eventPublisher.publishEvent(new IntegrationUpdatedEvent(user.getUserId(), - user.getUsername(), - beforeUpdate, - TO_ACTIVITY_RESOURCE.apply(updatedIntegration) - )); + IntegrationActivityResource beforeUpdate, Integration updatedIntegration) { + eventPublisher.publishEvent( + new IntegrationUpdatedEvent(user.getUserId(), user.getUsername(), beforeUpdate, + TO_ACTIVITY_RESOURCE.apply(updatedIntegration) + )); } private void publishCreationActivity(Integration integration, ReportPortalUser user) { - eventPublisher.publishEvent(new IntegrationCreatedEvent(TO_ACTIVITY_RESOURCE.apply(integration), - user.getUserId(), - user.getUsername() - )); + eventPublisher.publishEvent( + new IntegrationCreatedEvent(TO_ACTIVITY_RESOURCE.apply(integration), user.getUserId(), + user.getUsername() + )); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/impl/DeleteIntegrationHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/integration/impl/DeleteIntegrationHandlerImpl.java index 4137032e78..19c4b400a1 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/impl/DeleteIntegrationHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/impl/DeleteIntegrationHandlerImpl.java @@ -27,8 +27,8 @@ import com.epam.ta.reportportal.entity.integration.IntegrationType; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Service; @@ -37,8 +37,8 @@ import java.util.List; import static com.epam.ta.reportportal.ws.converter.converters.IntegrationConverter.TO_ACTIVITY_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.INTEGRATION_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INTEGRATION_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; /** * @author Andrei Varabyeu diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/impl/ExecuteIntegrationHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/integration/impl/ExecuteIntegrationHandlerImpl.java index 315d1692e6..e3fc47a608 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/impl/ExecuteIntegrationHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/impl/ExecuteIntegrationHandlerImpl.java @@ -17,9 +17,9 @@ package com.epam.ta.reportportal.core.integration.impl; import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; -import static com.epam.ta.reportportal.ws.model.ErrorType.INTEGRATION_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INTEGRATION_NOT_FOUND; import static java.util.Optional.ofNullable; import com.epam.reportportal.extension.ReportPortalExtensionPoint; @@ -30,7 +30,7 @@ import com.epam.ta.reportportal.dao.IntegrationRepository; import com.epam.ta.reportportal.entity.integration.Integration; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.Map; import java.util.function.Supplier; import org.springframework.scheduling.annotation.Async; diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/impl/GetIntegrationHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/integration/impl/GetIntegrationHandlerImpl.java index d3c2e00305..f3c78358ed 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/impl/GetIntegrationHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/impl/GetIntegrationHandlerImpl.java @@ -33,8 +33,8 @@ import com.epam.ta.reportportal.entity.integration.IntegrationType; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.integration.IntegrationResource; +import com.epam.ta.reportportal.model.integration.IntegrationResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import java.util.Optional; @@ -58,8 +58,8 @@ public class GetIntegrationHandlerImpl implements GetIntegrationHandler { private final GetBugTrackingSystemHandler getBugTrackingSystemHandler; @Autowired - public GetIntegrationHandlerImpl( - @Qualifier("integrationServiceMapping") Map integrationServiceMapping, + public GetIntegrationHandlerImpl(@Qualifier("integrationServiceMapping") + Map integrationServiceMapping, @Qualifier("basicIntegrationServiceImpl") IntegrationService integrationService, IntegrationRepository integrationRepository, IntegrationTypeRepository integrationTypeRepository, ProjectRepository projectRepository, @@ -76,18 +76,16 @@ public GetIntegrationHandlerImpl( public IntegrationResource getProjectIntegrationById(Long integrationId, String projectName) { Project project = projectRepository.findByName(projectName) .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, projectName)); - Integration integration = integrationRepository.findByIdAndProjectId(integrationId, - project.getId()) - .orElseThrow( + Integration integration = + integrationRepository.findByIdAndProjectId(integrationId, project.getId()).orElseThrow( () -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, integrationId)); return TO_INTEGRATION_RESOURCE.apply(integration); } @Override public IntegrationResource getGlobalIntegrationById(Long integrationId) { - Integration integration = integrationRepository.findGlobalById(integrationId) - .orElseThrow( - () -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, integrationId)); + Integration integration = integrationRepository.findGlobalById(integrationId).orElseThrow( + () -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, integrationId)); return TO_INTEGRATION_RESOURCE.apply(integration); } @@ -95,14 +93,14 @@ public IntegrationResource getGlobalIntegrationById(Long integrationId) { public Optional getEnabledByProjectIdOrGlobalAndIntegrationGroup(Long projectId, IntegrationGroupEnum integrationGroup) { - List integrationTypeIds = integrationTypeRepository.findAllByIntegrationGroup( - integrationGroup) - .stream() - .map(IntegrationType::getId) - .collect(Collectors.toList()); + List integrationTypeIds = + integrationTypeRepository.findAllByIntegrationGroup(integrationGroup).stream() + .map(IntegrationType::getId).collect(Collectors.toList()); - List integrations = integrationRepository.findAllByProjectIdAndInIntegrationTypeIds( - projectId, integrationTypeIds); + List integrations = + integrationRepository.findAllByProjectIdAndInIntegrationTypeIds(projectId, + integrationTypeIds + ); if (!CollectionUtils.isEmpty(integrations)) { @@ -121,22 +119,25 @@ public Optional getEnabledByProjectIdOrGlobalAndIntegrationGroup(Lo public Integration getEnabledBtsIntegration(ReportPortalUser.ProjectDetails projectDetails, String url, String btsProject) { - Project project = projectRepository.findById(projectDetails.getProjectId()) - .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, - projectDetails.getProjectName())); - - Integration integration = getBugTrackingSystemHandler.getEnabledProjectIntegration( - projectDetails, url, btsProject) - .orElseGet(() -> { - Integration globalIntegration = getBugTrackingSystemHandler.getEnabledGlobalIntegration( - url, btsProject) - .orElseThrow(() -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, url)); - - IntegrationValidator.validateProjectLevelIntegrationConstraints(project, - globalIntegration); - - return globalIntegration; - }); + Project project = projectRepository.findById(projectDetails.getProjectId()).orElseThrow( + () -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, + projectDetails.getProjectName() + )); + + Integration integration = + getBugTrackingSystemHandler.getEnabledProjectIntegration(projectDetails, url, btsProject) + .orElseGet(() -> { + Integration globalIntegration = + getBugTrackingSystemHandler.getEnabledGlobalIntegration(url, btsProject) + .orElseThrow( + () -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, url)); + + IntegrationValidator.validateProjectLevelIntegrationConstraints(project, + globalIntegration + ); + + return globalIntegration; + }); validateIntegration(integration); return integration; } @@ -145,21 +146,25 @@ public Integration getEnabledBtsIntegration(ReportPortalUser.ProjectDetails proj public Integration getEnabledBtsIntegration(ReportPortalUser.ProjectDetails projectDetails, Long integrationId) { - Project project = projectRepository.findById(projectDetails.getProjectId()) - .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, - projectDetails.getProjectName())); - - Integration integration = getBugTrackingSystemHandler.getEnabledProjectIntegration( - projectDetails, integrationId).orElseGet(() -> { - Integration globalIntegration = getBugTrackingSystemHandler.getEnabledGlobalIntegration( - integrationId) - .orElseThrow( - () -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, integrationId)); - - IntegrationValidator.validateProjectLevelIntegrationConstraints(project, globalIntegration); - - return globalIntegration; - }); + Project project = projectRepository.findById(projectDetails.getProjectId()).orElseThrow( + () -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, + projectDetails.getProjectName() + )); + + Integration integration = + getBugTrackingSystemHandler.getEnabledProjectIntegration(projectDetails, integrationId) + .orElseGet(() -> { + Integration globalIntegration = + getBugTrackingSystemHandler.getEnabledGlobalIntegration(integrationId) + .orElseThrow(() -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, + integrationId + )); + + IntegrationValidator.validateProjectLevelIntegrationConstraints( + project, globalIntegration); + + return globalIntegration; + }); validateIntegration(integration); return integration; } @@ -167,9 +172,8 @@ public Integration getEnabledBtsIntegration(ReportPortalUser.ProjectDetails proj @Override public Integration getEnabledBtsIntegration(Long integrationId) { - Integration globalIntegration = getBugTrackingSystemHandler.getEnabledGlobalIntegration( - integrationId) - .orElseThrow( + Integration globalIntegration = + getBugTrackingSystemHandler.getEnabledGlobalIntegration(integrationId).orElseThrow( () -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, integrationId)); return globalIntegration; @@ -185,10 +189,8 @@ public List getGlobalIntegrations() { public List getGlobalIntegrations(String pluginName) { IntegrationType integrationType = integrationTypeRepository.findByName(pluginName) .orElseThrow(() -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, pluginName)); - return integrationRepository.findAllGlobalByType(integrationType) - .stream() - .map(TO_INTEGRATION_RESOURCE) - .collect(Collectors.toList()); + return integrationRepository.findAllGlobalByType(integrationType).stream() + .map(TO_INTEGRATION_RESOURCE).collect(Collectors.toList()); } @Override @@ -206,10 +208,8 @@ public List getProjectIntegrations(String pluginName, Strin IntegrationType integrationType = integrationTypeRepository.findByName(pluginName) .orElseThrow(() -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, pluginName)); return integrationRepository.findAllByProjectIdAndTypeOrderByCreationDateDesc(project.getId(), - integrationType) - .stream() - .map(TO_INTEGRATION_RESOURCE) - .collect(Collectors.toList()); + integrationType + ).stream().map(TO_INTEGRATION_RESOURCE).collect(Collectors.toList()); } @Override @@ -217,36 +217,33 @@ public boolean testConnection(Long integrationId, String projectName) { Project project = projectRepository.findByName(projectName) .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, projectName)); - Integration integration = integrationRepository.findByIdAndProjectId(integrationId, - project.getId()) - .orElseGet(() -> integrationRepository.findGlobalById(integrationId) - .orElseThrow( + Integration integration = + integrationRepository.findByIdAndProjectId(integrationId, project.getId()).orElseGet( + () -> integrationRepository.findGlobalById(integrationId).orElseThrow( () -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, integrationId))); - IntegrationService integrationService = integrationServiceMapping.getOrDefault( - integration.getType().getName(), - this.basicIntegrationService - ); + IntegrationService integrationService = + integrationServiceMapping.getOrDefault(integration.getType().getName(), + this.basicIntegrationService + ); return integrationService.checkConnection(integration); } @Override public boolean testConnection(Long integrationId) { - Integration integration = integrationRepository.findGlobalById(integrationId) - .orElseThrow( - () -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, integrationId)); + Integration integration = integrationRepository.findGlobalById(integrationId).orElseThrow( + () -> new ReportPortalException(ErrorType.INTEGRATION_NOT_FOUND, integrationId)); - IntegrationService integrationService = integrationServiceMapping.getOrDefault( - integration.getType().getName(), - this.basicIntegrationService - ); + IntegrationService integrationService = + integrationServiceMapping.getOrDefault(integration.getType().getName(), + this.basicIntegrationService + ); return integrationService.checkConnection(integration); } private Optional getGlobalIntegrationByIntegrationTypeIds( List integrationTypeIds) { - return integrationRepository.findAllGlobalInIntegrationTypeIds(integrationTypeIds) - .stream() + return integrationRepository.findAllGlobalInIntegrationTypeIds(integrationTypeIds).stream() .filter(integration -> integration.getType().isEnabled() && integration.isEnabled()) .findFirst(); } @@ -255,13 +252,14 @@ private void validateIntegration(Integration integration) { BusinessRule.expect(integration, i -> integration.getType().isEnabled()) .verify(ErrorType.UNABLE_INTERACT_WITH_INTEGRATION, Suppliers.formattedSupplier("'{}' type integrations are disabled by Administrator", - integration.getType().getName()) - .get() + integration.getType().getName() + ).get() ); BusinessRule.expect(integration, Integration::isEnabled) .verify(ErrorType.UNABLE_INTERACT_WITH_INTEGRATION, Suppliers.formattedSupplier("Integration with ID = '{}' is disabled", - integration.getId()).get() + integration.getId() + ).get() ); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/CreatePluginHandler.java b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/CreatePluginHandler.java index d3b6e30433..8f2d6c78c2 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/CreatePluginHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/CreatePluginHandler.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.integration.plugin; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.EntryCreatedRS; import org.springframework.web.multipart.MultipartFile; /** @@ -25,12 +25,12 @@ */ public interface CreatePluginHandler { - /** - * Upload and start up the plugin - * - * @param pluginFile Plugin file - * @param user User that uploaded plugin - * @return {@link EntryCreatedRS} with the newly created {@link com.epam.ta.reportportal.entity.integration.IntegrationType#id} - */ - EntryCreatedRS uploadPlugin(MultipartFile pluginFile, ReportPortalUser user); + /** + * Upload and start up the plugin + * + * @param pluginFile Plugin file + * @param user User that uploaded plugin + * @return {@link EntryCreatedRS} with the newly created {@link com.epam.ta.reportportal.entity.integration.IntegrationType#id} + */ + EntryCreatedRS uploadPlugin(MultipartFile pluginFile, ReportPortalUser user); } diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/DeletePluginHandler.java b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/DeletePluginHandler.java index f0834476dc..2dcb7cb6c8 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/DeletePluginHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/DeletePluginHandler.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.integration.plugin; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * @author Ivan Budayeu diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/GetPluginHandler.java b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/GetPluginHandler.java index 0e3eaece79..e2e16d8357 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/GetPluginHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/GetPluginHandler.java @@ -16,7 +16,7 @@ package com.epam.ta.reportportal.core.integration.plugin; -import com.epam.ta.reportportal.ws.model.integration.IntegrationTypeResource; +import com.epam.ta.reportportal.model.integration.IntegrationTypeResource; import java.util.List; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/UpdatePluginHandler.java b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/UpdatePluginHandler.java index 6b1b3dffe0..45e64f01da 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/UpdatePluginHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/UpdatePluginHandler.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.core.integration.plugin; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.integration.UpdatePluginStateRQ; +import com.epam.ta.reportportal.model.integration.UpdatePluginStateRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * @author Ivan Budayeu diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/binary/PluginFilesProvider.java b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/binary/PluginFilesProvider.java index 20439cb983..09334d8595 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/binary/PluginFilesProvider.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/binary/PluginFilesProvider.java @@ -20,7 +20,7 @@ import com.epam.ta.reportportal.entity.attachment.BinaryData; import com.epam.ta.reportportal.entity.integration.IntegrationType; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.io.File; import java.io.IOException; import java.io.InputStream; diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/CreatePluginHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/CreatePluginHandlerImpl.java index ed9ff309cf..bc40d5e10d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/CreatePluginHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/CreatePluginHandlerImpl.java @@ -23,9 +23,9 @@ import com.epam.ta.reportportal.core.plugin.Pf4jPluginBox; import com.epam.ta.reportportal.entity.integration.IntegrationType; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.activity.PluginActivityResource; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.activity.PluginActivityResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.io.IOException; import java.io.InputStream; import org.apache.commons.lang3.StringUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/DeletePluginHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/DeletePluginHandlerImpl.java index caedb340e0..cc0a1b595f 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/DeletePluginHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/DeletePluginHandlerImpl.java @@ -27,9 +27,9 @@ import com.epam.ta.reportportal.entity.enums.ReservedIntegrationTypeEnum; import com.epam.ta.reportportal.entity.integration.IntegrationType; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.activity.PluginActivityResource; +import com.epam.ta.reportportal.model.activity.PluginActivityResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/GetPluginHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/GetPluginHandlerImpl.java index 1a0080020f..9a09b0cbec 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/GetPluginHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/GetPluginHandlerImpl.java @@ -18,8 +18,8 @@ import com.epam.ta.reportportal.core.integration.plugin.GetPluginHandler; import com.epam.ta.reportportal.dao.IntegrationTypeRepository; +import com.epam.ta.reportportal.model.integration.IntegrationTypeResource; import com.epam.ta.reportportal.ws.converter.converters.IntegrationTypeConverter; -import com.epam.ta.reportportal.ws.model.integration.IntegrationTypeResource; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; @@ -42,17 +42,13 @@ public GetPluginHandlerImpl(IntegrationTypeRepository integrationTypeRepository) @Override public List getPlugins() { - return integrationTypeRepository.findAllByOrderByCreationDate() - .stream() - .map(IntegrationTypeConverter.TO_RESOURCE) - .collect(Collectors.toList()); + return integrationTypeRepository.findAllByOrderByCreationDate().stream() + .map(IntegrationTypeConverter.TO_RESOURCE).collect(Collectors.toList()); } @Override public List getPublicPlugins() { - return integrationTypeRepository.findAllByAccessType(ACCESS_TYPE_PUBLIC_NAME) - .stream() - .map(IntegrationTypeConverter.TO_RESOURCE) - .collect(Collectors.toList()); + return integrationTypeRepository.findAllByAccessType(ACCESS_TYPE_PUBLIC_NAME).stream() + .map(IntegrationTypeConverter.TO_RESOURCE).collect(Collectors.toList()); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/PluginLoaderImpl.java b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/PluginLoaderImpl.java index f165d7241e..a4837d2261 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/PluginLoaderImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/PluginLoaderImpl.java @@ -31,7 +31,7 @@ import com.epam.ta.reportportal.filesystem.DataStore; import com.epam.ta.reportportal.util.FeatureFlagHandler; import com.epam.ta.reportportal.ws.converter.builders.IntegrationTypeBuilder; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.io.File; import java.io.IOException; import java.io.InputStream; diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/UpdatePluginHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/UpdatePluginHandlerImpl.java index 34171e6231..3ccaace013 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/UpdatePluginHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/plugin/impl/UpdatePluginHandlerImpl.java @@ -26,10 +26,10 @@ import com.epam.ta.reportportal.entity.enums.ReservedIntegrationTypeEnum; import com.epam.ta.reportportal.entity.integration.IntegrationType; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.activity.PluginActivityResource; -import com.epam.ta.reportportal.ws.model.integration.UpdatePluginStateRQ; +import com.epam.ta.reportportal.model.activity.PluginActivityResource; +import com.epam.ta.reportportal.model.integration.UpdatePluginStateRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import org.apache.commons.lang3.BooleanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/util/BasicIntegrationServiceImpl.java b/src/main/java/com/epam/ta/reportportal/core/integration/util/BasicIntegrationServiceImpl.java index fb79c653f6..c332cbf785 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/util/BasicIntegrationServiceImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/util/BasicIntegrationServiceImpl.java @@ -16,7 +16,7 @@ package com.epam.ta.reportportal.core.integration.util; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; import static java.util.Optional.ofNullable; import com.epam.reportportal.extension.CommonPluginCommand; @@ -28,8 +28,8 @@ import com.epam.ta.reportportal.entity.integration.IntegrationParams; import com.epam.ta.reportportal.entity.integration.IntegrationType; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.integration.IntegrationRQ; import com.epam.ta.reportportal.ws.converter.builders.IntegrationBuilder; -import com.epam.ta.reportportal.ws.model.integration.IntegrationRQ; import java.time.LocalDateTime; import java.util.Map; import java.util.Optional; @@ -60,19 +60,18 @@ public BasicIntegrationServiceImpl(IntegrationRepository integrationRepository, @Override public Integration createIntegration(IntegrationRQ integrationRq, IntegrationType integrationType) { - return new IntegrationBuilder().withCreationDate(LocalDateTime.now()) - .withType(integrationType) - .withEnabled(integrationRq.getEnabled()) - .withName(integrationRq.getName()) - .withParams(new IntegrationParams( - retrieveCreateParams(integrationType.getName(), integrationRq.getIntegrationParams()))) - .get(); + return new IntegrationBuilder().withCreationDate(LocalDateTime.now()).withType(integrationType) + .withEnabled(integrationRq.getEnabled()).withName(integrationRq.getName()).withParams( + new IntegrationParams(retrieveCreateParams(integrationType.getName(), + integrationRq.getIntegrationParams() + ))).get(); } @Override public Integration updateIntegration(Integration integration, IntegrationRQ integrationRQ) { Map validParams = retrieveUpdatedParams(integration.getType().getName(), - integrationRQ.getIntegrationParams()); + integrationRQ.getIntegrationParams() + ); IntegrationParams combinedParams = getCombinedParams(integration, validParams); integration.setParams(combinedParams); ofNullable(integrationRQ.getEnabled()).ifPresent(integration::setEnabled); @@ -83,8 +82,8 @@ public Integration updateIntegration(Integration integration, IntegrationRQ inte @Override public Map retrieveCreateParams(String integrationType, Map integrationParams) { - final Optional> pluginCommand = getCommonCommand(integrationType, - RETRIEVE_CREATE_PARAMS); + final Optional> pluginCommand = + getCommonCommand(integrationType, RETRIEVE_CREATE_PARAMS); if (pluginCommand.isPresent()) { return (Map) pluginCommand.get().executeCommand(integrationParams); } @@ -94,8 +93,8 @@ public Map retrieveCreateParams(String integrationType, @Override public Map retrieveUpdatedParams(String integrationType, Map integrationParams) { - final Optional> pluginCommand = getCommonCommand(integrationType, - RETRIEVE_UPDATED_PARAMS); + final Optional> pluginCommand = + getCommonCommand(integrationType, RETRIEVE_UPDATED_PARAMS); if (pluginCommand.isPresent()) { return (Map) pluginCommand.get().executeCommand(integrationParams); } @@ -104,8 +103,8 @@ public Map retrieveUpdatedParams(String integrationType, @Override public boolean checkConnection(Integration integration) { - final Optional> pluginCommand = getIntegrationCommand( - integration.getType().getName(), TEST_CONNECTION_COMMAND); + final Optional> pluginCommand = + getIntegrationCommand(integration.getType().getName(), TEST_CONNECTION_COMMAND); if (pluginCommand.isPresent()) { return (Boolean) pluginCommand.get() .executeCommand(integration, integration.getParams().getParams()); @@ -114,21 +113,21 @@ public boolean checkConnection(Integration integration) { } private Optional> getIntegrationCommand(String integration, String commandName) { - ReportPortalExtensionPoint pluginInstance = pluginBox.getInstance(integration, - ReportPortalExtensionPoint.class) - .orElseThrow( + ReportPortalExtensionPoint pluginInstance = + pluginBox.getInstance(integration, ReportPortalExtensionPoint.class).orElseThrow( () -> new ReportPortalException(BAD_REQUEST_ERROR, "Plugin for {} isn't installed", - integration)); + integration + )); return ofNullable(pluginInstance.getIntegrationCommand(commandName)); } private Optional> getCommonCommand(String integration, String commandName) { - ReportPortalExtensionPoint pluginInstance = pluginBox.getInstance(integration, - ReportPortalExtensionPoint.class) - .orElseThrow( + ReportPortalExtensionPoint pluginInstance = + pluginBox.getInstance(integration, ReportPortalExtensionPoint.class).orElseThrow( () -> new ReportPortalException(BAD_REQUEST_ERROR, "Plugin for {} isn't installed", - integration)); + integration + )); return ofNullable(pluginInstance.getCommonCommand(commandName)); } diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/util/BtsIntegrationService.java b/src/main/java/com/epam/ta/reportportal/core/integration/util/BtsIntegrationService.java index db252edcc9..9539903560 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/util/BtsIntegrationService.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/util/BtsIntegrationService.java @@ -16,7 +16,7 @@ package com.epam.ta.reportportal.core.integration.util; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; -import static com.epam.ta.reportportal.ws.model.ErrorType.UNABLE_INTERACT_WITH_INTEGRATION; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.UNABLE_INTERACT_WITH_INTEGRATION; import com.epam.reportportal.extension.bugtracking.BtsExtension; import com.epam.ta.reportportal.commons.validation.Suppliers; @@ -26,7 +26,7 @@ import com.epam.ta.reportportal.entity.enums.AuthType; import com.epam.ta.reportportal.entity.integration.Integration; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Maps; import java.util.Map; import java.util.Optional; diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/util/EmailServerIntegrationService.java b/src/main/java/com/epam/ta/reportportal/core/integration/util/EmailServerIntegrationService.java index 595012e21e..6fce8a6926 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/util/EmailServerIntegrationService.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/util/EmailServerIntegrationService.java @@ -18,8 +18,8 @@ import static com.epam.ta.reportportal.commons.validation.BusinessRule.fail; import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; -import static com.epam.ta.reportportal.ws.model.ErrorType.EMAIL_CONFIGURATION_IS_INCORRECT; -import static com.epam.ta.reportportal.ws.model.ErrorType.FORBIDDEN_OPERATION; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.EMAIL_CONFIGURATION_IS_INCORRECT; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FORBIDDEN_OPERATION; import static java.util.Optional.ofNullable; import com.epam.ta.reportportal.commons.validation.BusinessRule; @@ -31,7 +31,7 @@ import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.util.email.EmailService; import com.epam.ta.reportportal.util.email.MailServiceFactory; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Maps; import com.mchange.lang.IntegerUtils; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/util/IntegrationService.java b/src/main/java/com/epam/ta/reportportal/core/integration/util/IntegrationService.java index 8aa41b60e7..10f44ea624 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/util/IntegrationService.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/util/IntegrationService.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.entity.integration.Integration; import com.epam.ta.reportportal.entity.integration.IntegrationType; -import com.epam.ta.reportportal.ws.model.integration.IntegrationRQ; +import com.epam.ta.reportportal.model.integration.IntegrationRQ; import java.util.Map; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/util/SauceLabsIntegrationService.java b/src/main/java/com/epam/ta/reportportal/core/integration/util/SauceLabsIntegrationService.java index 5e48b9d2b5..05f7cd2f4b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/util/SauceLabsIntegrationService.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/util/SauceLabsIntegrationService.java @@ -19,7 +19,7 @@ import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.core.integration.util.property.SauceLabsProperties.ACCESS_TOKEN; import static com.epam.ta.reportportal.core.integration.util.property.SauceLabsProperties.USERNAME; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; import com.epam.ta.reportportal.core.plugin.PluginBox; import com.epam.ta.reportportal.dao.IntegrationRepository; diff --git a/src/main/java/com/epam/ta/reportportal/core/integration/util/validator/IntegrationValidator.java b/src/main/java/com/epam/ta/reportportal/core/integration/util/validator/IntegrationValidator.java index 9ad4eea6b3..4b4fa0ca0e 100644 --- a/src/main/java/com/epam/ta/reportportal/core/integration/util/validator/IntegrationValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/integration/util/validator/IntegrationValidator.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.entity.integration.Integration; import com.epam.ta.reportportal.entity.integration.IntegrationType; import com.epam.ta.reportportal.entity.project.Project; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Objects; import org.apache.commons.lang3.StringUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/DeleteTestItemHandler.java b/src/main/java/com/epam/ta/reportportal/core/item/DeleteTestItemHandler.java index af63784c47..4c5ef18c1d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/DeleteTestItemHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/DeleteTestItemHandler.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.item; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.Collection; import java.util.List; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/ExternalTicketHandler.java b/src/main/java/com/epam/ta/reportportal/core/item/ExternalTicketHandler.java index 98d67d87ad..50366a7aea 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/ExternalTicketHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/ExternalTicketHandler.java @@ -18,8 +18,8 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.item.issue.IssueEntity; -import com.epam.ta.reportportal.ws.model.issue.Issue; -import com.epam.ta.reportportal.ws.model.item.UnlinkExternalIssueRQ; +import com.epam.ta.reportportal.model.item.UnlinkExternalIssueRQ; +import com.epam.ta.reportportal.ws.reporting.Issue; import java.util.List; import java.util.Set; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/FinishTestItemHandler.java b/src/main/java/com/epam/ta/reportportal/core/item/FinishTestItemHandler.java index 52a1671278..5d4f84e113 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/FinishTestItemHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/FinishTestItemHandler.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.core.item; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * Handler for finish test item operation diff --git a/src/main/java/com/epam/ta/reportportal/core/item/GetTestItemHandler.java b/src/main/java/com/epam/ta/reportportal/core/item/GetTestItemHandler.java index a85cdc9a22..38dbf79c91 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/GetTestItemHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/GetTestItemHandler.java @@ -24,8 +24,8 @@ import com.epam.ta.reportportal.entity.filter.UserFilter; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.TestItemResource; -import com.epam.ta.reportportal.ws.model.statistics.StatisticsResource; +import com.epam.ta.reportportal.ws.reporting.StatisticsResource; +import com.epam.ta.reportportal.ws.reporting.TestItemResource; import java.util.List; import java.util.Map; import javax.annotation.Nullable; @@ -64,9 +64,8 @@ TestItemResource getTestItem(String testItemId, ReportPortalUser.ProjectDetails * @return {@link Iterable} of the {@link TestItemResource} */ Iterable getTestItems(Queryable filter, Pageable pageable, - ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user, @Nullable Long launchId, @Nullable Long filterId, boolean isLatest, - int launchesLimit); + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, + @Nullable Long launchId, @Nullable Long filterId, boolean isLatest, int launchesLimit); /** * Gets {@link TestItem} instances @@ -78,8 +77,8 @@ Iterable getTestItems(Queryable filter, Pageable pageable, * @return {@link Iterable} of the {@link TestItemResource} */ Iterable getTestItemsByProvider(Queryable filter, Pageable pageable, - ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user, Map params); + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, + Map params); /** * Gets accumulated statistics of items by data provider @@ -125,8 +124,7 @@ StatisticsResource getStatisticsByProvider(Queryable filter, * @return {@link List} of the {@link ItemAttribute#getKey()} */ List getAttributeKeys(Long launchFilterId, boolean isLatest, int launchesLimit, - ReportPortalUser.ProjectDetails projectDetails, - String keyPart); + ReportPortalUser.ProjectDetails projectDetails, String keyPart); /** * Get specified attribute keys diff --git a/src/main/java/com/epam/ta/reportportal/core/item/StartTestItemHandler.java b/src/main/java/com/epam/ta/reportportal/core/item/StartTestItemHandler.java index af72cf97a3..7d86d4f0fb 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/StartTestItemHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/StartTestItemHandler.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.core.item; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.item.ItemCreatedRS; +import com.epam.ta.reportportal.ws.reporting.ItemCreatedRS; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; /** * Handler for start launch operation diff --git a/src/main/java/com/epam/ta/reportportal/core/item/TestItemService.java b/src/main/java/com/epam/ta/reportportal/core/item/TestItemService.java index 3a35654534..87e8c2867b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/TestItemService.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/TestItemService.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/UpdateTestItemHandler.java b/src/main/java/com/epam/ta/reportportal/core/item/UpdateTestItemHandler.java index 8cb6dcbac9..7007168b3b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/UpdateTestItemHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/UpdateTestItemHandler.java @@ -17,12 +17,12 @@ package com.epam.ta.reportportal.core.item; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.BulkInfoUpdateRQ; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.issue.DefineIssueRQ; -import com.epam.ta.reportportal.ws.model.issue.Issue; -import com.epam.ta.reportportal.ws.model.item.ExternalIssueRQ; -import com.epam.ta.reportportal.ws.model.item.UpdateTestItemRQ; +import com.epam.ta.reportportal.model.issue.DefineIssueRQ; +import com.epam.ta.reportportal.model.item.ExternalIssueRQ; +import com.epam.ta.reportportal.model.item.UpdateTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.BulkInfoUpdateRQ; +import com.epam.ta.reportportal.ws.reporting.Issue; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.List; /** @@ -53,8 +53,7 @@ List defineTestItemsIssues(ReportPortalUser.ProjectDetails projectDetails * @return OperationCompletionRS */ OperationCompletionRS updateTestItem(ReportPortalUser.ProjectDetails projectDetails, Long itemId, - UpdateTestItemRQ rq, - ReportPortalUser user); + UpdateTestItemRQ rq, ReportPortalUser user); /** * Add or remove external system issue link directly to the @@ -66,8 +65,7 @@ OperationCompletionRS updateTestItem(ReportPortalUser.ProjectDetails projectDeta * @return {@link List} of the {@link OperationCompletionRS} */ List processExternalIssues(ExternalIssueRQ request, - ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user); + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user); /** * Resets items issue to default state diff --git a/src/main/java/com/epam/ta/reportportal/core/item/history/ITestItemsHistoryService.java b/src/main/java/com/epam/ta/reportportal/core/item/history/ITestItemsHistoryService.java index 5df86ae3cb..a7cc1659e1 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/history/ITestItemsHistoryService.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/history/ITestItemsHistoryService.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.TestItemHistoryElement; +import com.epam.ta.reportportal.model.TestItemHistoryElement; import java.util.List; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/item/history/TestItemsHistoryHandler.java b/src/main/java/com/epam/ta/reportportal/core/item/history/TestItemsHistoryHandler.java index 0b6ccb81cd..a201d226f0 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/history/TestItemsHistoryHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/history/TestItemsHistoryHandler.java @@ -19,7 +19,7 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Queryable; import com.epam.ta.reportportal.core.item.impl.history.param.HistoryRequestParams; -import com.epam.ta.reportportal.ws.model.TestItemHistoryElement; +import com.epam.ta.reportportal.model.TestItemHistoryElement; import org.springframework.data.domain.Pageable; /** @@ -41,7 +41,7 @@ public interface TestItemsHistoryHandler { * @return {@link Iterable} of {@link TestItemHistoryElement} */ Iterable getItemsHistory(ReportPortalUser.ProjectDetails projectDetails, - Queryable filter, Pageable pageable, - HistoryRequestParams historyRequestParams, ReportPortalUser user); + Queryable filter, Pageable pageable, HistoryRequestParams historyRequestParams, + ReportPortalUser user); } \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/core/item/identity/IdentityUtil.java b/src/main/java/com/epam/ta/reportportal/core/item/identity/IdentityUtil.java index 225c02851d..23d7bc19ac 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/identity/IdentityUtil.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/identity/IdentityUtil.java @@ -2,7 +2,7 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/DeleteTestItemHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/DeleteTestItemHandlerImpl.java index 38b6dc7fb9..f90708fe38 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/DeleteTestItemHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/DeleteTestItemHandlerImpl.java @@ -20,10 +20,10 @@ import static com.epam.ta.reportportal.commons.Predicates.not; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.FORBIDDEN_OPERATION; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_IS_NOT_FINISHED; -import static com.epam.ta.reportportal.ws.model.ErrorType.TEST_ITEM_IS_NOT_FINISHED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FORBIDDEN_OPERATION; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_IS_NOT_FINISHED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.TEST_ITEM_IS_NOT_FINISHED; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; @@ -47,8 +47,8 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.common.collect.Sets; import java.util.Collection; import java.util.List; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/ExternalTicketHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/ExternalTicketHandlerImpl.java index 03377e97ba..1c2b9bb067 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/ExternalTicketHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/ExternalTicketHandlerImpl.java @@ -25,9 +25,10 @@ import com.epam.ta.reportportal.entity.bts.Ticket; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.item.issue.IssueEntity; +import com.epam.ta.reportportal.model.item.UnlinkExternalIssueRQ; import com.epam.ta.reportportal.ws.converter.converters.TicketConverter; -import com.epam.ta.reportportal.ws.model.issue.Issue; -import com.epam.ta.reportportal.ws.model.item.UnlinkExternalIssueRQ; +import com.epam.ta.reportportal.ws.reporting.Issue; +import com.epam.ta.reportportal.ws.reporting.Issue.ExternalSystemIssue; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; @@ -82,19 +83,17 @@ public void updateLinking(String submitter, IssueEntity issueEntity, /** * Finds tickets that are existed in db and removes them from request. * - * @param externalIssues {@link - * com.epam.ta.reportportal.ws.model.issue.Issue.ExternalSystemIssue} + * @param externalIssues {@link com.epam.ta.reportportal.ws.reporting.Issue.ExternalSystemIssue} * @return List of existed tickets in db. */ - private List collectExistedTickets(Collection externalIssues) { + private List collectExistedTickets(Collection externalIssues) { if (CollectionUtils.isEmpty(externalIssues)) { return Collections.emptyList(); } - List existedTickets = ticketRepository.findByTicketIdIn(externalIssues.stream() - .map(Issue.ExternalSystemIssue::getTicketId) - .collect(toList())); - List existedTicketsIds = existedTickets.stream().map(Ticket::getTicketId) - .collect(toList()); + List existedTickets = ticketRepository.findByTicketIdIn( + externalIssues.stream().map(Issue.ExternalSystemIssue::getTicketId).collect(toList())); + List existedTicketsIds = + existedTickets.stream().map(Ticket::getTicketId).collect(toList()); externalIssues.removeIf(it -> existedTicketsIds.contains(it.getTicketId())); return existedTickets; } @@ -102,8 +101,7 @@ private List collectExistedTickets(Collection /** * TODO document this * - * @param externalIssues {@link - * com.epam.ta.reportportal.ws.model.issue.Issue.ExternalSystemIssue} + * @param externalIssues {@link com.epam.ta.reportportal.ws.reporting.Issue.ExternalSystemIssue} * @param username {@link com.epam.ta.reportportal.entity.user.User#login} * @return {@link Set} of the {@link Ticket} */ @@ -114,7 +112,8 @@ private Set collectTickets(Collection externa } return externalIssues.stream().map(it -> { Ticket ticket; - Optional ticketOptional = ticketRepository.findByTicketId(it.getTicketId()); + Optional ticketOptional = + ticketRepository.findByTicketIdAndBtsProject(it.getTicketId(), it.getBtsProject()); if (ticketOptional.isPresent()) { ticket = ticketOptional.get(); ticket.setUrl(it.getUrl()); @@ -126,9 +125,8 @@ private Set collectTickets(Collection externa } ticket.setSubmitter(username); ticket.setSubmitDate(ofNullable(it.getSubmitDate()).map( - millis -> LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), - ZoneOffset.UTC - )).orElse(LocalDateTime.now())); + millis -> LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneOffset.UTC)) + .orElse(LocalDateTime.now())); return ticket; }).collect(toSet()); } diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerAsyncImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerAsyncImpl.java index 04dd74a2b7..40cdbd45ad 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerAsyncImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerAsyncImpl.java @@ -24,9 +24,9 @@ import com.epam.ta.reportportal.core.item.FinishTestItemHandler; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.util.ReportingQueueService; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.epam.ta.reportportal.ws.rabbit.MessageHeaders; import com.epam.ta.reportportal.ws.rabbit.RequestType; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerImpl.java index 986cbab87c..70fc6c41f9 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerImpl.java @@ -35,11 +35,11 @@ import static com.epam.ta.reportportal.entity.project.ProjectRole.PROJECT_MANAGER; import static com.epam.ta.reportportal.util.Predicates.ITEM_CAN_BE_INDEXED; import static com.epam.ta.reportportal.ws.converter.converters.TestItemConverter.TO_ACTIVITY_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.AMBIGUOUS_TEST_ITEM_STATUS; -import static com.epam.ta.reportportal.ws.model.ErrorType.FINISH_ITEM_NOT_ALLOWED; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.TEST_ITEM_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.AMBIGUOUS_TEST_ITEM_STATUS; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FINISH_ITEM_NOT_ALLOWED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.TEST_ITEM_NOT_FOUND; import static java.util.Optional.ofNullable; import com.epam.ta.reportportal.commons.Preconditions; @@ -68,12 +68,12 @@ import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.jooq.enums.JStatusEnum; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; import com.epam.ta.reportportal.ws.converter.builders.TestItemBuilder; import com.epam.ta.reportportal.ws.converter.converters.IssueConverter; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; -import com.epam.ta.reportportal.ws.model.issue.Issue; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.Issue; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Collections; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/GetTestItemHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/GetTestItemHandlerImpl.java index 75e583a81b..42a82b801a 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/GetTestItemHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/GetTestItemHandlerImpl.java @@ -16,6 +16,14 @@ package com.epam.ta.reportportal.core.item.impl; +import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_ID; +import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_PROJECT_ID; +import static com.epam.ta.reportportal.commons.querygen.constant.LaunchCriteriaConstant.CRITERIA_LAUNCH_MODE; +import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; +import static com.epam.ta.reportportal.entity.project.ProjectRole.OPERATOR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static java.util.stream.Collectors.toList; + import com.epam.ta.reportportal.commons.Predicates; import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Condition; @@ -46,28 +54,23 @@ import com.epam.ta.reportportal.ws.converter.utils.ResourceUpdater; import com.epam.ta.reportportal.ws.converter.utils.ResourceUpdaterProvider; import com.epam.ta.reportportal.ws.converter.utils.item.content.TestItemUpdaterContent; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.TestItemResource; -import com.epam.ta.reportportal.ws.model.statistics.StatisticsResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.StatisticsResource; +import com.epam.ta.reportportal.ws.reporting.TestItemResource; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import javax.annotation.Nullable; import org.apache.commons.lang3.tuple.Pair; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import javax.annotation.Nullable; -import java.util.*; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_ID; -import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_PROJECT_ID; -import static com.epam.ta.reportportal.commons.querygen.constant.LaunchCriteriaConstant.CRITERIA_LAUNCH_MODE; -import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; -import static com.epam.ta.reportportal.entity.project.ProjectRole.OPERATOR; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static java.util.stream.Collectors.toList; - /** * GET operations for {@link TestItem}
* Default implementation @@ -78,253 +81,256 @@ @Service class GetTestItemHandlerImpl implements GetTestItemHandler { - public static final String PROVIDER_TYPE_PARAM = "providerType"; - - private final TestItemRepository testItemRepository; - - private final TestItemService testItemService; - - private final LaunchAccessValidator launchAccessValidator; - - private final ItemAttributeRepository itemAttributeRepository; - - private final List> resourceUpdaterProviders; - - private final TicketRepository ticketRepository; - - private final UserFilterRepository filterRepository; - - @Autowired - private Map testItemDataProviders; - - @Autowired - public GetTestItemHandlerImpl(TestItemRepository testItemRepository, TestItemService testItemService, - LaunchAccessValidator launchAccessValidator, ItemAttributeRepository itemAttributeRepository, - List> resourceUpdaterProviders, - TicketRepository ticketRepository, UserFilterRepository filterRepository) { - this.testItemRepository = testItemRepository; - this.testItemService = testItemService; - this.launchAccessValidator = launchAccessValidator; - this.itemAttributeRepository = itemAttributeRepository; - this.resourceUpdaterProviders = resourceUpdaterProviders; - this.ticketRepository = ticketRepository; - this.filterRepository = filterRepository; - } - - @Override - public TestItemResource getTestItem(String testItemId, ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { - TestItem testItem; - try { - testItem = testItemRepository.findById(Long.parseLong(testItemId)) - .orElseThrow(() -> new ReportPortalException(ErrorType.TEST_ITEM_NOT_FOUND, testItemId)); - } catch (NumberFormatException e) { - testItem = testItemRepository.findByUuid(testItemId) - .orElseThrow(() -> new ReportPortalException(ErrorType.TEST_ITEM_NOT_FOUND, testItemId)); - } - - Launch launch = testItemService.getEffectiveLaunch(testItem); - launchAccessValidator.validate(launch.getId(), projectDetails, user); - - List> resourceUpdaters = getResourceUpdaters(projectDetails.getProjectId(), - Collections.singletonList(testItem) - ); - TestItemResource testItemResource = TestItemConverter.TO_RESOURCE.apply(testItem); - resourceUpdaters.forEach(updater -> updater.updateResource(testItemResource)); - return testItemResource; - } - - @Override - public Iterable getTestItems(Queryable filter, Pageable pageable, ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user, @Nullable Long launchId, @Nullable Long filterId, boolean isLatest, int launchesLimit) { - - Optional launchIdOptional = Optional.ofNullable(launchId); - Optional filterIdOptional = Optional.ofNullable(filterId); - - Page testItemPage = filterIdOptional.map(launchFilterId -> { - validateProjectRole(projectDetails, user); - return getItemsWithLaunchesFiltering(filter, pageable, projectDetails, launchFilterId, isLatest, launchesLimit); - }).orElseGet(() -> launchIdOptional.map(id -> { - launchAccessValidator.validate(id, projectDetails, user); - return testItemRepository.findByFilter(filter, pageable); - }).orElseThrow(() -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, "Neither launch nor filter id specified."))); - - return PagedResourcesAssembler.pageMultiConverter(items -> { - List> resourceUpdaters = getResourceUpdaters(projectDetails.getProjectId(), - testItemPage.getContent() - ); - return items.stream().map(item -> { - TestItemResource testItemResource = TestItemConverter.TO_RESOURCE.apply(item); - resourceUpdaters.forEach(updater -> updater.updateResource(testItemResource)); - return testItemResource; - }).collect(toList()); - }).apply(testItemPage); - } - - @Override - public Iterable getTestItemsByProvider(Queryable filter, Pageable pageable, - ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, Map params) { - DataProviderType dataProviderType = DataProviderType.findByName(params.get(PROVIDER_TYPE_PARAM)) - .orElseThrow(() -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, - "Test item data provider base is not specified. Allowed data provider {}", - DataProviderType.values() - )); - - Page testItemPage = testItemDataProviders.get(dataProviderType) - .getTestItems(filter, pageable, projectDetails, user, params); - - return PagedResourcesAssembler.pageMultiConverter(items -> { - List> resourceUpdaters = getResourceUpdaters(projectDetails.getProjectId(), - testItemPage.getContent() - ); - return items.stream().map(item -> { - TestItemResource testItemResource = TestItemConverter.TO_RESOURCE.apply(item); - resourceUpdaters.forEach(updater -> updater.updateResource(testItemResource)); - return testItemResource; - }).collect(toList()); - }).apply(testItemPage); - } - - @Override - public StatisticsResource getStatisticsByProvider(Queryable filter, ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser reportPortalUser, Map params) { - DataProviderType dataProviderType = DataProviderType.findByName(params.get(PROVIDER_TYPE_PARAM)) - .orElseThrow(() -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, - "Test item data provider base is not specified. Allowed data provider {}", - DataProviderType.values() - )); - return StatisticsConverter.TO_RESOURCE.apply(testItemDataProviders.get(dataProviderType) - .accumulateStatistics(filter, projectDetails, reportPortalUser, params)); - } - - protected void validateProjectRole(ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { - if (user.getUserRole() != UserRole.ADMINISTRATOR) { - expect(projectDetails.getProjectRole() == OPERATOR, Predicate.isEqual(false)).verify(ACCESS_DENIED); - } - } - - private Page getItemsWithLaunchesFiltering(Queryable testItemFilter, Pageable testItemPageable, - ReportPortalUser.ProjectDetails projectDetails, Long launchFilterId, boolean isLatest, int launchesLimit) { - - UserFilter userFilter = filterRepository.findByIdAndProjectId(launchFilterId, projectDetails.getProjectId()) - .orElseThrow(() -> new ReportPortalException(ErrorType.USER_FILTER_NOT_FOUND_IN_PROJECT, - launchFilterId, - projectDetails.getProjectName() - )); - - Pair queryablePair = DefaultLaunchFilterProvider.createDefaultLaunchQueryablePair(projectDetails, - userFilter, - launchesLimit - ); - - return testItemRepository.findByFilter(isLatest, - queryablePair.getKey(), - testItemFilter, - queryablePair.getValue(), - testItemPageable - ); - } - - private List> getResourceUpdaters(Long projectId, List testItems) { - return resourceUpdaterProviders.stream() - .map(retriever -> retriever.retrieve(TestItemUpdaterContent.of(projectId, testItems))) - .collect(toList()); - - } - - @Override - public List getTicketIds(Long launchId, String term) { - BusinessRule.expect(term.length() > 2, Predicates.equalTo(true)).verify(ErrorType.INCORRECT_FILTER_PARAMETERS, - Suppliers.formattedSupplier("Length of the filtering string '{}' is less than 3 symbols", term) - ); - return ticketRepository.findByLaunchIdAndTerm(launchId, term); - } - - @Override - public List getTicketIds(ReportPortalUser.ProjectDetails projectDetails, String term) { - BusinessRule.expect(term.length() > 0, Predicates.equalTo(true)).verify(ErrorType.INCORRECT_FILTER_PARAMETERS, - Suppliers.formattedSupplier("Length of the filtering string '{}' is less than 1 symbols", term) - ); - return ticketRepository.findByProjectIdAndTerm(projectDetails.getProjectId(), term); - } - - @Override - public List getAttributeKeys(Long launchFilterId, boolean isLatest, int launchesLimit, - ReportPortalUser.ProjectDetails projectDetails, String keyPart) { - - UserFilter userFilter = filterRepository.findByIdAndProjectId(launchFilterId, projectDetails.getProjectId()) - .orElseThrow(() -> new ReportPortalException(ErrorType.USER_FILTER_NOT_FOUND_IN_PROJECT, - launchFilterId, - projectDetails.getProjectName() - )); - - Pair queryablePair = DefaultLaunchFilterProvider.createDefaultLaunchQueryablePair(projectDetails, - userFilter, - launchesLimit - ); - return itemAttributeRepository.findAllKeysByLaunchFilter(queryablePair.getKey(), - queryablePair.getValue(), - isLatest, - keyPart, - false - ); - } - - @Override - public List getAttributeKeys(Long launchId, String value) { - return itemAttributeRepository.findTestItemAttributeKeys(launchId, value, false); - } - - @Override - public List getAttributeValues(Long launchId, String key, String value) { - return itemAttributeRepository.findTestItemAttributeValues(launchId, key, value, false); - } - - @Override - public List getAttributeKeys(ReportPortalUser.ProjectDetails projectDetails, String launchName, String keyPart) { - return itemAttributeRepository.findTestItemKeysByProjectIdAndLaunchName(projectDetails.getProjectId(), launchName, keyPart, false); - } - - @Override - public List getAttributeValues(ReportPortalUser.ProjectDetails projectDetails, String launchName, String key, - String valuePart) { - return itemAttributeRepository.findTestItemValuesByProjectIdAndLaunchName( - projectDetails.getProjectId(), - launchName, - key, - valuePart, - false - ); - } - - @Override - public List getTestItems(Long[] ids, ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { - List items; - if (user.getUserRole() != UserRole.ADMINISTRATOR) { - items = testItemRepository.findByFilter(getItemsFilter(ids, projectDetails)); - } else { - items = testItemRepository.findAllById(Arrays.asList(ids)); - } - List> resourceUpdaters = getResourceUpdaters(projectDetails.getProjectId(), items); - return items.stream().map(item -> { - TestItemResource testItemResource = TestItemConverter.TO_RESOURCE.apply(item); - resourceUpdaters.forEach(updater -> updater.updateResource(testItemResource)); - return testItemResource; - }).collect(toList()); - } - - private Filter getItemsFilter(Long[] ids, ReportPortalUser.ProjectDetails projectDetails) { - final Filter filter = Filter.builder() - .withTarget(TestItem.class) - .withCondition(FilterCondition.builder().eq(CRITERIA_PROJECT_ID, String.valueOf(projectDetails.getProjectId())).build()) - .withCondition(FilterCondition.builder() - .withSearchCriteria(CRITERIA_ID) - .withCondition(Condition.IN) - .withValue(Arrays.stream(ids).map(Object::toString).collect(Collectors.joining(","))) - .build()) - .build(); - return projectDetails.getProjectRole() != ProjectRole.OPERATOR ? - filter : - filter.withCondition(FilterCondition.builder().eq(CRITERIA_LAUNCH_MODE, LaunchModeEnum.DEFAULT.name()).build()); - } + public static final String PROVIDER_TYPE_PARAM = "providerType"; + + private final TestItemRepository testItemRepository; + + private final TestItemService testItemService; + + private final LaunchAccessValidator launchAccessValidator; + + private final ItemAttributeRepository itemAttributeRepository; + + private final List> + resourceUpdaterProviders; + + private final TicketRepository ticketRepository; + + private final UserFilterRepository filterRepository; + + @Autowired + private Map testItemDataProviders; + + @Autowired + public GetTestItemHandlerImpl(TestItemRepository testItemRepository, + TestItemService testItemService, LaunchAccessValidator launchAccessValidator, + ItemAttributeRepository itemAttributeRepository, + List> resourceUpdaterProviders, + TicketRepository ticketRepository, UserFilterRepository filterRepository) { + this.testItemRepository = testItemRepository; + this.testItemService = testItemService; + this.launchAccessValidator = launchAccessValidator; + this.itemAttributeRepository = itemAttributeRepository; + this.resourceUpdaterProviders = resourceUpdaterProviders; + this.ticketRepository = ticketRepository; + this.filterRepository = filterRepository; + } + + @Override + public TestItemResource getTestItem(String testItemId, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { + TestItem testItem; + try { + testItem = testItemRepository.findById(Long.parseLong(testItemId)) + .orElseThrow(() -> new ReportPortalException(ErrorType.TEST_ITEM_NOT_FOUND, testItemId)); + } catch (NumberFormatException e) { + testItem = testItemRepository.findByUuid(testItemId) + .orElseThrow(() -> new ReportPortalException(ErrorType.TEST_ITEM_NOT_FOUND, testItemId)); + } + + Launch launch = testItemService.getEffectiveLaunch(testItem); + launchAccessValidator.validate(launch.getId(), projectDetails, user); + + List> resourceUpdaters = + getResourceUpdaters(projectDetails.getProjectId(), Collections.singletonList(testItem)); + TestItemResource testItemResource = TestItemConverter.TO_RESOURCE.apply(testItem); + resourceUpdaters.forEach(updater -> updater.updateResource(testItemResource)); + return testItemResource; + } + + @Override + public Iterable getTestItems(Queryable filter, Pageable pageable, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, + @Nullable Long launchId, @Nullable Long filterId, boolean isLatest, int launchesLimit) { + + Optional launchIdOptional = Optional.ofNullable(launchId); + Optional filterIdOptional = Optional.ofNullable(filterId); + + Page testItemPage = filterIdOptional.map(launchFilterId -> { + validateProjectRole(projectDetails, user); + return getItemsWithLaunchesFiltering( + filter, pageable, projectDetails, launchFilterId, isLatest, launchesLimit); + }).orElseGet(() -> launchIdOptional.map(id -> { + launchAccessValidator.validate(id, projectDetails, user); + return testItemRepository.findByFilter(filter, pageable); + }).orElseThrow(() -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, + "Neither launch nor filter id specified." + ))); + + return PagedResourcesAssembler.pageMultiConverter(items -> { + List> resourceUpdaters = + getResourceUpdaters(projectDetails.getProjectId(), testItemPage.getContent()); + return items.stream().map(item -> { + TestItemResource testItemResource = TestItemConverter.TO_RESOURCE.apply(item); + resourceUpdaters.forEach(updater -> updater.updateResource(testItemResource)); + return testItemResource; + }).collect(toList()); + }).apply(testItemPage); + } + + @Override + public Iterable getTestItemsByProvider(Queryable filter, Pageable pageable, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, + Map params) { + DataProviderType dataProviderType = DataProviderType.findByName(params.get(PROVIDER_TYPE_PARAM)) + .orElseThrow(() -> new ReportPortalException( + ErrorType.BAD_REQUEST_ERROR, + "Test item data provider base is not specified. Allowed data provider {}", + DataProviderType.values() + )); + + Page testItemPage = testItemDataProviders.get(dataProviderType) + .getTestItems(filter, pageable, projectDetails, user, params); + + return PagedResourcesAssembler.pageMultiConverter(items -> { + List> resourceUpdaters = + getResourceUpdaters(projectDetails.getProjectId(), testItemPage.getContent()); + return items.stream().map(item -> { + TestItemResource testItemResource = TestItemConverter.TO_RESOURCE.apply(item); + resourceUpdaters.forEach(updater -> updater.updateResource(testItemResource)); + return testItemResource; + }).collect(toList()); + }).apply(testItemPage); + } + + @Override + public StatisticsResource getStatisticsByProvider(Queryable filter, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser reportPortalUser, + Map params) { + DataProviderType dataProviderType = DataProviderType.findByName(params.get(PROVIDER_TYPE_PARAM)) + .orElseThrow(() -> new ReportPortalException( + ErrorType.BAD_REQUEST_ERROR, + "Test item data provider base is not specified. Allowed data provider {}", + DataProviderType.values() + )); + return StatisticsConverter.TO_RESOURCE.apply(testItemDataProviders.get(dataProviderType) + .accumulateStatistics(filter, projectDetails, reportPortalUser, params)); + } + + protected void validateProjectRole(ReportPortalUser.ProjectDetails projectDetails, + ReportPortalUser user) { + if (user.getUserRole() != UserRole.ADMINISTRATOR) { + expect(projectDetails.getProjectRole() == OPERATOR, Predicate.isEqual(false)).verify( + ACCESS_DENIED); + } + } + + private Page getItemsWithLaunchesFiltering(Queryable testItemFilter, + Pageable testItemPageable, ReportPortalUser.ProjectDetails projectDetails, + Long launchFilterId, boolean isLatest, int launchesLimit) { + + UserFilter userFilter = + filterRepository.findByIdAndProjectId(launchFilterId, projectDetails.getProjectId()) + .orElseThrow(() -> new ReportPortalException(ErrorType.USER_FILTER_NOT_FOUND_IN_PROJECT, + launchFilterId, projectDetails.getProjectName() + )); + + Pair queryablePair = + DefaultLaunchFilterProvider.createDefaultLaunchQueryablePair(projectDetails, userFilter, + launchesLimit + ); + + return testItemRepository.findByFilter(isLatest, queryablePair.getKey(), testItemFilter, + queryablePair.getValue(), testItemPageable + ); + } + + private List> getResourceUpdaters(Long projectId, + List testItems) { + return resourceUpdaterProviders.stream() + .map(retriever -> retriever.retrieve(TestItemUpdaterContent.of(projectId, testItems))) + .collect(toList()); + + } + + @Override + public List getTicketIds(Long launchId, String term) { + BusinessRule.expect(term.length() > 2, Predicates.equalTo(true)) + .verify(ErrorType.INCORRECT_FILTER_PARAMETERS, Suppliers.formattedSupplier( + "Length of the filtering string '{}' is less than 3 symbols", term)); + return ticketRepository.findByLaunchIdAndTerm(launchId, term); + } + + @Override + public List getTicketIds(ReportPortalUser.ProjectDetails projectDetails, String term) { + BusinessRule.expect(term.length() > 0, Predicates.equalTo(true)) + .verify(ErrorType.INCORRECT_FILTER_PARAMETERS, Suppliers.formattedSupplier( + "Length of the filtering string '{}' is less than 1 symbols", term)); + return ticketRepository.findByProjectIdAndTerm(projectDetails.getProjectId(), term); + } + + @Override + public List getAttributeKeys(Long launchFilterId, boolean isLatest, int launchesLimit, + ReportPortalUser.ProjectDetails projectDetails, String keyPart) { + + UserFilter userFilter = + filterRepository.findByIdAndProjectId(launchFilterId, projectDetails.getProjectId()) + .orElseThrow(() -> new ReportPortalException(ErrorType.USER_FILTER_NOT_FOUND_IN_PROJECT, + launchFilterId, projectDetails.getProjectName() + )); + + Pair queryablePair = + DefaultLaunchFilterProvider.createDefaultLaunchQueryablePair(projectDetails, userFilter, + launchesLimit + ); + return itemAttributeRepository.findAllKeysByLaunchFilter(queryablePair.getKey(), + queryablePair.getValue(), isLatest, keyPart, false + ); + } + + @Override + public List getAttributeKeys(Long launchId, String value) { + return itemAttributeRepository.findTestItemAttributeKeys(launchId, value, false); + } + + @Override + public List getAttributeValues(Long launchId, String key, String value) { + return itemAttributeRepository.findTestItemAttributeValues(launchId, key, value, false); + } + + @Override + public List getAttributeKeys(ReportPortalUser.ProjectDetails projectDetails, + String launchName, String keyPart) { + return itemAttributeRepository.findTestItemKeysByProjectIdAndLaunchName( + projectDetails.getProjectId(), launchName, keyPart, false); + } + + @Override + public List getAttributeValues(ReportPortalUser.ProjectDetails projectDetails, + String launchName, String key, String valuePart) { + return itemAttributeRepository.findTestItemValuesByProjectIdAndLaunchName( + projectDetails.getProjectId(), launchName, key, valuePart, false); + } + + @Override + public List getTestItems(Long[] ids, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { + List items; + if (user.getUserRole() != UserRole.ADMINISTRATOR) { + items = testItemRepository.findByFilter(getItemsFilter(ids, projectDetails)); + } else { + items = testItemRepository.findAllById(Arrays.asList(ids)); + } + List> resourceUpdaters = + getResourceUpdaters(projectDetails.getProjectId(), items); + return items.stream().map(item -> { + TestItemResource testItemResource = TestItemConverter.TO_RESOURCE.apply(item); + resourceUpdaters.forEach(updater -> updater.updateResource(testItemResource)); + return testItemResource; + }).collect(toList()); + } + + private Filter getItemsFilter(Long[] ids, ReportPortalUser.ProjectDetails projectDetails) { + final Filter filter = Filter.builder().withTarget(TestItem.class).withCondition( + FilterCondition.builder() + .eq(CRITERIA_PROJECT_ID, String.valueOf(projectDetails.getProjectId())).build()) + .withCondition( + FilterCondition.builder().withSearchCriteria(CRITERIA_ID).withCondition(Condition.IN) + .withValue( + Arrays.stream(ids).map(Object::toString).collect(Collectors.joining(","))) + .build()).build(); + return projectDetails.getProjectRole() != ProjectRole.OPERATOR ? filter : filter.withCondition( + FilterCondition.builder().eq(CRITERIA_LAUNCH_MODE, LaunchModeEnum.DEFAULT.name()).build()); + } } diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/IssueTypeHandler.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/IssueTypeHandler.java index e8b4553b21..6cd80bdb40 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/IssueTypeHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/IssueTypeHandler.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.item.impl; import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; -import static com.epam.ta.reportportal.ws.model.ErrorType.FAILED_TEST_ITEM_ISSUE_TYPE_DEFINITION; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FAILED_TEST_ITEM_ISSUE_TYPE_DEFINITION; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toList; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/LaunchAccessValidatorImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/LaunchAccessValidatorImpl.java index 5ccf992ff4..7a27a7521d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/LaunchAccessValidatorImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/LaunchAccessValidatorImpl.java @@ -20,9 +20,9 @@ import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; import static com.epam.ta.reportportal.entity.project.ProjectRole.OPERATOR; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.FORBIDDEN_OPERATION; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FORBIDDEN_OPERATION; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_NOT_FOUND; import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.dao.LaunchRepository; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerAsyncImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerAsyncImpl.java index ffa9eef04d..44b9f7e811 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerAsyncImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerAsyncImpl.java @@ -21,8 +21,8 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.core.item.StartTestItemHandler; import com.epam.ta.reportportal.util.ReportingQueueService; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.item.ItemCreatedRS; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.ItemCreatedRS; import com.epam.ta.reportportal.ws.rabbit.MessageHeaders; import com.epam.ta.reportportal.ws.rabbit.RequestType; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerImpl.java index c53070507f..b34dad2357 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerImpl.java @@ -18,11 +18,11 @@ import static com.epam.ta.reportportal.commons.Predicates.equalTo; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; -import static com.epam.ta.reportportal.ws.model.ErrorType.CHILD_START_TIME_EARLIER_THAN_PARENT; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.TEST_ITEM_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.CHILD_START_TIME_EARLIER_THAN_PARENT; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.TEST_ITEM_NOT_FOUND; import static java.util.Optional.ofNullable; import static org.apache.commons.lang3.BooleanUtils.isTrue; @@ -44,8 +44,8 @@ import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.converter.builders.TestItemBuilder; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.item.ItemCreatedRS; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.ItemCreatedRS; import java.util.List; import java.util.Objects; import java.util.Optional; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/UpdateTestItemHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/UpdateTestItemHandlerImpl.java index e6f0742223..dfd80a6aa1 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/UpdateTestItemHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/UpdateTestItemHandlerImpl.java @@ -25,11 +25,11 @@ import static com.epam.ta.reportportal.util.ItemInfoUtils.extractAttributeResource; import static com.epam.ta.reportportal.util.Predicates.ITEM_CAN_BE_INDEXED; import static com.epam.ta.reportportal.ws.converter.converters.TestItemConverter.TO_ACTIVITY_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.FAILED_TEST_ITEM_ISSUE_TYPE_DEFINITION; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.TEST_ITEM_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FAILED_TEST_ITEM_ISSUE_TYPE_DEFINITION; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.TEST_ITEM_NOT_FOUND; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static java.util.stream.Collectors.toList; @@ -61,22 +61,22 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.issue.DefineIssueRQ; +import com.epam.ta.reportportal.model.issue.IssueDefinition; +import com.epam.ta.reportportal.model.item.ExternalIssueRQ; +import com.epam.ta.reportportal.model.item.LinkExternalIssueRQ; +import com.epam.ta.reportportal.model.item.UnlinkExternalIssueRQ; +import com.epam.ta.reportportal.model.item.UpdateTestItemRQ; import com.epam.ta.reportportal.util.ItemInfoUtils; import com.epam.ta.reportportal.ws.converter.builders.IssueEntityBuilder; import com.epam.ta.reportportal.ws.converter.builders.TestItemBuilder; import com.epam.ta.reportportal.ws.converter.converters.IssueConverter; import com.epam.ta.reportportal.ws.converter.converters.ItemAttributeConverter; -import com.epam.ta.reportportal.ws.model.BulkInfoUpdateRQ; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; -import com.epam.ta.reportportal.ws.model.issue.DefineIssueRQ; -import com.epam.ta.reportportal.ws.model.issue.Issue; -import com.epam.ta.reportportal.ws.model.issue.IssueDefinition; -import com.epam.ta.reportportal.ws.model.item.ExternalIssueRQ; -import com.epam.ta.reportportal.ws.model.item.LinkExternalIssueRQ; -import com.epam.ta.reportportal.ws.model.item.UnlinkExternalIssueRQ; -import com.epam.ta.reportportal.ws.model.item.UpdateTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.BulkInfoUpdateRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.Issue; import java.util.ArrayList; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/history/TestItemsHistoryHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/history/TestItemsHistoryHandlerImpl.java index 2540a28565..67e8c6fc19 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/history/TestItemsHistoryHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/history/TestItemsHistoryHandlerImpl.java @@ -19,9 +19,9 @@ import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_PROJECT_ID; import static com.epam.ta.reportportal.commons.querygen.constant.LaunchCriteriaConstant.CRITERIA_LAUNCH_MODE; import static com.epam.ta.reportportal.commons.querygen.constant.TestItemCriteriaConstant.CRITERIA_HAS_STATS; -import static com.epam.ta.reportportal.ws.model.ErrorType.UNABLE_LOAD_TEST_ITEM_HISTORY; import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_HISTORY_DEPTH_BOUND; import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_HISTORY_DEPTH_BOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.UNABLE_LOAD_TEST_ITEM_HISTORY; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toList; @@ -42,13 +42,13 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.item.history.TestItemHistory; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.TestItemHistoryElement; import com.epam.ta.reportportal.ws.converter.PagedResourcesAssembler; import com.epam.ta.reportportal.ws.converter.converters.TestItemConverter; import com.epam.ta.reportportal.ws.converter.utils.ResourceUpdater; import com.epam.ta.reportportal.ws.converter.utils.ResourceUpdaterProvider; import com.epam.ta.reportportal.ws.converter.utils.item.content.TestItemUpdaterContent; -import com.epam.ta.reportportal.ws.model.TestItemHistoryElement; -import com.epam.ta.reportportal.ws.model.TestItemResource; +import com.epam.ta.reportportal.ws.reporting.TestItemResource; import com.google.common.collect.Lists; import java.util.List; import java.util.Map; @@ -76,7 +76,8 @@ public class TestItemsHistoryHandlerImpl implements TestItemsHistoryHandler { private final TestItemRepository testItemRepository; private final HistoryProviderFactory historyProviderFactory; - private final List> resourceUpdaterProviders; + private final List> + resourceUpdaterProviders; @Autowired public TestItemsHistoryHandlerImpl(TestItemRepository testItemRepository, @@ -89,41 +90,33 @@ public TestItemsHistoryHandlerImpl(TestItemRepository testItemRepository, @Override public Iterable getItemsHistory( - ReportPortalUser.ProjectDetails projectDetails, Queryable filter, - Pageable pageable, HistoryRequestParams historyRequestParams, ReportPortalUser user) { + ReportPortalUser.ProjectDetails projectDetails, Queryable filter, Pageable pageable, + HistoryRequestParams historyRequestParams, ReportPortalUser user) { validateHistoryDepth(historyRequestParams.getHistoryDepth()); - CompositeFilter itemHistoryFilter = new CompositeFilter(Operator.AND, - filter, - Filter.builder() - .withTarget(filter.getTarget().getClazz()) - .withCondition(FilterCondition.builder() - .eq(CRITERIA_PROJECT_ID, String.valueOf(projectDetails.getProjectId())) - .build()) + CompositeFilter itemHistoryFilter = new CompositeFilter(Operator.AND, filter, + Filter.builder().withTarget(filter.getTarget().getClazz()).withCondition( + FilterCondition.builder() + .eq(CRITERIA_PROJECT_ID, String.valueOf(projectDetails.getProjectId())).build()) .withCondition( FilterCondition.builder().eq(CRITERIA_LAUNCH_MODE, LaunchModeEnum.DEFAULT.name()) - .build()) - .withCondition( - FilterCondition.builder().eq(CRITERIA_HAS_STATS, String.valueOf(Boolean.TRUE)) - .build()) + .build()).withCondition( + FilterCondition.builder().eq(CRITERIA_HAS_STATS, String.valueOf(Boolean.TRUE)).build()) .build() ); - Page testItemHistoryPage = historyProviderFactory.getProvider( - historyRequestParams) - .orElseThrow(() -> new ReportPortalException(UNABLE_LOAD_TEST_ITEM_HISTORY, - "Unable to find suitable history baseline provider" - )) - .provide(itemHistoryFilter, pageable, historyRequestParams, projectDetails, user, - !oldHistory); - - return buildHistoryElements( - oldHistory ? TestItemResource::getUniqueId - : testItemResource -> String.valueOf(testItemResource.getTestCaseHash()), - testItemHistoryPage, - projectDetails.getProjectId(), - pageable + Page testItemHistoryPage = + historyProviderFactory.getProvider(historyRequestParams).orElseThrow( + () -> new ReportPortalException(UNABLE_LOAD_TEST_ITEM_HISTORY, + "Unable to find suitable history baseline provider" + )).provide(itemHistoryFilter, pageable, historyRequestParams, projectDetails, user, + !oldHistory + ); + + return buildHistoryElements(oldHistory ? TestItemResource::getUniqueId : + testItemResource -> String.valueOf(testItemResource.getTestCaseHash()), testItemHistoryPage, + projectDetails.getProjectId(), pageable ); } @@ -132,11 +125,9 @@ private void validateHistoryDepth(int historyDepth) { Predicate greaterThan = t -> t > MIN_HISTORY_DEPTH_BOUND; Predicate lessThan = t -> t < MAX_HISTORY_DEPTH_BOUND; String historyDepthMessage = Suppliers.formattedSupplier( - "Items history depth should be greater than '{}' and lower than '{}'", - MIN_HISTORY_DEPTH_BOUND, - MAX_HISTORY_DEPTH_BOUND - ) - .get(); + "Items history depth should be greater than '{}' and lower than '{}'", + MIN_HISTORY_DEPTH_BOUND, MAX_HISTORY_DEPTH_BOUND + ).get(); BusinessRule.expect(historyDepth, greaterThan.and(lessThan)) .verify(UNABLE_LOAD_TEST_ITEM_HISTORY, historyDepthMessage); } @@ -145,13 +136,12 @@ private Iterable buildHistoryElements( Function groupingFunction, Page testItemHistoryPage, Long projectId, Pageable pageable) { - List testItems = testItemRepository.findAllById(testItemHistoryPage.getContent() - .stream() - .flatMap(history -> history.getItemIds().stream()) - .collect(toList())); + List testItems = testItemRepository.findAllById( + testItemHistoryPage.getContent().stream().flatMap(history -> history.getItemIds().stream()) + .collect(toList())); - List> resourceUpdaters = getResourceUpdaters(projectId, - testItems); + List> resourceUpdaters = + getResourceUpdaters(projectId, testItems); Map> itemsMapping = testItems.stream().map(item -> { TestItemResource testItemResource = TestItemConverter.TO_RESOURCE.apply(item); @@ -159,25 +149,19 @@ private Iterable buildHistoryElements( return testItemResource; }).collect(groupingBy(groupingFunction, toMap(TestItemResource::getItemId, res -> res))); - List testItemHistoryElements = testItemHistoryPage.getContent() - .stream() + List testItemHistoryElements = testItemHistoryPage.getContent().stream() .map(history -> ofNullable(itemsMapping.get(history.getGroupingField())).map(mapping -> { TestItemHistoryElement historyResource = new TestItemHistoryElement(); historyResource.setGroupingField(history.getGroupingField()); List resources = Lists.newArrayList(); - ofNullable(history.getItemIds()).ifPresent( - itemIds -> itemIds.forEach(itemId -> ofNullable(mapping.get(itemId)).ifPresent( - resources::add))); + ofNullable(history.getItemIds()).ifPresent(itemIds -> itemIds.forEach( + itemId -> ofNullable(mapping.get(itemId)).ifPresent(resources::add))); historyResource.setResources(resources); return historyResource; - })) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(toList()); + })).filter(Optional::isPresent).map(Optional::get).collect(toList()); - return PagedResourcesAssembler.pageConverter() - .apply(PageableExecutionUtils.getPage(testItemHistoryElements, - pageable, + return PagedResourcesAssembler.pageConverter().apply( + PageableExecutionUtils.getPage(testItemHistoryElements, pageable, testItemHistoryPage::getTotalElements )); diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/history/param/HistoryRequestParams.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/history/param/HistoryRequestParams.java index 368db777c4..0e1417780d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/history/param/HistoryRequestParams.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/history/param/HistoryRequestParams.java @@ -20,7 +20,7 @@ import com.epam.ta.reportportal.commons.validation.Suppliers; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Arrays; import java.util.Optional; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/ComparingBaselineHistoryProvider.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/ComparingBaselineHistoryProvider.java index 0060c2782d..f5e168c158 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/ComparingBaselineHistoryProvider.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/ComparingBaselineHistoryProvider.java @@ -28,7 +28,7 @@ import com.epam.ta.reportportal.entity.item.history.TestItemHistory; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.apache.commons.lang3.tuple.Pair; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/FilterBaselineHistoryProvider.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/FilterBaselineHistoryProvider.java index f266e30c35..e85055c03a 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/FilterBaselineHistoryProvider.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/FilterBaselineHistoryProvider.java @@ -29,7 +29,7 @@ import com.epam.ta.reportportal.entity.item.history.TestItemHistory; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.apache.commons.lang3.tuple.Pair; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/LaunchBaselineHistoryProvider.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/LaunchBaselineHistoryProvider.java index ec7c80627b..1d1c2f0b61 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/LaunchBaselineHistoryProvider.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/LaunchBaselineHistoryProvider.java @@ -26,7 +26,7 @@ import com.epam.ta.reportportal.entity.item.history.TestItemHistory; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/TestItemBaselineHistoryProvider.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/TestItemBaselineHistoryProvider.java index b1512142d9..1564b2be5a 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/TestItemBaselineHistoryProvider.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/history/provider/impl/TestItemBaselineHistoryProvider.java @@ -35,7 +35,7 @@ import com.epam.ta.reportportal.entity.item.history.TestItemHistory; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.lang3.BooleanUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/merge/strategy/AbstractLaunchMergeStrategy.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/merge/strategy/AbstractLaunchMergeStrategy.java index 30c5adb73c..77d251ca76 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/merge/strategy/AbstractLaunchMergeStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/merge/strategy/AbstractLaunchMergeStrategy.java @@ -20,7 +20,7 @@ import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.entity.enums.StatusEnum.IN_PROGRESS; import static com.epam.ta.reportportal.ws.converter.converters.ItemAttributeConverter.FROM_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.FINISH_TIME_EARLIER_THAN_START_TIME; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FINISH_TIME_EARLIER_THAN_START_TIME; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; @@ -42,11 +42,11 @@ import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.converter.builders.LaunchBuilder; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.launch.MergeLaunchesRQ; -import com.epam.ta.reportportal.ws.model.launch.Mode; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.MergeLaunchesRQ; +import com.epam.ta.reportportal.ws.reporting.Mode; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; import com.google.common.collect.Sets; import java.util.Collection; import java.util.Comparator; @@ -69,9 +69,8 @@ public abstract class AbstractLaunchMergeStrategy implements LaunchMergeStrategy private final TestItemUniqueIdGenerator identifierGenerator; protected AbstractLaunchMergeStrategy(LaunchRepository launchRepository, - TestItemRepository testItemRepository, - LogRepository logRepository, AttachmentRepository attachmentRepository, - TestItemUniqueIdGenerator identifierGenerator) { + TestItemRepository testItemRepository, LogRepository logRepository, + AttachmentRepository attachmentRepository, TestItemUniqueIdGenerator identifierGenerator) { this.launchRepository = launchRepository; this.testItemRepository = testItemRepository; this.logRepository = logRepository; @@ -80,13 +79,13 @@ protected AbstractLaunchMergeStrategy(LaunchRepository launchRepository, } protected Launch createNewLaunch(ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user, MergeLaunchesRQ rq, - List launchesList) { - Launch newLaunch = createResultedLaunch(projectDetails.getProjectId(), user.getUserId(), rq, - launchesList); + ReportPortalUser user, MergeLaunchesRQ rq, List launchesList) { + Launch newLaunch = + createResultedLaunch(projectDetails.getProjectId(), user.getUserId(), rq, launchesList); boolean isNameChanged = !newLaunch.getName().equals(launchesList.get(0).getName()); updateChildrenOfLaunches(newLaunch, rq.getLaunches(), rq.isExtendSuitesDescription(), - isNameChanged); + isNameChanged + ); return newLaunch; } @@ -102,38 +101,28 @@ protected Launch createNewLaunch(ReportPortalUser.ProjectDetails projectDetails, */ private Launch createResultedLaunch(Long projectId, Long userId, MergeLaunchesRQ mergeLaunchesRQ, List launches) { - Date startTime = ofNullable(mergeLaunchesRQ.getStartTime()).orElse( - EntityUtils.TO_DATE.apply(launches.stream() - .min(Comparator.comparing(Launch::getStartTime)) - .orElseThrow( + Date startTime = ofNullable(mergeLaunchesRQ.getStartTime()).orElse(EntityUtils.TO_DATE.apply( + launches.stream().min(Comparator.comparing(Launch::getStartTime)).orElseThrow( () -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, "Invalid launches")) .getStartTime())); - Date endTime = ofNullable(mergeLaunchesRQ.getEndTime()).orElse( - EntityUtils.TO_DATE.apply(launches.stream() - .max(Comparator.comparing(Launch::getEndTime)) - .orElseThrow( + Date endTime = ofNullable(mergeLaunchesRQ.getEndTime()).orElse(EntityUtils.TO_DATE.apply( + launches.stream().max(Comparator.comparing(Launch::getEndTime)).orElseThrow( () -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, "Invalid launches")) .getEndTime())); expect(endTime, time -> !time.before(startTime)).verify(FINISH_TIME_EARLIER_THAN_START_TIME, - TO_LOCAL_DATE_TIME.apply(endTime), - startTime, - projectId + TO_LOCAL_DATE_TIME.apply(endTime), startTime, projectId ); StartLaunchRQ startRQ = new StartLaunchRQ(); startRQ.setMode(ofNullable(mergeLaunchesRQ.getMode()).orElse(Mode.DEFAULT)); - startRQ.setDescription(ofNullable(mergeLaunchesRQ.getDescription()).orElse(launches.stream() - .map(Launch::getDescription) - .collect(joining("\n\n")))); + startRQ.setDescription(ofNullable(mergeLaunchesRQ.getDescription()).orElse( + launches.stream().map(Launch::getDescription).collect(joining("\n\n")))); startRQ.setName(ofNullable(mergeLaunchesRQ.getName()).orElse( "Merged: " + launches.stream().map(Launch::getName).distinct().collect(joining(", ")))); startRQ.setStartTime(startTime); - Launch launch = new LaunchBuilder().addStartRQ(startRQ) - .addProject(projectId) - .addStatus(IN_PROGRESS.name()) - .addUserId(userId) - .addEndTime(endTime) - .get(); + Launch launch = + new LaunchBuilder().addStartRQ(startRQ).addProject(projectId).addStatus(IN_PROGRESS.name()) + .addUserId(userId).addEndTime(endTime).get(); launch.setHasRetries(launches.stream().anyMatch(Launch::isHasRetries)); launchRepository.save(launch); @@ -157,22 +146,17 @@ private void mergeAttributes(Set attributesFromRq, Set mergedAttributes = Sets.newHashSet(); if (attributesFromRq == null) { - mergedAttributes.addAll(launchesToMerge.stream() - .map(Launch::getAttributes) - .flatMap(Collection::stream) - .peek(it -> it.setLaunch(resultedLaunch)) - .collect(Collectors.toSet())); + mergedAttributes.addAll( + launchesToMerge.stream().map(Launch::getAttributes).flatMap(Collection::stream) + .peek(it -> it.setLaunch(resultedLaunch)).collect(Collectors.toSet())); } else { - mergedAttributes.addAll(launchesToMerge.stream() - .map(Launch::getAttributes) - .flatMap(Collection::stream) - .filter(ItemAttribute::isSystem) - .peek(it -> it.setLaunch(resultedLaunch)) - .collect(Collectors.toSet())); - mergedAttributes.addAll(attributesFromRq.stream() - .map(FROM_RESOURCE) - .peek(attr -> attr.setLaunch(resultedLaunch)) - .collect(Collectors.toSet())); + mergedAttributes.addAll( + launchesToMerge.stream().map(Launch::getAttributes).flatMap(Collection::stream) + .filter(ItemAttribute::isSystem).peek(it -> it.setLaunch(resultedLaunch)) + .collect(Collectors.toSet())); + mergedAttributes.addAll( + attributesFromRq.stream().map(FROM_RESOURCE).peek(attr -> attr.setLaunch(resultedLaunch)) + .collect(Collectors.toSet())); } resultedLaunch.setAttributes(mergedAttributes); } @@ -190,7 +174,8 @@ private void updateChildrenOfLaunches(Launch newLaunch, Set launches, List testItems = launches.stream().peek(id -> { logRepository.updateLaunchIdByLaunchId(id, newLaunch.getId()); attachmentRepository.updateLaunchIdByProjectIdAndLaunchId(newLaunch.getProjectId(), id, - newLaunch.getId()); + newLaunch.getId() + ); }).flatMap(id -> { Launch launch = launchRepository.findById(id) .orElseThrow(() -> new ReportPortalException(ErrorType.LAUNCH_NOT_FOUND, id)); @@ -199,15 +184,16 @@ private void updateChildrenOfLaunches(Launch newLaunch, Set launches, if (isNameChanged && identifierGenerator.validate(testItem.getUniqueId())) { testItem.setUniqueId( identifierGenerator.generate(testItem, IdentityUtil.getParentIds(testItem), - newLaunch)); + newLaunch + )); } if (testItem.getType().sameLevel(TestItemTypeEnum.SUITE)) { // Add launch reference description for top level items Supplier newDescription = Suppliers.formattedSupplier( ((null != testItem.getDescription()) ? testItem.getDescription() : "") + ( - extendDescription ? - "\r\n@launch '{} #{}'" : - ""), launch.getName(), launch.getNumber()); + extendDescription ? "\r\n@launch '{} #{}'" : ""), launch.getName(), + launch.getNumber() + ); testItem.setDescription(newDescription.get()); } }); diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/merge/strategy/BasicLaunchMergeStrategy.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/merge/strategy/BasicLaunchMergeStrategy.java index c38fb183e2..7c0cde8793 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/merge/strategy/BasicLaunchMergeStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/merge/strategy/BasicLaunchMergeStrategy.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.dao.LogRepository; import com.epam.ta.reportportal.dao.TestItemRepository; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.launch.MergeLaunchesRQ; +import com.epam.ta.reportportal.ws.reporting.MergeLaunchesRQ; import java.util.List; /** @@ -34,19 +34,18 @@ public class BasicLaunchMergeStrategy extends AbstractLaunchMergeStrategy { private final StatisticsCalculationFactory statisticsCalculationFactory; public BasicLaunchMergeStrategy(LaunchRepository launchRepository, - TestItemRepository testItemRepository, - LogRepository logRepository, AttachmentRepository attachmentRepository, - TestItemUniqueIdGenerator identifierGenerator, + TestItemRepository testItemRepository, LogRepository logRepository, + AttachmentRepository attachmentRepository, TestItemUniqueIdGenerator identifierGenerator, StatisticsCalculationFactory statisticsCalculationFactory) { super(launchRepository, testItemRepository, logRepository, attachmentRepository, - identifierGenerator); + identifierGenerator + ); this.statisticsCalculationFactory = statisticsCalculationFactory; } @Override public Launch mergeLaunches(ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, - MergeLaunchesRQ rq, - List launchesList) { + MergeLaunchesRQ rq, List launchesList) { Launch newLaunch = createNewLaunch(projectDetails, user, rq, launchesList); diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/merge/strategy/DeepLaunchMergeStrategy.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/merge/strategy/DeepLaunchMergeStrategy.java index 5eeb57ecf9..4e7c2a069c 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/merge/strategy/DeepLaunchMergeStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/merge/strategy/DeepLaunchMergeStrategy.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.dao.LogRepository; import com.epam.ta.reportportal.dao.TestItemRepository; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.launch.MergeLaunchesRQ; +import com.epam.ta.reportportal.ws.reporting.MergeLaunchesRQ; import java.util.List; /** @@ -35,13 +35,13 @@ public DeepLaunchMergeStrategy(LaunchRepository launchRepository, TestItemRepository testItemRepository, LogRepository logRepository, AttachmentRepository attachmentRepository, TestItemUniqueIdGenerator identifierGenerator) { super(launchRepository, testItemRepository, logRepository, attachmentRepository, - identifierGenerator); + identifierGenerator + ); } @Override public Launch mergeLaunches(ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, - MergeLaunchesRQ rq, - List launchesList) { + MergeLaunchesRQ rq, List launchesList) { Launch newLaunch = createNewLaunch(projectDetails, user, rq, launchesList); launchRepository.mergeLaunchTestItems(newLaunch.getId()); diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/FilterDataProviderImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/FilterDataProviderImpl.java index a223249c75..d7c4b2ccf9 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/FilterDataProviderImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/FilterDataProviderImpl.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.util.ControllerUtils; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.apache.commons.lang3.tuple.Pair; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; @@ -43,7 +43,7 @@ import static com.epam.ta.reportportal.entity.project.ProjectRole.OPERATOR; import static com.epam.ta.reportportal.ws.controller.TestItemController.IS_LATEST_LAUNCHES_REQUEST_PARAM; import static com.epam.ta.reportportal.ws.controller.TestItemController.LAUNCHES_LIMIT_REQUEST_PARAM; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; /** * @author Pavel Bortnik diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/BaselineLaunchDataProvider.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/BaselineLaunchDataProvider.java index 1173a2da6f..907eb58685 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/BaselineLaunchDataProvider.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/BaselineLaunchDataProvider.java @@ -31,7 +31,7 @@ import com.epam.ta.reportportal.entity.statistics.Statistics; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.util.ControllerUtils; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Map; import java.util.Optional; import java.util.Set; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/CumulativeTestItemDataProviderImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/CumulativeTestItemDataProviderImpl.java index 8b06c0881c..567f430371 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/CumulativeTestItemDataProviderImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/CumulativeTestItemDataProviderImpl.java @@ -33,7 +33,7 @@ import com.epam.ta.reportportal.dao.WidgetContentRepository; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.statistics.Statistics; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import java.util.Set; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/DelegatingClusterDataProviderHandler.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/DelegatingClusterDataProviderHandler.java index d05d1ff697..c2aea512d5 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/DelegatingClusterDataProviderHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/DelegatingClusterDataProviderHandler.java @@ -22,7 +22,7 @@ import com.epam.ta.reportportal.core.item.impl.provider.DataProviderHandler; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.statistics.Statistics; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.BooleanUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/LaunchDataProviderHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/LaunchDataProviderHandlerImpl.java index c3eb72781d..e0e001b020 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/LaunchDataProviderHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/LaunchDataProviderHandlerImpl.java @@ -31,7 +31,7 @@ import com.epam.ta.reportportal.entity.statistics.Statistics; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.util.ControllerUtils; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Map; import java.util.Optional; import java.util.Set; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/MaterializedWidgetProviderHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/MaterializedWidgetProviderHandlerImpl.java index bd207f6aa7..470239f88a 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/MaterializedWidgetProviderHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/provider/impl/MaterializedWidgetProviderHandlerImpl.java @@ -30,7 +30,7 @@ import com.epam.ta.reportportal.entity.widget.WidgetType; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.util.ControllerUtils; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/retry/DefaultRetryHandler.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/retry/DefaultRetryHandler.java index cdfd718ca6..9dc31d4a43 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/retry/DefaultRetryHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/retry/DefaultRetryHandler.java @@ -7,7 +7,7 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.jooq.enums.JStatusEnum; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.time.LocalDateTime; import java.util.Objects; import org.springframework.context.ApplicationEventPublisher; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/status/AbstractStatusChangingStrategy.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/status/AbstractStatusChangingStrategy.java index 0fe5d2600f..9f2dd39951 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/status/AbstractStatusChangingStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/status/AbstractStatusChangingStrategy.java @@ -23,8 +23,8 @@ import static com.epam.ta.reportportal.entity.enums.StatusEnum.WARN; import static com.epam.ta.reportportal.entity.enums.TestItemIssueGroup.TO_INVESTIGATE; import static com.epam.ta.reportportal.ws.converter.converters.TestItemConverter.TO_ACTIVITY_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; import static java.util.Optional.ofNullable; import com.epam.ta.reportportal.commons.ReportPortalUser; @@ -47,8 +47,8 @@ import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ChangeStatusHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ChangeStatusHandlerImpl.java index 9d4eef2b72..02fab7fd4e 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ChangeStatusHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ChangeStatusHandlerImpl.java @@ -34,7 +34,7 @@ import com.epam.ta.reportportal.entity.item.issue.IssueEntity; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.jooq.enums.JStatusEnum; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; import com.google.common.collect.Lists; import java.util.Map; import java.util.Optional; @@ -55,8 +55,8 @@ public class ChangeStatusHandlerImpl implements ChangeStatusHandler { @Autowired public ChangeStatusHandlerImpl(TestItemRepository testItemRepository, - IssueEntityRepository issueEntityRepository, - MessageBus messageBus, LaunchRepository launchRepository, + IssueEntityRepository issueEntityRepository, MessageBus messageBus, + LaunchRepository launchRepository, Map statusChangingStrategyMapping) { this.testItemRepository = testItemRepository; this.issueEntityRepository = issueEntityRepository; @@ -77,11 +77,10 @@ public void changeParentStatus(TestItem childItem, Long projectId, ReportPortalU if (parent.getItemResults().getStatus() != resolvedStatus) { TestItemActivityResource before = TO_ACTIVITY_RESOURCE.apply(parent, projectId); changeStatus(parent, resolvedStatus, user); - messageBus.publishActivity(new TestItemStatusChangedEvent(before, - TO_ACTIVITY_RESOURCE.apply(parent, projectId), - user.getUserId(), - user.getUsername() - )); + messageBus.publishActivity( + new TestItemStatusChangedEvent(before, TO_ACTIVITY_RESOURCE.apply(parent, projectId), + user.getUserId(), user.getUsername() + )); changeParentStatus(parent, projectId, user); } @@ -94,23 +93,23 @@ private boolean isParentStatusUpdateRequired(TestItem parent) { && parent.getItemResults().getStatus() != PASSED && parent.getItemResults().getStatus() != FAILED && !testItemRepository.hasItemsInStatusByParent(parent.getItemId(), parent.getPath(), - StatusEnum.IN_PROGRESS.name()); + StatusEnum.IN_PROGRESS.name() + ); } private StatusEnum resolveStatus(Long itemId) { return testItemRepository.hasDescendantsNotInStatus(itemId, StatusEnum.PASSED.name(), INFO.name(), - WARN.name()) ? - FAILED : - PASSED; + WARN.name() + ) ? FAILED : PASSED; } private void changeStatus(TestItem parent, StatusEnum resolvedStatus, ReportPortalUser user) { if (parent.isHasChildren() || !parent.isHasStats()) { parent.getItemResults().setStatus(resolvedStatus); } else { - Optional statusChangingStrategy = ofNullable( - statusChangingStrategyMapping.get(resolvedStatus)); + Optional statusChangingStrategy = + ofNullable(statusChangingStrategyMapping.get(resolvedStatus)); if (statusChangingStrategy.isPresent()) { statusChangingStrategy.get().changeStatus(parent, resolvedStatus, user, false); } else { @@ -124,11 +123,10 @@ private void changeStatus(TestItem parent, StatusEnum resolvedStatus, ReportPort public void changeLaunchStatus(Launch launch) { if (launch.getStatus() != StatusEnum.IN_PROGRESS) { if (!launchRepository.hasItemsInStatuses(launch.getId(), - Lists.newArrayList(JStatusEnum.IN_PROGRESS))) { + Lists.newArrayList(JStatusEnum.IN_PROGRESS) + )) { StatusEnum launchStatus = launchRepository.hasRootItemsWithStatusNotEqual(launch.getId(), - StatusEnum.PASSED.name(), - INFO.name(), - WARN.name() + StatusEnum.PASSED.name(), INFO.name(), WARN.name() ) ? FAILED : PASSED; launch.setStatus(launchStatus); } diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ToFailedStatusChangingStrategy.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ToFailedStatusChangingStrategy.java index f1fb3a84a8..48290899a6 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ToFailedStatusChangingStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ToFailedStatusChangingStrategy.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.item.impl.status; import static com.epam.ta.reportportal.commons.Preconditions.statusIn; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.validation.BusinessRule; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ToPassedStatusChangingStrategy.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ToPassedStatusChangingStrategy.java index babcc18e7e..a9c23082c2 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ToPassedStatusChangingStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ToPassedStatusChangingStrategy.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.item.impl.status; import static com.epam.ta.reportportal.commons.Preconditions.statusIn; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; import static java.util.Optional.ofNullable; import com.epam.ta.reportportal.commons.ReportPortalUser; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ToSkippedStatusChangingStrategy.java b/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ToSkippedStatusChangingStrategy.java index 863896daff..ebea065f7f 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ToSkippedStatusChangingStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/impl/status/ToSkippedStatusChangingStrategy.java @@ -18,7 +18,7 @@ import static com.epam.ta.reportportal.commons.Preconditions.statusIn; import static com.epam.ta.reportportal.entity.enums.StatusEnum.FAILED; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; import static java.util.Optional.ofNullable; import com.epam.ta.reportportal.commons.ReportPortalUser; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/merge/LaunchMergeStrategy.java b/src/main/java/com/epam/ta/reportportal/core/item/merge/LaunchMergeStrategy.java index aa786bbf44..5ce7bdfec3 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/merge/LaunchMergeStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/merge/LaunchMergeStrategy.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.launch.MergeLaunchesRQ; +import com.epam.ta.reportportal.ws.reporting.MergeLaunchesRQ; import java.util.List; /** @@ -27,6 +27,5 @@ public interface LaunchMergeStrategy { Launch mergeLaunches(ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, - MergeLaunchesRQ rq, - List launchesList); + MergeLaunchesRQ rq, List launchesList); } diff --git a/src/main/java/com/epam/ta/reportportal/core/item/utils/DefaultLaunchFilterProvider.java b/src/main/java/com/epam/ta/reportportal/core/item/utils/DefaultLaunchFilterProvider.java index b1fdecff05..891ba6fe35 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/utils/DefaultLaunchFilterProvider.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/utils/DefaultLaunchFilterProvider.java @@ -32,8 +32,8 @@ import com.epam.ta.reportportal.entity.enums.StatusEnum; import com.epam.ta.reportportal.entity.filter.ObjectType; import com.epam.ta.reportportal.entity.filter.UserFilter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.launch.Mode; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.Mode; import org.apache.commons.lang3.tuple.Pair; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/NestedStepConditionValidator.java b/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/NestedStepConditionValidator.java index 87338a1f1d..1ac1640450 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/NestedStepConditionValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/NestedStepConditionValidator.java @@ -2,11 +2,11 @@ import static com.epam.ta.reportportal.commons.Predicates.equalTo; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; import com.epam.ta.reportportal.commons.validation.Suppliers; import com.epam.ta.reportportal.entity.item.TestItem; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; import org.springframework.core.Ordered; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/ParentItemValidator.java b/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/ParentItemValidator.java index ef29f979df..0512ad8070 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/ParentItemValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/ParentItemValidator.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.item.validator.parent; import com.epam.ta.reportportal.entity.item.TestItem; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; public interface ParentItemValidator { diff --git a/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/PathLengthValidator.java b/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/PathLengthValidator.java index 774e87f54c..630ef509a1 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/PathLengthValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/PathLengthValidator.java @@ -17,11 +17,11 @@ package com.epam.ta.reportportal.core.item.validator.parent; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; import com.epam.ta.reportportal.commons.Predicates; import com.epam.ta.reportportal.entity.item.TestItem; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; import org.springframework.core.Ordered; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/RetryConditionValidator.java b/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/RetryConditionValidator.java index 485eabcec5..3fa5f7167c 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/RetryConditionValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/RetryConditionValidator.java @@ -2,10 +2,10 @@ import static com.epam.ta.reportportal.commons.Predicates.isNull; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; -import static com.epam.ta.reportportal.ws.model.ErrorType.UNABLE_TO_SAVE_CHILD_ITEM_FOR_THE_RETRY; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.UNABLE_TO_SAVE_CHILD_ITEM_FOR_THE_RETRY; import com.epam.ta.reportportal.entity.item.TestItem; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; import org.springframework.core.Ordered; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/StartTimeConditionValidator.java b/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/StartTimeConditionValidator.java index ed453d8b9e..ab95b6de7b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/StartTimeConditionValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/item/validator/parent/StartTimeConditionValidator.java @@ -1,11 +1,11 @@ package com.epam.ta.reportportal.core.item.validator.parent; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; -import static com.epam.ta.reportportal.ws.model.ErrorType.CHILD_START_TIME_EARLIER_THAN_PARENT; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.CHILD_START_TIME_EARLIER_THAN_PARENT; import com.epam.ta.reportportal.commons.Preconditions; import com.epam.ta.reportportal.entity.item.TestItem; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; import org.springframework.core.Ordered; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/core/jasper/impl/AbstractJasperReportHandler.java b/src/main/java/com/epam/ta/reportportal/core/jasper/impl/AbstractJasperReportHandler.java index 73773ec557..8af901ae70 100644 --- a/src/main/java/com/epam/ta/reportportal/core/jasper/impl/AbstractJasperReportHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/jasper/impl/AbstractJasperReportHandler.java @@ -15,14 +15,14 @@ */ package com.epam.ta.reportportal.core.jasper.impl; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.commons.validation.Suppliers; import com.epam.ta.reportportal.core.jasper.GetJasperReportHandler; import com.epam.ta.reportportal.entity.jasper.ReportFormat; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.io.OutputStream; import java.util.Set; import net.sf.jasperreports.engine.JRException; diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/DeleteLaunchHandler.java b/src/main/java/com/epam/ta/reportportal/core/launch/DeleteLaunchHandler.java index 3f65e87a77..b725a47e5f 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/DeleteLaunchHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/DeleteLaunchHandler.java @@ -17,9 +17,10 @@ package com.epam.ta.reportportal.core.launch; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.DeleteBulkRQ; -import com.epam.ta.reportportal.ws.model.DeleteBulkRS; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.model.DeleteBulkRQ; +import com.epam.ta.reportportal.model.DeleteBulkRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import java.util.List; /** * Delete Launch request handler @@ -42,13 +43,13 @@ OperationCompletionRS deleteLaunch(Long launchId, ReportPortalUser.ProjectDetail ReportPortalUser user); /** - * Bul launches delete. + * Bulk launches delete. * - * @param deleteBulkRQ {@link DeleteBulkRQ} + * @param ids list of launch ids * @param projectDetails Project Details * @param user User * @return DeleteLaunchesRS */ - DeleteBulkRS deleteLaunches(DeleteBulkRQ deleteBulkRQ, + DeleteBulkRS deleteLaunches(List ids, ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user); } \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/FinishLaunchHandler.java b/src/main/java/com/epam/ta/reportportal/core/launch/FinishLaunchHandler.java index a7108fb717..b2a5770a89 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/FinishLaunchHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/FinishLaunchHandler.java @@ -18,8 +18,8 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; -import com.epam.ta.reportportal.ws.model.launch.FinishLaunchRS; +import com.epam.ta.reportportal.model.launch.FinishLaunchRS; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; /** * {@link FinishExecutionRQ} request handler @@ -40,7 +40,6 @@ public interface FinishLaunchHandler { * @return FinishLaunchRS */ FinishLaunchRS finishLaunch(String launchId, FinishExecutionRQ finishLaunchRQ, - ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user, String baseUrl); + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, String baseUrl); } \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/GetLaunchHandler.java b/src/main/java/com/epam/ta/reportportal/core/launch/GetLaunchHandler.java index 3d0bc531c5..cea26cc441 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/GetLaunchHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/GetLaunchHandler.java @@ -21,8 +21,8 @@ import com.epam.ta.reportportal.entity.jasper.ReportFormat; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.entity.widget.content.ChartStatisticsContent; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; import com.epam.ta.reportportal.ws.model.launch.cluster.ClusterInfoResource; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; import java.io.OutputStream; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/MergeLaunchHandler.java b/src/main/java/com/epam/ta/reportportal/core/launch/MergeLaunchHandler.java index c6026baab4..6aab3985aa 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/MergeLaunchHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/MergeLaunchHandler.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.core.launch; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; -import com.epam.ta.reportportal.ws.model.launch.MergeLaunchesRQ; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; +import com.epam.ta.reportportal.ws.reporting.MergeLaunchesRQ; /** * Merge launches handler in common one diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/StartLaunchHandler.java b/src/main/java/com/epam/ta/reportportal/core/launch/StartLaunchHandler.java index b5c551b266..51b1604b99 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/StartLaunchHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/StartLaunchHandler.java @@ -20,10 +20,10 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.entity.project.ProjectRole; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.launch.Mode; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.Mode; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRS; import java.util.function.Predicate; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/StopLaunchHandler.java b/src/main/java/com/epam/ta/reportportal/core/launch/StopLaunchHandler.java index 3a85ce26b1..98c4538a23 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/StopLaunchHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/StopLaunchHandler.java @@ -17,9 +17,9 @@ package com.epam.ta.reportportal.core.launch; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.BulkRQ; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.model.BulkRQ; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.List; /** @@ -37,8 +37,7 @@ public interface StopLaunchHandler { * @return OperationCompletionRS */ OperationCompletionRS stopLaunch(Long launchId, FinishExecutionRQ finishLaunchRQ, - ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user); + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user); /** * Bulk stop launches operation. @@ -49,6 +48,5 @@ OperationCompletionRS stopLaunch(Long launchId, FinishExecutionRQ finishLaunchRQ * @return OperationCompletionsRS */ List stopLaunch(BulkRQ bulkRQ, - ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user); + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user); } diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/UpdateLaunchHandler.java b/src/main/java/com/epam/ta/reportportal/core/launch/UpdateLaunchHandler.java index 152b24a579..9105b19a4d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/UpdateLaunchHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/UpdateLaunchHandler.java @@ -17,12 +17,12 @@ package com.epam.ta.reportportal.core.launch; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.BulkInfoUpdateRQ; -import com.epam.ta.reportportal.ws.model.BulkRQ; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.launch.AnalyzeLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.UpdateLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.cluster.CreateClustersRQ; +import com.epam.ta.reportportal.model.BulkRQ; +import com.epam.ta.reportportal.model.launch.AnalyzeLaunchRQ; +import com.epam.ta.reportportal.model.launch.UpdateLaunchRQ; +import com.epam.ta.reportportal.model.launch.cluster.CreateClustersRQ; +import com.epam.ta.reportportal.ws.reporting.BulkInfoUpdateRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.List; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/cluster/GetClusterHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/launch/cluster/GetClusterHandlerImpl.java index 3bc0b38bc9..27f52530ab 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/cluster/GetClusterHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/cluster/GetClusterHandlerImpl.java @@ -25,7 +25,7 @@ import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.converter.PagedResourcesAssembler; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.epam.ta.reportportal.ws.model.launch.cluster.ClusterInfoResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; @@ -61,8 +61,8 @@ public Cluster getById(Long id) { public Iterable getResources(Launch launch, Pageable pageable) { final Pageable pageableWithSort = applySort(pageable); - final Page clusters = clusterRepository.findAllByLaunchId(launch.getId(), - pageableWithSort); + final Page clusters = + clusterRepository.findAllByLaunchId(launch.getId(), pageableWithSort); return getClusterResources(clusters, launch.getId()); } @@ -73,8 +73,8 @@ private Pageable applySort(Pageable pageable) { } private Iterable getClusterResources(Page clusters, Long launchId) { - final com.epam.ta.reportportal.ws.model.Page clustersPage = PagedResourcesAssembler.pageConverter( - TO_CLUSTER_INFO).apply(clusters); + final com.epam.ta.reportportal.model.Page clustersPage = + PagedResourcesAssembler.pageConverter(TO_CLUSTER_INFO).apply(clusters); eventPublisher.publishEvent(new GetClusterResourcesEvent(clustersPage.getContent(), launchId)); return clustersPage; } diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/cluster/UniqueErrorAnalysisStarter.java b/src/main/java/com/epam/ta/reportportal/core/launch/cluster/UniqueErrorAnalysisStarter.java index b5726506d9..2546a02289 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/cluster/UniqueErrorAnalysisStarter.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/cluster/UniqueErrorAnalysisStarter.java @@ -21,8 +21,8 @@ import com.epam.ta.reportportal.core.launch.cluster.config.ClusterEntityContext; import com.epam.ta.reportportal.core.launch.cluster.config.GenerateClustersConfig; +import com.epam.ta.reportportal.model.project.UniqueErrorConfig; import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; -import com.epam.ta.reportportal.ws.model.project.UniqueErrorConfig; import java.util.Map; import org.apache.commons.collections4.CollectionUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/cluster/UniqueErrorGenerator.java b/src/main/java/com/epam/ta/reportportal/core/launch/cluster/UniqueErrorGenerator.java index ae2e4432c2..23374d56c0 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/cluster/UniqueErrorGenerator.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/cluster/UniqueErrorGenerator.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.pipeline.PipelineConstructor; import com.epam.ta.reportportal.pipeline.PipelinePart; import com.epam.ta.reportportal.pipeline.TransactionalPipeline; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.function.Predicate; import org.slf4j.Logger; diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/cluster/pipeline/data/AnalyzerClusterDataProvider.java b/src/main/java/com/epam/ta/reportportal/core/launch/cluster/pipeline/data/AnalyzerClusterDataProvider.java index f1fea1c8b4..6ccec8ca9b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/cluster/pipeline/data/AnalyzerClusterDataProvider.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/cluster/pipeline/data/AnalyzerClusterDataProvider.java @@ -23,9 +23,9 @@ import com.epam.ta.reportportal.core.analyzer.auto.client.model.cluster.GenerateClustersRq; import com.epam.ta.reportportal.core.launch.cluster.config.ClusterEntityContext; import com.epam.ta.reportportal.core.launch.cluster.config.GenerateClustersConfig; -import com.epam.ta.reportportal.ws.model.ErrorType; import com.epam.ta.reportportal.ws.model.analyzer.IndexLaunch; import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Optional; import java.util.function.Predicate; diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/impl/DeleteLaunchHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/launch/impl/DeleteLaunchHandlerImpl.java index a1509b40f9..011b9acc68 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/impl/DeleteLaunchHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/impl/DeleteLaunchHandlerImpl.java @@ -22,12 +22,13 @@ import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; import static com.epam.ta.reportportal.entity.project.ProjectRole.PROJECT_MANAGER; import static com.epam.ta.reportportal.ws.converter.converters.LaunchConverter.TO_ACTIVITY_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.FORBIDDEN_OPERATION; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_IS_NOT_FINISHED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FORBIDDEN_OPERATION; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_IS_NOT_FINISHED; import com.epam.reportportal.events.ElementsDeletedEvent; import com.epam.ta.reportportal.commons.ReportPortalUser; +import com.epam.ta.reportportal.commons.ReportPortalUser.ProjectDetails; import com.epam.ta.reportportal.core.ElementsCounterService; import com.epam.ta.reportportal.core.analyzer.auto.LogIndexer; import com.epam.ta.reportportal.core.events.MessageBus; @@ -41,12 +42,12 @@ import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.DeleteBulkRQ; -import com.epam.ta.reportportal.ws.model.DeleteBulkRS; -import com.epam.ta.reportportal.ws.model.ErrorRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.activity.LaunchActivityResource; +import com.epam.ta.reportportal.model.DeleteBulkRQ; +import com.epam.ta.reportportal.model.DeleteBulkRS; +import com.epam.ta.reportportal.model.activity.LaunchActivityResource; +import com.epam.ta.reportportal.ws.reporting.ErrorRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.api.client.util.Maps; import com.google.common.collect.Lists; import java.util.List; @@ -87,9 +88,8 @@ public class DeleteLaunchHandlerImpl implements DeleteLaunchHandler { @Autowired public DeleteLaunchHandlerImpl(ContentRemover launchContentRemover, - LaunchRepository launchRepository, MessageBus messageBus, - LogIndexer logIndexer, AttachmentRepository attachmentRepository, - ApplicationEventPublisher eventPublisher, + LaunchRepository launchRepository, MessageBus messageBus, LogIndexer logIndexer, + AttachmentRepository attachmentRepository, ApplicationEventPublisher eventPublisher, ElementsCounterService elementsCounterService, LogService logService) { this.launchContentRemover = launchContentRemover; this.launchRepository = launchRepository; @@ -106,8 +106,8 @@ public OperationCompletionRS deleteLaunch(Long launchId, Launch launch = launchRepository.findById(launchId) .orElseThrow(() -> new ReportPortalException(ErrorType.LAUNCH_NOT_FOUND, launchId)); validate(launch, user, projectDetails); - final Long numberOfLaunchElements = elementsCounterService.countNumberOfLaunchElements( - launchId); + final Long numberOfLaunchElements = + elementsCounterService.countNumberOfLaunchElements(launchId); logIndexer.indexLaunchesRemove(projectDetails.getProjectId(), Lists.newArrayList(launchId)); launchContentRemover.remove(launch); @@ -117,27 +117,28 @@ public OperationCompletionRS deleteLaunch(Long launchId, messageBus.publishActivity( new LaunchDeletedEvent(TO_ACTIVITY_RESOURCE.apply(launch), user.getUserId(), - user.getUsername())); + user.getUsername() + )); eventPublisher.publishEvent( new ElementsDeletedEvent(launchId, launch.getProjectId(), numberOfLaunchElements)); return new OperationCompletionRS("Launch with ID = '" + launchId + "' successfully deleted."); } - public DeleteBulkRS deleteLaunches(DeleteBulkRQ deleteBulkRQ, + public DeleteBulkRS deleteLaunches(List ids, ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { List notFound = Lists.newArrayList(); List exceptions = Lists.newArrayList(); Map toDelete = Maps.newHashMap(); List launchIds = Lists.newArrayList(); - deleteBulkRQ.getIds().forEach(id -> { + ids.forEach(id -> { Optional optionalLaunch = launchRepository.findById(id); if (optionalLaunch.isPresent()) { Launch launch = optionalLaunch.get(); try { validate(launch, user, projectDetails); - Long numberOfLaunchElements = elementsCounterService.countNumberOfLaunchElements( - launch.getId()); + Long numberOfLaunchElements = + elementsCounterService.countNumberOfLaunchElements(launch.getId()); toDelete.put(launch, numberOfLaunchElements); launchIds.add(id); } catch (ReportPortalException ex) { @@ -162,7 +163,8 @@ public DeleteBulkRS deleteLaunches(DeleteBulkRQ deleteBulkRQ, new LaunchDeletedEvent(launchActivity, user.getUserId(), user.getUsername())); eventPublisher.publishEvent( new ElementsDeletedEvent(entry.getKey().getId(), entry.getKey().getProjectId(), - entry.getValue())); + entry.getValue() + )); }); return new DeleteBulkRS(launchIds, notFound, exceptions.stream().map(ex -> { @@ -190,12 +192,14 @@ private void validate(Launch launch, ReportPortalUser user, expect(launch.getProjectId(), equalTo(projectDetails.getProjectId())).verify( FORBIDDEN_OPERATION, formattedSupplier("Target launch '{}' not under specified project '{}'", launch.getId(), - projectDetails.getProjectId()) + projectDetails.getProjectId() + ) ); /* Only PROJECT_MANAGER roles could delete launches */ if (projectDetails.getProjectRole().lowerThan(PROJECT_MANAGER)) { expect(user.getUserId(), Predicate.isEqual(launch.getUserId())).verify(ACCESS_DENIED, - "You are not launch owner."); + "You are not launch owner." + ); } } } diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerAsyncImpl.java b/src/main/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerAsyncImpl.java index 04221771f3..274fc65202 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerAsyncImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerAsyncImpl.java @@ -20,11 +20,11 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.core.launch.FinishLaunchHandler; +import com.epam.ta.reportportal.model.launch.FinishLaunchRS; import com.epam.ta.reportportal.util.ReportingQueueService; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; -import com.epam.ta.reportportal.ws.model.launch.FinishLaunchRS; import com.epam.ta.reportportal.ws.rabbit.MessageHeaders; import com.epam.ta.reportportal.ws.rabbit.RequestType; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; import java.util.Map; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; @@ -47,8 +47,7 @@ public class FinishLaunchHandlerAsyncImpl implements FinishLaunchHandler { @Override public FinishLaunchRS finishLaunch(String launchId, FinishExecutionRQ request, - ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user, String baseUrl) { + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, String baseUrl) { // todo: may be problem - no access to repository, so no possibility to validateRoles() here amqpTemplate.convertAndSend(EXCHANGE_REPORTING, @@ -60,7 +59,8 @@ public FinishLaunchRS finishLaunch(String launchId, FinishExecutionRQ request, headers.put(MessageHeaders.LAUNCH_ID, launchId); headers.put(MessageHeaders.BASE_URL, baseUrl); return message; - }); + } + ); FinishLaunchRS response = new FinishLaunchRS(); response.setId(launchId); diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerImpl.java index 4e1d71a82a..460664bd98 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerImpl.java @@ -21,7 +21,7 @@ import static com.epam.ta.reportportal.core.launch.util.LinkGenerator.generateLaunchLink; import static com.epam.ta.reportportal.entity.enums.StatusEnum.FAILED; import static com.epam.ta.reportportal.entity.enums.StatusEnum.PASSED; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_NOT_FOUND; import com.epam.reportportal.extension.event.LaunchFinishedPluginEvent; import com.epam.ta.reportportal.commons.ReportPortalUser; @@ -32,9 +32,9 @@ import com.epam.ta.reportportal.entity.enums.StatusEnum; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.launch.FinishLaunchRS; import com.epam.ta.reportportal.ws.converter.builders.LaunchBuilder; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; -import com.epam.ta.reportportal.ws.model.launch.FinishLaunchRS; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -59,7 +59,8 @@ public class FinishLaunchHandlerImpl implements FinishLaunchHandler { @Autowired public FinishLaunchHandlerImpl(LaunchRepository launchRepository, - @Qualifier("finishLaunchHierarchyHandler") FinishHierarchyHandler finishHierarchyHandler, + @Qualifier("finishLaunchHierarchyHandler") + FinishHierarchyHandler finishHierarchyHandler, ApplicationEventPublisher eventPublisher) { this.launchRepository = launchRepository; this.finishHierarchyHandler = finishHierarchyHandler; @@ -68,8 +69,7 @@ public FinishLaunchHandlerImpl(LaunchRepository launchRepository, @Override public FinishLaunchRS finishLaunch(String launchId, FinishExecutionRQ finishLaunchRQ, - ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user, String baseUrl) { + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, String baseUrl) { Launch launch = launchRepository.findByUuid(launchId) .orElseThrow(() -> new ReportPortalException(LAUNCH_NOT_FOUND, launchId)); @@ -80,30 +80,24 @@ public FinishLaunchRS finishLaunch(String launchId, FinishExecutionRQ finishLaun Long id = launch.getId(); - final int finishedCount = finishHierarchyHandler.finishDescendants(launch, - status.orElse(StatusEnum.INTERRUPTED), - finishLaunchRQ.getEndTime(), - user, - projectDetails - ); + final int finishedCount = + finishHierarchyHandler.finishDescendants(launch, status.orElse(StatusEnum.INTERRUPTED), + finishLaunchRQ.getEndTime(), user, projectDetails + ); if (finishedCount > 0) { - launch.setStatus(launchRepository.hasRootItemsWithStatusNotEqual(id, - StatusEnum.PASSED.name(), - StatusEnum.INFO.name(), - StatusEnum.WARN.name() + launch.setStatus(launchRepository.hasRootItemsWithStatusNotEqual(id, StatusEnum.PASSED.name(), + StatusEnum.INFO.name(), StatusEnum.WARN.name() ) ? FAILED : PASSED); } else { - launch.setStatus(status.orElseGet(() -> launchRepository.hasRootItemsWithStatusNotEqual(id, - StatusEnum.PASSED.name(), - StatusEnum.INFO.name(), - StatusEnum.WARN.name() - ) ? FAILED : PASSED)); + launch.setStatus(status.orElseGet(() -> + launchRepository.hasRootItemsWithStatusNotEqual(id, StatusEnum.PASSED.name(), + StatusEnum.INFO.name(), StatusEnum.WARN.name() + ) ? FAILED : PASSED)); } launch = new LaunchBuilder(launch).addDescription( buildDescription(launch.getDescription(), finishLaunchRQ.getDescription())) - .addAttributes(finishLaunchRQ.getAttributes()) - .addEndTime(finishLaunchRQ.getEndTime()) + .addAttributes(finishLaunchRQ.getAttributes()).addEndTime(finishLaunchRQ.getEndTime()) .get(); eventPublisher.publishEvent( @@ -114,14 +108,15 @@ public FinishLaunchRS finishLaunch(String launchId, FinishExecutionRQ finishLaun response.setId(launch.getUuid()); response.setNumber(launch.getNumber()); response.setLink(generateLaunchLink(baseUrl, projectDetails.getProjectName(), - String.valueOf(launch.getId()))); + String.valueOf(launch.getId()) + )); return response; } private String buildDescription(String existDescription, String fromRequestDescription) { if (null != existDescription) { - return null != fromRequestDescription ? existDescription + " " + fromRequestDescription - : existDescription; + return null != fromRequestDescription ? existDescription + " " + fromRequestDescription : + existDescription; } else { return null; } diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/impl/GetLaunchHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/launch/impl/GetLaunchHandlerImpl.java index 28d2093850..137aa655e8 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/impl/GetLaunchHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/impl/GetLaunchHandlerImpl.java @@ -37,13 +37,10 @@ import static com.epam.ta.reportportal.dao.constant.WidgetContentRepositoryConstants.EXECUTIONS_PASSED; import static com.epam.ta.reportportal.dao.constant.WidgetContentRepositoryConstants.EXECUTIONS_SKIPPED; import static com.epam.ta.reportportal.entity.enums.StatusEnum.IN_PROGRESS; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_FILTER_PARAMETERS; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_NOT_FOUND; import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_LAUNCH_NAME_LENGTH; -import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_LAUNCH_NAME_LENGTH; -import static com.epam.ta.reportportal.ws.model.launch.Mode.DEBUG; -import static com.epam.ta.reportportal.ws.model.launch.Mode.DEFAULT; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_FILTER_PARAMETERS; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_NOT_FOUND; import static java.util.Collections.singletonMap; import static java.util.Optional.ofNullable; @@ -78,10 +75,10 @@ import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.converter.PagedResourcesAssembler; import com.epam.ta.reportportal.ws.converter.converters.LaunchConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; -import com.epam.ta.reportportal.ws.model.launch.Mode; import com.epam.ta.reportportal.ws.model.launch.cluster.ClusterInfoResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; +import com.epam.ta.reportportal.ws.reporting.Mode; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import java.io.OutputStream; @@ -126,14 +123,12 @@ public class GetLaunchHandlerImpl implements GetLaunchHandler { @Autowired public GetLaunchHandlerImpl(GetClusterHandler getClusterHandler, - LaunchRepository launchRepository, - TestItemRepository testItemRepository, ItemAttributeRepository itemAttributeRepository, - ProjectRepository projectRepository, + LaunchRepository launchRepository, TestItemRepository testItemRepository, + ItemAttributeRepository itemAttributeRepository, ProjectRepository projectRepository, WidgetContentRepository widgetContentRepository, UserRepository userRepository, JasperDataProvider dataProvider, @Qualifier("launchJasperReportHandler") GetJasperReportHandler jasperReportHandler, - LaunchConverter launchConverter, - ApplicationEventPublisher applicationEventPublisher) { + LaunchConverter launchConverter, ApplicationEventPublisher applicationEventPublisher) { this.getClusterHandler = getClusterHandler; this.launchRepository = launchRepository; this.testItemRepository = testItemRepository; @@ -177,8 +172,8 @@ public LaunchResource getLaunchByProjectName(String projectName, Pageable pageab Project project = projectRepository.findByName(projectName) .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, projectName)); - Page launches = launchRepository.findByFilter(ProjectFilter.of(filter, project.getId()), - pageable); + Page launches = + launchRepository.findByFilter(ProjectFilter.of(filter, project.getId()), pageable); expect(launches, notNull()).verify(LAUNCH_NOT_FOUND); return getLaunchResource(launches.iterator().next()); } @@ -192,16 +187,16 @@ private LaunchResource getLaunchResource(Launch launch) { @Override public Iterable getProjectLaunches(ReportPortalUser.ProjectDetails projectDetails, - Filter filter, Pageable pageable, - String userName) { + Filter filter, Pageable pageable, String userName) { validateModeConditions(filter); - Project project = projectRepository.findById(projectDetails.getProjectId()) - .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, - projectDetails.getProjectId())); + Project project = projectRepository.findById(projectDetails.getProjectId()).orElseThrow( + () -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, + projectDetails.getProjectId() + )); - filter = addLaunchCommonCriteria(DEFAULT, filter); - Page launches = launchRepository.findByFilter(ProjectFilter.of(filter, project.getId()), - pageable); + filter = addLaunchCommonCriteria(Mode.DEFAULT, filter); + Page launches = + launchRepository.findByFilter(ProjectFilter.of(filter, project.getId()), pageable); return getLaunchResources(launches); } @@ -213,9 +208,11 @@ public Iterable getProjectLaunches(ReportPortalUser.ProjectDetai public Iterable getDebugLaunches(ReportPortalUser.ProjectDetails projectDetails, Filter filter, Pageable pageable) { validateModeConditions(filter); - filter = addLaunchCommonCriteria(DEBUG, filter); - Page launches = launchRepository.findByFilter( - ProjectFilter.of(filter, projectDetails.getProjectId()), pageable); + filter = addLaunchCommonCriteria(Mode.DEBUG, filter); + Page launches = + launchRepository.findByFilter(ProjectFilter.of(filter, projectDetails.getProjectId()), + pageable + ); return getLaunchResources(launches); } @@ -223,14 +220,16 @@ public Iterable getDebugLaunches(ReportPortalUser.ProjectDetails public List getAttributeKeys(ReportPortalUser.ProjectDetails projectDetails, String value) { return itemAttributeRepository.findLaunchAttributeKeys(projectDetails.getProjectId(), value, - false); + false + ); } @Override public List getAttributeValues(ReportPortalUser.ProjectDetails projectDetails, String key, String value) { return itemAttributeRepository.findLaunchAttributeValues(projectDetails.getProjectId(), key, - value, false); + value, false + ); } @Override @@ -239,14 +238,15 @@ public Iterable getLatestLaunches(ReportPortalUser.ProjectDetail validateModeConditions(filter); - Project project = projectRepository.findById(projectDetails.getProjectId()) - .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, - projectDetails.getProjectId())); + Project project = projectRepository.findById(projectDetails.getProjectId()).orElseThrow( + () -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, + projectDetails.getProjectId() + )); - filter = addLaunchCommonCriteria(DEFAULT, filter); + filter = addLaunchCommonCriteria(Mode.DEFAULT, filter); - Page launches = launchRepository.findAllLatestByFilter( - ProjectFilter.of(filter, project.getId()), pageable); + Page launches = + launchRepository.findAllLatestByFilter(ProjectFilter.of(filter, project.getId()), pageable); return getLaunchResources(launches); } @@ -264,8 +264,8 @@ public boolean hasItemsWithIssues(Launch launch) { } private Iterable getLaunchResources(Page launches) { - final com.epam.ta.reportportal.ws.model.Page launchResourcePage = PagedResourcesAssembler.pageConverter( - launchConverter.TO_RESOURCE).apply(launches); + final com.epam.ta.reportportal.model.Page launchResourcePage = + PagedResourcesAssembler.pageConverter(launchConverter.TO_RESOURCE).apply(launches); applicationEventPublisher.publishEvent( new GetLaunchResourceCollectionEvent(launchResourcePage.getContent())); return launchResourcePage; @@ -275,15 +275,12 @@ private Iterable getLaunchResources(Page launches) { public List getLaunchNames(ReportPortalUser.ProjectDetails projectDetails, String value) { expect(value.length() <= MAX_LAUNCH_NAME_LENGTH, equalTo(true)).verify( INCORRECT_FILTER_PARAMETERS, - formattedSupplier("Length of the launch name string '{}' more than {} symbols", - value, + formattedSupplier("Length of the launch name string '{}' more than {} symbols", value, MAX_LAUNCH_NAME_LENGTH ) ); return launchRepository.getLaunchNamesByModeExcludedByStatus(projectDetails.getProjectId(), - value, - LaunchModeEnum.DEFAULT, - StatusEnum.IN_PROGRESS + value, LaunchModeEnum.DEFAULT, StatusEnum.IN_PROGRESS ); } @@ -294,8 +291,8 @@ public List getOwners(ReportPortalUser.ProjectDetails projectDetails, St formattedSupplier("Length of the filtering string '{}' is less than 3 symbols", value) ); - LaunchModeEnum launchMode = LaunchModeEnum.findByName(mode) - .orElseThrow(() -> new ReportPortalException(ErrorType.INCORRECT_FILTER_PARAMETERS, + LaunchModeEnum launchMode = LaunchModeEnum.findByName(mode).orElseThrow( + () -> new ReportPortalException(ErrorType.INCORRECT_FILTER_PARAMETERS, formattedSupplier("Mode - {} doesn't exist.", mode) )); @@ -306,34 +303,24 @@ public List getOwners(ReportPortalUser.ProjectDetails projectDetails, St public Map> getLaunchesComparisonInfo( ReportPortalUser.ProjectDetails projectDetails, Long[] ids) { - List contentFields = Lists.newArrayList(DEFECTS_AUTOMATION_BUG_TOTAL, - DEFECTS_NO_DEFECT_TOTAL, - DEFECTS_PRODUCT_BUG_TOTAL, - DEFECTS_SYSTEM_ISSUE_TOTAL, - DEFECTS_TO_INVESTIGATE_TOTAL, - EXECUTIONS_FAILED, - EXECUTIONS_PASSED, - EXECUTIONS_SKIPPED - ); - - Filter filter = Filter.builder() - .withTarget(Launch.class) - .withCondition(new FilterCondition(Condition.IN, - false, - Arrays.stream(ids).map(String::valueOf).collect(Collectors.joining(",")), - CRITERIA_ID - )) - .withCondition( - new FilterCondition(EQUALS, false, String.valueOf(projectDetails.getProjectId()), - CRITERIA_PROJECT_ID)) - .build(); - - List result = widgetContentRepository.launchesComparisonStatistics( - filter, - contentFields, - Sort.unsorted(), - ids.length - ); + List contentFields = + Lists.newArrayList(DEFECTS_AUTOMATION_BUG_TOTAL, DEFECTS_NO_DEFECT_TOTAL, + DEFECTS_PRODUCT_BUG_TOTAL, DEFECTS_SYSTEM_ISSUE_TOTAL, DEFECTS_TO_INVESTIGATE_TOTAL, + EXECUTIONS_FAILED, EXECUTIONS_PASSED, EXECUTIONS_SKIPPED + ); + + Filter filter = Filter.builder().withTarget(Launch.class).withCondition( + new FilterCondition(Condition.IN, false, + Arrays.stream(ids).map(String::valueOf).collect(Collectors.joining(",")), CRITERIA_ID + )).withCondition( + new FilterCondition(EQUALS, false, String.valueOf(projectDetails.getProjectId()), + CRITERIA_PROJECT_ID + )).build(); + + List result = + widgetContentRepository.launchesComparisonStatistics(filter, contentFields, Sort.unsorted(), + ids.length + ); return singletonMap(RESULT, result); @@ -356,8 +343,7 @@ public void exportLaunch(Long launchId, ReportFormat reportFormat, OutputStream "Launch '{}' has IN_PROGRESS status. Impossible to export such elements.", launchId) ); - String userFullName = userRepository.findById(user.getUserId()) - .map(User::getFullName) + String userFullName = userRepository.findById(user.getUserId()).map(User::getFullName) .orElseThrow(() -> new ReportPortalException(ErrorType.USER_NOT_FOUND, user.getUserId())); Map params = jasperReportHandler.convertParams(launch); @@ -402,11 +388,9 @@ private Filter addLaunchCommonCriteria(Mode mode, Filter filter) { * @param filter */ private void validateModeConditions(Filter filter) { - expect(filter.getFilterConditions() - .stream() - .map(ConvertibleCondition::getAllConditions) - .flatMap(Collection::stream) - .anyMatch(HAS_ANY_MODE), equalTo(false)).verify(INCORRECT_FILTER_PARAMETERS, + expect(filter.getFilterConditions().stream().map(ConvertibleCondition::getAllConditions) + .flatMap(Collection::stream).anyMatch(HAS_ANY_MODE), equalTo(false)).verify( + INCORRECT_FILTER_PARAMETERS, "Filters for 'mode' aren't applicable for project's launches." ); } diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/impl/MergeLaunchHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/launch/impl/MergeLaunchHandlerImpl.java index 6d463d219e..80011c059c 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/impl/MergeLaunchHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/impl/MergeLaunchHandlerImpl.java @@ -22,34 +22,32 @@ import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.entity.enums.StatusEnum.IN_PROGRESS; import static com.epam.ta.reportportal.entity.user.UserRole.ADMINISTRATOR; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.FORBIDDEN_OPERATION; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_IS_NOT_FINISHED; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.UNSUPPORTED_MERGE_STRATEGY_TYPE; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FORBIDDEN_OPERATION; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_IS_NOT_FINISHED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.UNSUPPORTED_MERGE_STRATEGY_TYPE; import com.epam.ta.reportportal.commons.Preconditions; import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.validation.Suppliers; import com.epam.ta.reportportal.core.analyzer.auto.LogIndexer; import com.epam.ta.reportportal.core.analyzer.auto.impl.AnalyzerUtils; -import com.epam.ta.reportportal.core.analyzer.auto.impl.preparer.LaunchPreparerService; import com.epam.ta.reportportal.core.item.impl.merge.strategy.LaunchMergeFactory; import com.epam.ta.reportportal.core.item.impl.merge.strategy.MergeStrategyType; import com.epam.ta.reportportal.core.launch.MergeLaunchHandler; import com.epam.ta.reportportal.core.statistics.StatisticsHelper; import com.epam.ta.reportportal.dao.LaunchRepository; import com.epam.ta.reportportal.dao.ProjectRepository; -import com.epam.ta.reportportal.dao.TestItemRepository; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.converter.converters.LaunchConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; -import com.epam.ta.reportportal.ws.model.launch.MergeLaunchesRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; +import com.epam.ta.reportportal.ws.reporting.MergeLaunchesRQ; import java.util.List; import java.util.Set; import org.apache.commons.collections.CollectionUtils; @@ -66,46 +64,36 @@ public class MergeLaunchHandlerImpl implements MergeLaunchHandler { private final LaunchRepository launchRepository; - private final TestItemRepository testItemRepository; - private final ProjectRepository projectRepository; private final LaunchMergeFactory launchMergeFactory; private final LaunchConverter launchConverter; - private final LaunchPreparerService launchPreparerService; - private final LogIndexer logIndexer; @Autowired public MergeLaunchHandlerImpl(LaunchRepository launchRepository, - TestItemRepository testItemRepository, - ProjectRepository projectRepository, LaunchMergeFactory launchMergeFactory, - LaunchConverter launchConverter, - LaunchPreparerService launchPreparerService, LogIndexer logIndexer) { + ProjectRepository projectRepository, + LaunchMergeFactory launchMergeFactory, LaunchConverter launchConverter, + LogIndexer logIndexer) { this.launchRepository = launchRepository; - this.testItemRepository = testItemRepository; this.projectRepository = projectRepository; this.launchMergeFactory = launchMergeFactory; this.launchConverter = launchConverter; - this.launchPreparerService = launchPreparerService; this.logIndexer = logIndexer; } @Override public LaunchResource mergeLaunches(ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, MergeLaunchesRQ rq) { - Project project = projectRepository.findById(projectDetails.getProjectId()) - .orElseThrow( - () -> new ReportPortalException(PROJECT_NOT_FOUND, projectDetails.getProjectName())); + Project project = projectRepository.findById(projectDetails.getProjectId()).orElseThrow( + () -> new ReportPortalException(PROJECT_NOT_FOUND, projectDetails.getProjectName())); Set launchesIds = rq.getLaunches(); expect(CollectionUtils.isNotEmpty(launchesIds), equalTo(true)).verify( - ErrorType.BAD_REQUEST_ERROR, - "At least one launch id should be specified for merging" - ); + ErrorType.BAD_REQUEST_ERROR, "At least one launch id should be specified for merging"); expect(launchesIds.size() > 0, equalTo(true)).verify(ErrorType.BAD_REQUEST_ERROR, "At least 1 launch id should be provided for merging" @@ -147,9 +135,9 @@ private void validateMergingLaunches(List launches, ReportPortalUser use * ADMINISTRATOR and PROJECT_MANAGER+ users have permission to merge not-only-own * launches */ - boolean isUserValidate = !(user.getUserRole().equals(ADMINISTRATOR) - || projectDetails.getProjectRole() - .sameOrHigherThan(ProjectRole.PROJECT_MANAGER)); + boolean isUserValidate = + !(user.getUserRole().equals(ADMINISTRATOR) || projectDetails.getProjectRole() + .sameOrHigherThan(ProjectRole.PROJECT_MANAGER)); launches.forEach(launch -> { expect(launch, notNull()).verify(LAUNCH_NOT_FOUND, launch); @@ -157,16 +145,16 @@ private void validateMergingLaunches(List launches, ReportPortalUser use expect(launch.getStatus(), not(Preconditions.statusIn(IN_PROGRESS))).verify( LAUNCH_IS_NOT_FINISHED, Suppliers.formattedSupplier("Cannot merge launch '{}' with status '{}'", launch.getId(), - launch.getStatus()) + launch.getStatus() + ) ); expect(launch.getProjectId(), equalTo(projectDetails.getProjectId())).verify( - FORBIDDEN_OPERATION, - "Impossible to merge launches from different projects." - ); + FORBIDDEN_OPERATION, "Impossible to merge launches from different projects."); if (isUserValidate) { - expect(launch.getUserId(), equalTo(user.getUserId())).verify(ACCESS_DENIED, + expect(launch.getUserId(), equalTo(user.getUserId())).verify( + ACCESS_DENIED, "You are not an owner of launches or have less than PROJECT_MANAGER project role." ); } diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/impl/MetadataUpdater.java b/src/main/java/com/epam/ta/reportportal/core/launch/impl/MetadataUpdater.java index 61e1470955..cf6c74cb07 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/impl/MetadataUpdater.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/impl/MetadataUpdater.java @@ -16,7 +16,7 @@ package com.epam.ta.reportportal.core.launch.impl; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; import java.util.Collection; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerAsyncImpl.java b/src/main/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerAsyncImpl.java index 9f90037d19..e837e76031 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerAsyncImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerAsyncImpl.java @@ -21,8 +21,8 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.core.launch.StartLaunchHandler; import com.epam.ta.reportportal.util.ReportingQueueService; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRS; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRS; import com.epam.ta.reportportal.ws.rabbit.MessageHeaders; import com.epam.ta.reportportal.ws.rabbit.RequestType; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerImpl.java index 43abc35b67..20ad6631a7 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerImpl.java @@ -27,8 +27,8 @@ import com.epam.ta.reportportal.dao.LaunchRepository; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.ws.converter.builders.LaunchBuilder; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRS; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRS; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/impl/StopLaunchHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/launch/impl/StopLaunchHandlerImpl.java index 7b87a8f0d6..f6a8ef9ebe 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/impl/StopLaunchHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/impl/StopLaunchHandlerImpl.java @@ -16,34 +16,32 @@ package com.epam.ta.reportportal.core.launch.impl; +import static com.epam.ta.reportportal.core.launch.util.LaunchValidator.validate; +import static com.epam.ta.reportportal.core.launch.util.LaunchValidator.validateRoles; +import static com.epam.ta.reportportal.entity.enums.StatusEnum.STOPPED; +import static java.util.Optional.ofNullable; +import static java.util.stream.Collectors.toList; + import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.core.events.MessageBus; import com.epam.ta.reportportal.core.events.activity.LaunchFinishedEvent; import com.epam.ta.reportportal.core.launch.StopLaunchHandler; import com.epam.ta.reportportal.dao.LaunchRepository; import com.epam.ta.reportportal.dao.TestItemRepository; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.BulkRQ; import com.epam.ta.reportportal.ws.converter.builders.LaunchBuilder; -import com.epam.ta.reportportal.ws.model.BulkRQ; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import java.util.Date; +import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.util.Date; -import java.util.List; - -import static com.epam.ta.reportportal.core.launch.util.LaunchValidator.validate; -import static com.epam.ta.reportportal.core.launch.util.LaunchValidator.validateRoles; -import static com.epam.ta.reportportal.entity.enums.StatusEnum.STOPPED; -import static java.util.Optional.ofNullable; -import static java.util.stream.Collectors.toList; - /** * @author Ihar Kahadouski */ @@ -51,52 +49,50 @@ @Transactional public class StopLaunchHandlerImpl implements StopLaunchHandler { - private static final String LAUNCH_STOP_DESCRIPTION = " stopped"; + private static final String LAUNCH_STOP_DESCRIPTION = " stopped"; - private final LaunchRepository launchRepository; - private final TestItemRepository testItemRepository; - private final ApplicationEventPublisher eventPublisher; + private final LaunchRepository launchRepository; + private final TestItemRepository testItemRepository; + private final ApplicationEventPublisher eventPublisher; - @Autowired - public StopLaunchHandlerImpl(LaunchRepository launchRepository, TestItemRepository testItemRepository, - ApplicationEventPublisher eventPublisher) { - this.launchRepository = launchRepository; - this.testItemRepository = testItemRepository; - this.eventPublisher = eventPublisher; - } + @Autowired + public StopLaunchHandlerImpl(LaunchRepository launchRepository, + TestItemRepository testItemRepository, ApplicationEventPublisher eventPublisher) { + this.launchRepository = launchRepository; + this.testItemRepository = testItemRepository; + this.eventPublisher = eventPublisher; + } - @Override - public OperationCompletionRS stopLaunch(Long launchId, FinishExecutionRQ finishLaunchRQ, ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user) { - Launch launch = launchRepository.findById(launchId) - .orElseThrow(() -> new ReportPortalException(ErrorType.LAUNCH_NOT_FOUND, launchId)); + @Override + public OperationCompletionRS stopLaunch(Long launchId, FinishExecutionRQ finishLaunchRQ, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { + Launch launch = launchRepository.findById(launchId) + .orElseThrow(() -> new ReportPortalException(ErrorType.LAUNCH_NOT_FOUND, launchId)); - validateRoles(launch, user, projectDetails); - validate(launch, finishLaunchRQ); + validateRoles(launch, user, projectDetails); + validate(launch, finishLaunchRQ); - launch = new LaunchBuilder(launch).addDescription(ofNullable(finishLaunchRQ.getDescription()).orElse(ofNullable(launch.getDescription()) - .orElse("")).concat(LAUNCH_STOP_DESCRIPTION)) - .addStatus(ofNullable(finishLaunchRQ.getStatus()).orElse(STOPPED.name())) - .addEndTime(ofNullable(finishLaunchRQ.getEndTime()).orElse(new Date())) - .addAttributes(finishLaunchRQ.getAttributes()) - .addAttribute(new ItemAttributeResource("status", "stopped")) - .get(); + launch = new LaunchBuilder(launch).addDescription( + ofNullable(finishLaunchRQ.getDescription()).orElse( + ofNullable(launch.getDescription()).orElse("")).concat(LAUNCH_STOP_DESCRIPTION)) + .addStatus(ofNullable(finishLaunchRQ.getStatus()).orElse(STOPPED.name())) + .addEndTime(ofNullable(finishLaunchRQ.getEndTime()).orElse(new Date())) + .addAttributes(finishLaunchRQ.getAttributes()) + .addAttribute(new ItemAttributeResource("status", "stopped")).get(); - launchRepository.save(launch); - testItemRepository.interruptInProgressItems(launch.getId()); + launchRepository.save(launch); + testItemRepository.interruptInProgressItems(launch.getId()); eventPublisher.publishEvent( new LaunchFinishedEvent(launch, user.getUserId(), user.getUsername(), false)); - return new OperationCompletionRS("Launch with ID = '" + launchId + "' successfully stopped."); - } + return new OperationCompletionRS("Launch with ID = '" + launchId + "' successfully stopped."); + } - @Override - public List stopLaunch(BulkRQ bulkRQ, ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user) { - return bulkRQ.getEntities() - .entrySet() - .stream() - .map(entry -> stopLaunch(entry.getKey(), entry.getValue(), projectDetails, user)) - .collect(toList()); - } + @Override + public List stopLaunch(BulkRQ bulkRQ, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { + return bulkRQ.getEntities().entrySet().stream() + .map(entry -> stopLaunch(entry.getKey(), entry.getValue(), projectDetails, user)) + .collect(toList()); + } } diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/impl/UpdateLaunchHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/launch/impl/UpdateLaunchHandlerImpl.java index d1dcac32b6..347e9b6e35 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/impl/UpdateLaunchHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/impl/UpdateLaunchHandlerImpl.java @@ -22,10 +22,10 @@ import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.entity.project.ProjectRole.PROJECT_MANAGER; import static com.epam.ta.reportportal.entity.project.ProjectUtils.getConfigParameters; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; import static java.util.stream.Collectors.toList; import com.epam.ta.reportportal.commons.ReportPortalUser; @@ -50,16 +50,16 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.BulkRQ; +import com.epam.ta.reportportal.model.launch.AnalyzeLaunchRQ; +import com.epam.ta.reportportal.model.launch.UpdateLaunchRQ; +import com.epam.ta.reportportal.model.launch.cluster.CreateClustersRQ; import com.epam.ta.reportportal.util.ItemInfoUtils; import com.epam.ta.reportportal.ws.converter.builders.LaunchBuilder; import com.epam.ta.reportportal.ws.converter.converters.ItemAttributeConverter; -import com.epam.ta.reportportal.ws.model.BulkInfoUpdateRQ; -import com.epam.ta.reportportal.ws.model.BulkRQ; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.launch.AnalyzeLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.Mode; -import com.epam.ta.reportportal.ws.model.launch.UpdateLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.cluster.CreateClustersRQ; +import com.epam.ta.reportportal.ws.reporting.BulkInfoUpdateRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.Mode; import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; import com.google.common.collect.Lists; import java.util.List; @@ -93,11 +93,11 @@ public class UpdateLaunchHandlerImpl implements UpdateLaunchHandler { @Autowired public UpdateLaunchHandlerImpl(GetProjectHandler getProjectHandler, - GetLaunchHandler getLaunchHandler, - LaunchAccessValidator launchAccessValidator, LaunchRepository launchRepository, - LogIndexer logIndexer, + GetLaunchHandler getLaunchHandler, LaunchAccessValidator launchAccessValidator, + LaunchRepository launchRepository, LogIndexer logIndexer, Map launchAnalysisStrategyMapping, - @Qualifier("uniqueErrorAnalysisStarterAsync") UniqueErrorAnalysisStarter uniqueErrorAnalysisStarter) { + @Qualifier("uniqueErrorAnalysisStarterAsync") + UniqueErrorAnalysisStarter uniqueErrorAnalysisStarter) { this.getProjectHandler = getProjectHandler; this.getLaunchHandler = getLaunchHandler; this.launchAccessValidator = launchAccessValidator; @@ -109,8 +109,7 @@ public UpdateLaunchHandlerImpl(GetProjectHandler getProjectHandler, @Override public OperationCompletionRS updateLaunch(Long launchId, - ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, - UpdateLaunchRQ rq) { + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user, UpdateLaunchRQ rq) { Project project = getProjectHandler.get(projectDetails); Launch launch = launchRepository.findById(launchId) .orElseThrow(() -> new ReportPortalException(LAUNCH_NOT_FOUND, launchId.toString())); @@ -118,10 +117,8 @@ public OperationCompletionRS updateLaunch(Long launchId, LaunchModeEnum previousMode = launch.getMode(); - launch = new LaunchBuilder(launch).addMode(rq.getMode()) - .addDescription(rq.getDescription()) - .overwriteAttributes(rq.getAttributes()) - .get(); + launch = new LaunchBuilder(launch).addMode(rq.getMode()).addDescription(rq.getDescription()) + .overwriteAttributes(rq.getAttributes()).get(); launchRepository.save(launch); if (!previousMode.equals(launch.getMode())) { @@ -133,19 +130,15 @@ public OperationCompletionRS updateLaunch(Long launchId, @Override public List updateLaunch(BulkRQ rq, - ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user) { - return rq.getEntities() - .entrySet() - .stream() + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { + return rq.getEntities().entrySet().stream() .map(entry -> updateLaunch(entry.getKey(), projectDetails, user, entry.getValue())) .collect(toList()); } @Override public OperationCompletionRS startLaunchAnalyzer(AnalyzeLaunchRQ analyzeRQ, - ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user) { + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { AnalyzerType analyzerType = AnalyzerType.fromString(analyzeRQ.getAnalyzerTypeName()); launchAnalysisStrategyMapping.get(analyzerType).analyze(analyzeRQ, projectDetails, user); return new OperationCompletionRS( @@ -156,38 +149,37 @@ public OperationCompletionRS startLaunchAnalyzer(AnalyzeLaunchRQ analyzeRQ, @Override @Transactional public OperationCompletionRS createClusters(CreateClustersRQ createClustersRQ, - ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user) { + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { final Launch launch = getLaunchHandler.get(createClustersRQ.getLaunchId()); launchAccessValidator.validate(launch, projectDetails, user); //TODO should be put inside *Validator after validators refactoring expect(launch.getStatus(), not(statusIn(StatusEnum.IN_PROGRESS))).verify(INCORRECT_REQUEST, - "Cannot analyze launch in progress."); + "Cannot analyze launch in progress." + ); final Project project = getProjectHandler.get(launch.getProjectId()); - final Map configParameters = getConfigParameters( - project.getProjectAttributes()); + final Map configParameters = + getConfigParameters(project.getProjectAttributes()); configParameters.put(ProjectAttributeEnum.UNIQUE_ERROR_ANALYZER_REMOVE_NUMBERS.getAttribute(), String.valueOf(createClustersRQ.isRemoveNumbers()) ); uniqueErrorAnalysisStarter.start(ClusterEntityContext.of(launch.getId(), launch.getProjectId()), - configParameters); + configParameters + ); return new OperationCompletionRS( Suppliers.formattedSupplier("Clusters generation for launch with ID='{}' started.", - launch.getId()) - .get()); + launch.getId() + ).get()); } @Override public OperationCompletionRS bulkInfoUpdate(BulkInfoUpdateRQ bulkUpdateRq, ReportPortalUser.ProjectDetails projectDetails) { expect(getProjectHandler.exists(projectDetails.getProjectId()), Predicate.isEqual(true)).verify( - PROJECT_NOT_FOUND, - projectDetails.getProjectId() - ); + PROJECT_NOT_FOUND, projectDetails.getProjectId()); List launches = launchRepository.findAllById(bulkUpdateRq.getIds()); launches.forEach( @@ -198,8 +190,8 @@ public OperationCompletionRS bulkInfoUpdate(BulkInfoUpdateRQ bulkUpdateRq, switch (it.getAction()) { case DELETE: { launches.forEach(launch -> { - ItemAttribute toDelete = ItemInfoUtils.findAttributeByResource(launch.getAttributes(), - it.getFrom()); + ItemAttribute toDelete = + ItemInfoUtils.findAttributeByResource(launch.getAttributes(), it.getFrom()); launch.getAttributes().remove(toDelete); }); break; @@ -212,8 +204,8 @@ public OperationCompletionRS bulkInfoUpdate(BulkInfoUpdateRQ bulkUpdateRq, launches.stream() .filter(launch -> ItemInfoUtils.containsAttribute(launch.getAttributes(), it.getTo())) .forEach(launch -> { - ItemAttribute itemAttribute = ItemAttributeConverter.FROM_RESOURCE.apply( - it.getTo()); + ItemAttribute itemAttribute = + ItemAttributeConverter.FROM_RESOURCE.apply(it.getTo()); itemAttribute.setLaunch(launch); launch.getAttributes().add(itemAttribute); }); diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/rerun/RerunHandler.java b/src/main/java/com/epam/ta/reportportal/core/launch/rerun/RerunHandler.java index 031ac97508..e438b57cdf 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/rerun/RerunHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/rerun/RerunHandler.java @@ -19,9 +19,9 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.item.ItemCreatedRS; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.ItemCreatedRS; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; import java.util.Optional; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/rerun/RerunHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/launch/rerun/RerunHandlerImpl.java index 7933d0421e..d7b67ec675 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/rerun/RerunHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/rerun/RerunHandlerImpl.java @@ -43,10 +43,10 @@ import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.converter.builders.TestCaseIdEntry; import com.epam.ta.reportportal.ws.converter.builders.TestItemBuilder; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.item.ItemCreatedRS; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.ItemCreatedRS; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; import java.util.Collections; import java.util.List; import java.util.Objects; diff --git a/src/main/java/com/epam/ta/reportportal/core/launch/util/LaunchValidator.java b/src/main/java/com/epam/ta/reportportal/core/launch/util/LaunchValidator.java index e8825eafd2..9f116a3e25 100644 --- a/src/main/java/com/epam/ta/reportportal/core/launch/util/LaunchValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/launch/util/LaunchValidator.java @@ -26,10 +26,10 @@ import static com.epam.ta.reportportal.entity.enums.StatusEnum.PASSED; import static com.epam.ta.reportportal.entity.enums.StatusEnum.SKIPPED; import static com.epam.ta.reportportal.entity.project.ProjectRole.PROJECT_MANAGER; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.FINISH_LAUNCH_NOT_ALLOWED; -import static com.epam.ta.reportportal.ws.model.ErrorType.FINISH_TIME_EARLIER_THAN_START_TIME; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_FINISH_STATUS; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FINISH_LAUNCH_NOT_ALLOWED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FINISH_TIME_EARLIER_THAN_START_TIME; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_FINISH_STATUS; import com.epam.ta.reportportal.commons.Preconditions; import com.epam.ta.reportportal.commons.ReportPortalUser; @@ -37,7 +37,7 @@ import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.user.UserRole; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; import java.util.function.Predicate; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/log/CreateLogHandler.java b/src/main/java/com/epam/ta/reportportal/core/log/CreateLogHandler.java index 4e584d1504..8570ecad24 100644 --- a/src/main/java/com/epam/ta/reportportal/core/log/CreateLogHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/log/CreateLogHandler.java @@ -22,9 +22,9 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.validation.Suppliers; import com.epam.ta.reportportal.entity.enums.LogLevel; -import com.epam.ta.reportportal.ws.model.EntryCreatedAsyncRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.EntryCreatedAsyncRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.springframework.web.multipart.MultipartFile; diff --git a/src/main/java/com/epam/ta/reportportal/core/log/DeleteLogHandler.java b/src/main/java/com/epam/ta/reportportal/core/log/DeleteLogHandler.java index d212f2129e..8493624fa2 100644 --- a/src/main/java/com/epam/ta/reportportal/core/log/DeleteLogHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/log/DeleteLogHandler.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.log; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; public interface DeleteLogHandler { diff --git a/src/main/java/com/epam/ta/reportportal/core/log/ElasticLogService.java b/src/main/java/com/epam/ta/reportportal/core/log/ElasticLogService.java index c836c6d521..afa2e92f3a 100644 --- a/src/main/java/com/epam/ta/reportportal/core/log/ElasticLogService.java +++ b/src/main/java/com/epam/ta/reportportal/core/log/ElasticLogService.java @@ -39,7 +39,7 @@ @Primary @Service -@ConditionalOnProperty(prefix = "rp.elasticsearch", name = "host") +@ConditionalOnProperty(prefix = "rp.searchengine", name = "host") public class ElasticLogService implements LogService { private final AmqpTemplate amqpTemplate; diff --git a/src/main/java/com/epam/ta/reportportal/core/log/GetLogHandler.java b/src/main/java/com/epam/ta/reportportal/core/log/GetLogHandler.java index 7b8b44e682..bc53a8602e 100644 --- a/src/main/java/com/epam/ta/reportportal/core/log/GetLogHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/log/GetLogHandler.java @@ -22,8 +22,8 @@ import com.epam.ta.reportportal.core.log.impl.PagedLogResource; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.log.Log; -import com.epam.ta.reportportal.ws.model.log.GetLogsUnderRq; -import com.epam.ta.reportportal.ws.model.log.LogResource; +import com.epam.ta.reportportal.model.log.GetLogsUnderRq; +import com.epam.ta.reportportal.model.log.LogResource; import java.util.List; import java.util.Map; import org.springframework.data.domain.Pageable; @@ -38,10 +38,10 @@ public interface GetLogHandler { /** * Returns logs for specified filter * - * @param filterable - filter definition - * @param pageable - pageable definition - * @param path - logs path - * @param projectDetails - project details + * @param filterable - filter definition + * @param pageable - pageable definition + * @param path - logs path + * @param projectDetails - project details * @return mapping with {@link TestItem#getItemId()} as key and its list of {@link LogResource} as value */ Iterable getLogs(String path, ReportPortalUser.ProjectDetails projectDetails, @@ -88,11 +88,10 @@ long getPageNumber(Long logId, ReportPortalUser.ProjectDetails projectDetails, F * @param queryable {@link Queryable} * @param pageable {@link Pageable} * @return The {@link Iterable} of {@link LogResource} and - * {@link com.epam.ta.reportportal.ws.model.NestedStepResource} entities + * {@link com.epam.ta.reportportal.model.NestedStepResource} entities */ Iterable getNestedItems(Long parentId, ReportPortalUser.ProjectDetails projectDetails, - Map params, - Queryable queryable, Pageable pageable); + Map params, Queryable queryable, Pageable pageable); List getLogsWithLocation(Long parentId, ReportPortalUser.ProjectDetails projectDetails, Map params, diff --git a/src/main/java/com/epam/ta/reportportal/core/log/impl/CreateLogHandlerAsyncImpl.java b/src/main/java/com/epam/ta/reportportal/core/log/impl/CreateLogHandlerAsyncImpl.java index 371d492f8b..9524b53465 100644 --- a/src/main/java/com/epam/ta/reportportal/core/log/impl/CreateLogHandlerAsyncImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/log/impl/CreateLogHandlerAsyncImpl.java @@ -23,8 +23,8 @@ import com.epam.ta.reportportal.core.configs.rabbit.DeserializablePair; import com.epam.ta.reportportal.core.log.CreateLogHandler; import com.epam.ta.reportportal.util.ReportingQueueService; -import com.epam.ta.reportportal.ws.model.EntryCreatedAsyncRS; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.EntryCreatedAsyncRS; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; import com.epam.ta.reportportal.ws.rabbit.MessageHeaders; import com.epam.ta.reportportal.ws.rabbit.RequestType; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/log/impl/CreateLogHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/log/impl/CreateLogHandlerImpl.java index ecaafb91dc..dd8604d854 100644 --- a/src/main/java/com/epam/ta/reportportal/core/log/impl/CreateLogHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/log/impl/CreateLogHandlerImpl.java @@ -34,9 +34,9 @@ import com.epam.ta.reportportal.entity.log.LogFull; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.converter.builders.LogFullBuilder; -import com.epam.ta.reportportal.ws.model.EntryCreatedAsyncRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.EntryCreatedAsyncRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.concurrent.CompletableFuture; diff --git a/src/main/java/com/epam/ta/reportportal/core/log/impl/DeleteLogHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/log/impl/DeleteLogHandlerImpl.java index a305082dd3..baece541f8 100644 --- a/src/main/java/com/epam/ta/reportportal/core/log/impl/DeleteLogHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/log/impl/DeleteLogHandlerImpl.java @@ -22,11 +22,11 @@ import static com.epam.ta.reportportal.commons.Predicates.notNull; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.FORBIDDEN_OPERATION; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_IS_NOT_FINISHED; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.TEST_ITEM_IS_NOT_FINISHED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FORBIDDEN_OPERATION; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_IS_NOT_FINISHED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.TEST_ITEM_IS_NOT_FINISHED; import static java.util.Optional.ofNullable; import com.epam.ta.reportportal.commons.ReportPortalUser; @@ -45,8 +45,8 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.Collections; import java.util.Objects; import java.util.Optional; diff --git a/src/main/java/com/epam/ta/reportportal/core/log/impl/GetLogHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/log/impl/GetLogHandlerImpl.java index c83b40440a..c0ee9fe615 100644 --- a/src/main/java/com/epam/ta/reportportal/core/log/impl/GetLogHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/log/impl/GetLogHandlerImpl.java @@ -22,8 +22,8 @@ import static com.epam.ta.reportportal.commons.querygen.constant.TestItemCriteriaConstant.CRITERIA_RETRY_PARENT_LAUNCH_ID; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; -import static com.epam.ta.reportportal.ws.model.ErrorType.FORBIDDEN_OPERATION; -import static com.epam.ta.reportportal.ws.model.ErrorType.LOG_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FORBIDDEN_OPERATION; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LOG_NOT_FOUND; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toMap; @@ -53,12 +53,12 @@ import com.epam.ta.reportportal.entity.log.Log; import com.epam.ta.reportportal.entity.log.LogFull; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.log.GetLogsUnderRq; +import com.epam.ta.reportportal.model.log.LogResource; import com.epam.ta.reportportal.ws.converter.PagedResourcesAssembler; import com.epam.ta.reportportal.ws.converter.converters.LogConverter; import com.epam.ta.reportportal.ws.converter.converters.TestItemConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.log.GetLogsUnderRq; -import com.epam.ta.reportportal.ws.model.log.LogResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Lists; import java.util.AbstractMap; import java.util.Collections; @@ -113,11 +113,12 @@ public GetLogHandlerImpl(LogRepository logRepository, LogService logService, @Override public Iterable getLogs(@Nullable String path, - ReportPortalUser.ProjectDetails projectDetails, Filter filterable, - Pageable pageable) { + ReportPortalUser.ProjectDetails projectDetails, Filter filterable, Pageable pageable) { ofNullable(path).ifPresent(p -> updateFilter(filterable, p)); - Page logFullPage = logService.findByFilter( - ProjectFilter.of(filterable, projectDetails.getProjectId()), pageable); + Page logFullPage = + logService.findByFilter(ProjectFilter.of(filterable, projectDetails.getProjectId()), + pageable + ); return PagedResourcesAssembler.pageConverter(LogConverter.TO_RESOURCE).apply(logFullPage); } @@ -125,20 +126,16 @@ public Iterable getLogs(@Nullable String path, public Map> getLogs(GetLogsUnderRq logsUnderRq, ReportPortalUser.ProjectDetails projectDetails) { - final LogLevel logLevel = LogLevel.toLevel(logsUnderRq.getLogLevel()) - .orElseThrow(() -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, - logsUnderRq.getLogLevel())); + final LogLevel logLevel = LogLevel.toLevel(logsUnderRq.getLogLevel()).orElseThrow( + () -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, logsUnderRq.getLogLevel())); return testItemRepository.findAllById(logsUnderRq.getItemIds()).stream() .collect(toMap(TestItem::getItemId, item -> { final Launch launch = testItemService.getEffectiveLaunch(item); validate(launch, projectDetails); return logService.findLatestUnderTestItemByLaunchIdAndTestItemIdsAndLogLevelGte( - launch.getId(), - item.getItemId(), - logLevel.toInt(), - LOG_UNDER_ITEM_BATCH_SIZE - ).stream().map(LogConverter.TO_RESOURCE).collect(Collectors.toList()); + launch.getId(), item.getItemId(), logLevel.toInt(), LOG_UNDER_ITEM_BATCH_SIZE) + .stream().map(LogConverter.TO_RESOURCE).collect(Collectors.toList()); })); } @@ -163,43 +160,37 @@ public LogResource getLog(String logId, ReportPortalUser.ProjectDetails projectD @Override public Iterable getNestedItems(Long parentId, ReportPortalUser.ProjectDetails projectDetails, - Map params, - Queryable queryable, Pageable pageable) { + Map params, Queryable queryable, Pageable pageable) { TestItem parentItem = testItemRepository.findById(parentId) .orElseThrow(() -> new ReportPortalException(ErrorType.TEST_ITEM_NOT_FOUND, parentId)); Launch launch = testItemService.getEffectiveLaunch(parentItem); validate(launch, projectDetails); - Boolean excludeEmptySteps = ofNullable(params.get(EXCLUDE_EMPTY_STEPS)).map( - BooleanUtils::toBoolean).orElse(false); - Boolean excludePassedLogs = ofNullable(params.get(EXCLUDE_PASSED_LOGS)).map( - BooleanUtils::toBoolean).orElse(false); + Boolean excludeEmptySteps = + ofNullable(params.get(EXCLUDE_EMPTY_STEPS)).map(BooleanUtils::toBoolean).orElse(false); + Boolean excludePassedLogs = + ofNullable(params.get(EXCLUDE_PASSED_LOGS)).map(BooleanUtils::toBoolean).orElse(false); - Page nestedItems = logRepository.findNestedItems(parentId, - excludeEmptySteps, - isLogsExclusionRequired(parentItem, excludePassedLogs), - queryable, - pageable + Page nestedItems = logRepository.findNestedItems(parentId, excludeEmptySteps, + isLogsExclusionRequired(parentItem, excludePassedLogs), queryable, pageable ); List content = nestedItems.getContent(); - Map> result = content.stream() - .collect(groupingBy(NestedItem::getType)); + Map> result = + content.stream().collect(groupingBy(NestedItem::getType)); Map logMap = ofNullable(result.get(LogRepositoryConstants.LOG)).map( - logs -> logService.findAllById(logs.stream() - .map(NestedItem::getId) - .collect(Collectors.toSet())).stream().collect(toMap(LogFull::getId, l -> l))) - .orElseGet(Collections::emptyMap); + logs -> logService.findAllById( + logs.stream().map(NestedItem::getId).collect(Collectors.toSet())).stream() + .collect(toMap(LogFull::getId, l -> l))).orElseGet(Collections::emptyMap); queryable.getFilterConditions().add(getLaunchCondition(launch.getId())); queryable.getFilterConditions().add(getParentPathCondition(parentItem)); Map nestedStepMap = ofNullable(result.get(LogRepositoryConstants.ITEM)).map( testItems -> testItemRepository.findAllNestedStepsByIds( - testItems.stream().map(NestedItem::getId).collect(Collectors.toSet()), - queryable, + testItems.stream().map(NestedItem::getId).collect(Collectors.toSet()), queryable, excludePassedLogs ).stream().collect(toMap(NestedStep::getId, i -> i))).orElseGet(Collections::emptyMap); @@ -214,36 +205,38 @@ public Iterable getNestedItems(Long parentId, ReportPortalUser.ProjectDetails } }); - return PagedResourcesAssembler.pageConverter() - .apply(PageableExecutionUtils.getPage(resources, nestedItems.getPageable(), - nestedItems::getTotalElements)); + return PagedResourcesAssembler.pageConverter().apply( + PageableExecutionUtils.getPage(resources, nestedItems.getPageable(), + nestedItems::getTotalElements + )); } @Override public List getLogsWithLocation(Long parentId, - ReportPortalUser.ProjectDetails projectDetails, - Map params, Queryable queryable, Pageable pageable) { + ReportPortalUser.ProjectDetails projectDetails, Map params, + Queryable queryable, Pageable pageable) { TestItem parentItem = testItemRepository.findById(parentId) .orElseThrow(() -> new ReportPortalException(ErrorType.TEST_ITEM_NOT_FOUND, parentId)); Launch launch = testItemService.getEffectiveLaunch(parentItem); validate(launch, projectDetails); - Boolean excludeEmptySteps = ofNullable(params.get(EXCLUDE_EMPTY_STEPS)).map( - BooleanUtils::toBoolean).orElse(false); - Boolean excludePassedLogs = ofNullable(params.get(EXCLUDE_PASSED_LOGS)).map( - BooleanUtils::toBoolean).orElse(false); - Boolean excludeLogContent = ofNullable(params.get(EXCLUDE_LOG_CONTENT)).map( - BooleanUtils::toBoolean).orElse(false); + Boolean excludeEmptySteps = + ofNullable(params.get(EXCLUDE_EMPTY_STEPS)).map(BooleanUtils::toBoolean).orElse(false); + Boolean excludePassedLogs = + ofNullable(params.get(EXCLUDE_PASSED_LOGS)).map(BooleanUtils::toBoolean).orElse(false); + Boolean excludeLogContent = + ofNullable(params.get(EXCLUDE_LOG_CONTENT)).map(BooleanUtils::toBoolean).orElse(false); List loadedLogs = new LinkedList<>(); loadInnerLogs(parentId, loadedLogs, Collections.emptyList(), excludeEmptySteps, - excludePassedLogs, queryable, pageable); + excludePassedLogs, queryable, pageable + ); if (!excludeLogContent) { - Map logMap = logService.findAllById(loadedLogs.stream() - .map(PagedLogResource::getId) - .collect(Collectors.toSet())).stream().collect(toMap(LogFull::getId, l -> l)); + Map logMap = logService.findAllById( + loadedLogs.stream().map(PagedLogResource::getId).collect(Collectors.toSet())).stream() + .collect(toMap(LogFull::getId, l -> l)); loadedLogs.forEach(resource -> { final LogFull model = logMap.get(resource.getId()); LogConverter.FILL_WITH_LOG_CONTENT.apply(model, resource); @@ -253,9 +246,8 @@ public List getLogsWithLocation(Long parentId, } private void loadInnerLogs(Long parentId, List results, - List> pagesLocation, - boolean excludeEmptySteps, boolean excludePassedLogs, Queryable queryable, - Pageable pageable) { + List> pagesLocation, boolean excludeEmptySteps, + boolean excludePassedLogs, Queryable queryable, Pageable pageable) { TestItem parentItem = testItemRepository.findById(parentId) .orElseThrow(() -> new ReportPortalException(ErrorType.TEST_ITEM_NOT_FOUND, parentId)); @@ -264,35 +256,26 @@ private void loadInnerLogs(Long parentId, List results, return; } - final List nestedItems = logRepository.findNestedItemsWithPage( - parentId, - excludeEmptySteps, - isLogsExclusionRequired(parentItem, excludePassedLogs), - queryable, - pageable - ); - nestedItems.stream() - .filter(nestedItem -> nestedItem.getType().equals(LogRepositoryConstants.ITEM) - || nestedItem.getLogLevel() >= LogLevel.ERROR_INT) - .forEach(nestedItem -> { - List> copy = new LinkedList<>(pagesLocation); - copy.add(new AbstractMap.SimpleEntry<>(nestedItem.getId(), nestedItem.getPageNumber())); - if (nestedItem.getType().equals(LogRepositoryConstants.ITEM)) { - loadInnerLogs(nestedItem.getId(), - results, - copy, - excludeEmptySteps, - excludePassedLogs, - queryable, - PageRequest.of(1, NESTED_STEP_MAX_PAGE_SIZE, pageable.getSort()) - ); - } else { - PagedLogResource pagedLogResource = new PagedLogResource(); - pagedLogResource.setId(nestedItem.getId()); - pagedLogResource.setPagesLocation(copy); - results.add(pagedLogResource); - } - }); + final List nestedItems = + logRepository.findNestedItemsWithPage(parentId, excludeEmptySteps, + isLogsExclusionRequired(parentItem, excludePassedLogs), queryable, pageable + ); + nestedItems.stream().filter( + nestedItem -> nestedItem.getType().equals(LogRepositoryConstants.ITEM) + || nestedItem.getLogLevel() >= LogLevel.ERROR_INT).forEach(nestedItem -> { + List> copy = new LinkedList<>(pagesLocation); + copy.add(new AbstractMap.SimpleEntry<>(nestedItem.getId(), nestedItem.getPageNumber())); + if (nestedItem.getType().equals(LogRepositoryConstants.ITEM)) { + loadInnerLogs(nestedItem.getId(), results, copy, excludeEmptySteps, excludePassedLogs, + queryable, PageRequest.of(1, NESTED_STEP_MAX_PAGE_SIZE, pageable.getSort()) + ); + } else { + PagedLogResource pagedLogResource = new PagedLogResource(); + pagedLogResource.setId(nestedItem.getId()); + pagedLogResource.setPagesLocation(copy); + results.add(pagedLogResource); + } + }); } /** @@ -308,7 +291,8 @@ private void validate(LogFull log, ReportPortalUser.ProjectDetails projectDetail expect(launchProjectId, equalTo(projectDetails.getProjectId())).verify(FORBIDDEN_OPERATION, formattedSupplier("Log '{}' is not under '{}' project", log.getId(), - projectDetails.getProjectName()) + projectDetails.getProjectName() + ) ); } @@ -316,7 +300,8 @@ private void validate(Launch launch, ReportPortalUser.ProjectDetails projectDeta expect(launch.getProjectId(), equalTo(projectDetails.getProjectId())).verify( FORBIDDEN_OPERATION, formattedSupplier("Launch '{}' is not under '{}' project", launch.getId(), - projectDetails.getProjectName()) + projectDetails.getProjectName() + ) ); } @@ -363,16 +348,15 @@ private void updateFilter(Filter filterable, String path) { Launch launch = testItemService.getEffectiveLaunch(testItem); - FilterCondition.ConditionBuilder itemLaunchIdConditionBuilder = FilterCondition.builder() - .eq(CRITERIA_ITEM_LAUNCH_ID, String.valueOf(launch.getId())); + FilterCondition.ConditionBuilder itemLaunchIdConditionBuilder = + FilterCondition.builder().eq(CRITERIA_ITEM_LAUNCH_ID, String.valueOf(launch.getId())); ConvertibleCondition launchIdCondition = ofNullable(testItem.getRetryOf()).map( retryOf -> (ConvertibleCondition) new CompositeFilterCondition( Lists.newArrayList(itemLaunchIdConditionBuilder.withOperator(Operator.OR).build(), FilterCondition.builder() .eq(CRITERIA_RETRY_PARENT_LAUNCH_ID, String.valueOf(launch.getId())) - .withOperator(Operator.OR) - .build() + .withOperator(Operator.OR).build() ))).orElseGet(itemLaunchIdConditionBuilder::build); filterable.getFilterConditions().add(launchIdCondition); @@ -387,34 +371,28 @@ private void updateFilter(Filter filterable, String path) { * @param filterable {@link Filter} with {@link FilterTarget#getClazz()} of {@link Log} */ private void updatePathCondition(TestItem testItem, Filter filterable) { - List resultConditions = filterable.getFilterConditions() - .stream() - .flatMap(c -> c.getAllConditions().stream()) - .filter(c -> BooleanUtils.isFalse( - CRITERIA_PATH.equals(c.getSearchCriteria()) && Condition.UNDER.equals( - c.getCondition()))) - .collect(Collectors.toList()); + List resultConditions = + filterable.getFilterConditions().stream().flatMap(c -> c.getAllConditions().stream()) + .filter(c -> BooleanUtils.isFalse( + CRITERIA_PATH.equals(c.getSearchCriteria()) && Condition.UNDER.equals( + c.getCondition()))).collect(Collectors.toList()); filterable.getFilterConditions().clear(); FilterCondition parentPathCondition = getParentPathCondition(testItem); resultConditions.add(ofNullable(testItem.getRetryOf()).map( - retryParent -> (ConvertibleCondition) new CompositeFilterCondition(Lists.newArrayList( - parentPathCondition, - FilterCondition.builder() - .withOperator(Operator.OR) - .withCondition(Condition.UNDER) - .withSearchCriteria(CRITERIA_PATH) - .withValue(String.valueOf(testItem.getPath())) - .build() - ))).orElse(parentPathCondition)); + retryParent -> (ConvertibleCondition) new CompositeFilterCondition( + Lists.newArrayList(parentPathCondition, + FilterCondition.builder().withOperator(Operator.OR).withCondition(Condition.UNDER) + .withSearchCriteria(CRITERIA_PATH).withValue(String.valueOf(testItem.getPath())) + .build() + ))).orElse(parentPathCondition)); filterable.getFilterConditions().addAll(resultConditions); } private FilterCondition getParentPathCondition(TestItem parent) { String pathValue = ofNullable(parent.getRetryOf()).flatMap( - retryParentId -> ofNullable(parent.getParentId()).flatMap( - testItemRepository::findById) + retryParentId -> ofNullable(parent.getParentId()).flatMap(testItemRepository::findById) .map(retryParent -> retryParent.getPath() + "." + parent.getItemId())) .orElse(parent.getPath()); return FilterCondition.builder().withCondition(Condition.UNDER) diff --git a/src/main/java/com/epam/ta/reportportal/core/log/impl/PagedLogResource.java b/src/main/java/com/epam/ta/reportportal/core/log/impl/PagedLogResource.java index 24804eb9f8..28a8fdba89 100644 --- a/src/main/java/com/epam/ta/reportportal/core/log/impl/PagedLogResource.java +++ b/src/main/java/com/epam/ta/reportportal/core/log/impl/PagedLogResource.java @@ -1,6 +1,6 @@ package com.epam.ta.reportportal.core.log.impl; -import com.epam.ta.reportportal.ws.model.log.LogResource; +import com.epam.ta.reportportal.model.log.LogResource; import java.util.LinkedList; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/log/impl/SaveLogBinaryDataTaskAsync.java b/src/main/java/com/epam/ta/reportportal/core/log/impl/SaveLogBinaryDataTaskAsync.java index e7ff9292b2..9bdf7190f9 100644 --- a/src/main/java/com/epam/ta/reportportal/core/log/impl/SaveLogBinaryDataTaskAsync.java +++ b/src/main/java/com/epam/ta/reportportal/core/log/impl/SaveLogBinaryDataTaskAsync.java @@ -20,8 +20,8 @@ import com.epam.ta.reportportal.commons.BinaryDataMetaInfo; import com.epam.ta.reportportal.entity.attachment.AttachmentMetaInfo; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; import com.google.common.base.Preconditions; import java.util.Optional; import java.util.function.Supplier; diff --git a/src/main/java/com/epam/ta/reportportal/core/onboarding/OnboardingService.java b/src/main/java/com/epam/ta/reportportal/core/onboarding/OnboardingService.java index 11cb4d0d80..fe3d559ae7 100644 --- a/src/main/java/com/epam/ta/reportportal/core/onboarding/OnboardingService.java +++ b/src/main/java/com/epam/ta/reportportal/core/onboarding/OnboardingService.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.dao.OnboardingRepository; import com.epam.ta.reportportal.entity.onboarding.Onboarding; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/src/main/java/com/epam/ta/reportportal/core/preference/GetPreferenceHandler.java b/src/main/java/com/epam/ta/reportportal/core/preference/GetPreferenceHandler.java index 83d48cd36e..ce0262f8c7 100644 --- a/src/main/java/com/epam/ta/reportportal/core/preference/GetPreferenceHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/preference/GetPreferenceHandler.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.preference; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.preference.PreferenceResource; +import com.epam.ta.reportportal.model.preference.PreferenceResource; /** * Get user preference handler diff --git a/src/main/java/com/epam/ta/reportportal/core/preference/UpdatePreferenceHandler.java b/src/main/java/com/epam/ta/reportportal/core/preference/UpdatePreferenceHandler.java index cfb3c7fdf3..2dc5b9159d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/preference/UpdatePreferenceHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/preference/UpdatePreferenceHandler.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.preference; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * Update user preference handler diff --git a/src/main/java/com/epam/ta/reportportal/core/preference/impl/GetPreferenceHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/preference/impl/GetPreferenceHandlerImpl.java index 0835adf044..004fb6559c 100644 --- a/src/main/java/com/epam/ta/reportportal/core/preference/impl/GetPreferenceHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/preference/impl/GetPreferenceHandlerImpl.java @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.core.preference.impl; import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.core.preference.GetPreferenceHandler; import com.epam.ta.reportportal.dao.UserPreferenceRepository; import com.epam.ta.reportportal.entity.preference.UserPreference; +import com.epam.ta.reportportal.model.filter.UserFilterResource; +import com.epam.ta.reportportal.model.preference.PreferenceResource; import com.epam.ta.reportportal.ws.converter.converters.UserFilterConverter; -import com.epam.ta.reportportal.ws.model.filter.UserFilterResource; -import com.epam.ta.reportportal.ws.model.preference.PreferenceResource; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; @@ -45,10 +46,10 @@ public GetPreferenceHandlerImpl(UserPreferenceRepository userPreferenceRepositor @Override public PreferenceResource getPreference(ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { - List userPreferences = userPreferenceRepository.findByProjectIdAndUserId( - projectDetails.getProjectId(), - user.getUserId() - ); + List userPreferences = + userPreferenceRepository.findByProjectIdAndUserId(projectDetails.getProjectId(), + user.getUserId() + ); PreferenceResource preferenceResource = new PreferenceResource(); preferenceResource.setUserId(user.getUserId()); preferenceResource.setProjectId(projectDetails.getProjectId()); diff --git a/src/main/java/com/epam/ta/reportportal/core/preference/impl/UpdatePreferenceHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/preference/impl/UpdatePreferenceHandlerImpl.java index 3d446ad73a..0c5706e0f0 100644 --- a/src/main/java/com/epam/ta/reportportal/core/preference/impl/UpdatePreferenceHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/preference/impl/UpdatePreferenceHandlerImpl.java @@ -24,8 +24,8 @@ import com.epam.ta.reportportal.entity.preference.UserPreference; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.converter.builders.UserPreferenceBuilder; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/core/project/CreateProjectHandler.java b/src/main/java/com/epam/ta/reportportal/core/project/CreateProjectHandler.java index a7fb7e1bd7..79f5524353 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/CreateProjectHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/CreateProjectHandler.java @@ -19,8 +19,8 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.user.User; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.project.CreateProjectRQ; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.project.CreateProjectRQ; /** * Create {@link Project} request handler diff --git a/src/main/java/com/epam/ta/reportportal/core/project/DeleteProjectHandler.java b/src/main/java/com/epam/ta/reportportal/core/project/DeleteProjectHandler.java index 2aa783949c..d6c1b0990c 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/DeleteProjectHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/DeleteProjectHandler.java @@ -18,8 +18,8 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.DeleteBulkRS; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.model.DeleteBulkRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.List; /** @@ -42,8 +42,8 @@ public interface DeleteProjectHandler { /** * Delete specified project. * - * @param ids projects ids - * @param user {@link ReportPortalUser} + * @param ids projects ids + * @param user {@link ReportPortalUser} * @return Bulk result of operation * @throws ReportPortalException if project not found */ diff --git a/src/main/java/com/epam/ta/reportportal/core/project/GetProjectHandler.java b/src/main/java/com/epam/ta/reportportal/core/project/GetProjectHandler.java index 81ee3dc926..7e215e4328 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/GetProjectHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/GetProjectHandler.java @@ -21,9 +21,9 @@ import com.epam.ta.reportportal.commons.querygen.Queryable; import com.epam.ta.reportportal.entity.jasper.ReportFormat; import com.epam.ta.reportportal.entity.project.Project; -import com.epam.ta.reportportal.ws.model.project.ProjectResource; -import com.epam.ta.reportportal.ws.model.user.SearchUserResource; -import com.epam.ta.reportportal.ws.model.user.UserResource; +import com.epam.ta.reportportal.model.project.ProjectResource; +import com.epam.ta.reportportal.model.user.SearchUserResource; +import com.epam.ta.reportportal.model.user.UserResource; import java.io.OutputStream; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/project/GetProjectInfoHandler.java b/src/main/java/com/epam/ta/reportportal/core/project/GetProjectInfoHandler.java index 8cc231aed3..4e3a674986 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/GetProjectInfoHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/GetProjectInfoHandler.java @@ -18,12 +18,12 @@ import com.epam.ta.reportportal.commons.querygen.Queryable; import com.epam.ta.reportportal.entity.enums.InfoInterval; -import com.epam.ta.reportportal.ws.model.project.ProjectInfoResource; +import com.epam.ta.reportportal.model.project.ProjectInfoResource; import java.util.Map; import org.springframework.data.domain.Pageable; /** - * Get {@link com.epam.ta.reportportal.ws.model.project.ProjectInfoResource} request handler + * Get {@link ProjectInfoResource} request handler * * @author Dzmitry_Kavalets */ @@ -32,7 +32,7 @@ public interface GetProjectInfoHandler { /** * Get all projects info * - * @param filter Queryable filter to apply on the projects + * @param filter Queryable filter to apply on the projects * @param pageable Pagination information for the results * @return An {@link Iterable} of {@link ProjectInfoResource} containing information about all projects */ diff --git a/src/main/java/com/epam/ta/reportportal/core/project/UpdateProjectHandler.java b/src/main/java/com/epam/ta/reportportal/core/project/UpdateProjectHandler.java index 784fc1f690..a3dca955e5 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/UpdateProjectHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/UpdateProjectHandler.java @@ -19,11 +19,11 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.project.AssignUsersRQ; -import com.epam.ta.reportportal.ws.model.project.UnassignUsersRQ; -import com.epam.ta.reportportal.ws.model.project.UpdateProjectRQ; -import com.epam.ta.reportportal.ws.model.project.email.ProjectNotificationConfigDTO; +import com.epam.ta.reportportal.model.project.AssignUsersRQ; +import com.epam.ta.reportportal.model.project.UnassignUsersRQ; +import com.epam.ta.reportportal.model.project.UpdateProjectRQ; +import com.epam.ta.reportportal.model.project.email.ProjectNotificationConfigDTO; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * Update {@link com.epam.ta.reportportal.entity.project.Project} request handler diff --git a/src/main/java/com/epam/ta/reportportal/core/project/impl/CreateProjectHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/impl/CreateProjectHandlerImpl.java index fe7570343d..a8fa04c139 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/impl/CreateProjectHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/impl/CreateProjectHandlerImpl.java @@ -40,10 +40,10 @@ import com.epam.ta.reportportal.entity.user.ProjectUser; import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.project.CreateProjectRQ; import com.epam.ta.reportportal.util.PersonalProjectService; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.project.CreateProjectRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Date; import java.util.Optional; import java.util.Set; @@ -98,18 +98,20 @@ public EntryCreatedRS createProject(CreateProjectRQ createProjectRQ, ReportPorta ); expect(projectName, - com.epam.ta.reportportal.util.Predicates.SPECIAL_CHARS_ONLY.negate()).verify( - ErrorType.INCORRECT_REQUEST, + com.epam.ta.reportportal.util.Predicates.SPECIAL_CHARS_ONLY.negate() + ).verify(ErrorType.INCORRECT_REQUEST, Suppliers.formattedSupplier("Project name '{}' consists only of special characters", - projectName) + projectName + ) ); Optional existProject = projectRepository.findByName(projectName); expect(existProject, not(isPresent())).verify(ErrorType.PROJECT_ALREADY_EXISTS, projectName); - ProjectType projectType = ProjectType.findByName(createProjectRQ.getEntryType()) - .orElseThrow(() -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, - createProjectRQ.getEntryType())); + ProjectType projectType = ProjectType.findByName(createProjectRQ.getEntryType()).orElseThrow( + () -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, + createProjectRQ.getEntryType() + )); expect(projectType, equalTo(ProjectType.INTERNAL)).verify(ErrorType.BAD_REQUEST_ERROR, "Only internal projects can be created via API" ); diff --git a/src/main/java/com/epam/ta/reportportal/core/project/impl/DeleteProjectHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/impl/DeleteProjectHandlerImpl.java index db3b6140cc..586b0be6af 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/impl/DeleteProjectHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/impl/DeleteProjectHandlerImpl.java @@ -42,10 +42,10 @@ import com.epam.ta.reportportal.entity.project.ProjectIssueType; import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.DeleteBulkRS; import com.epam.ta.reportportal.util.FeatureFlagHandler; -import com.epam.ta.reportportal.ws.model.DeleteBulkRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.common.cache.Cache; import com.google.common.collect.Lists; import com.google.common.collect.Maps; diff --git a/src/main/java/com/epam/ta/reportportal/core/project/impl/GetProjectHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/impl/GetProjectHandlerImpl.java index 976ea58141..ce1ba05391 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/impl/GetProjectHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/impl/GetProjectHandlerImpl.java @@ -16,9 +16,21 @@ package com.epam.ta.reportportal.core.project.impl; +import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_PROJECT; +import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_PROJECT_ID; +import static com.epam.ta.reportportal.commons.querygen.constant.UserCriteriaConstant.CRITERIA_EMAIL; +import static com.epam.ta.reportportal.commons.querygen.constant.UserCriteriaConstant.CRITERIA_FULL_NAME; +import static com.epam.ta.reportportal.commons.querygen.constant.UserCriteriaConstant.CRITERIA_USER; +import static com.epam.ta.reportportal.core.analyzer.auto.impl.AnalyzerUtils.getAnalyzerConfig; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; + import com.epam.ta.reportportal.commons.Predicates; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.commons.querygen.*; +import com.epam.ta.reportportal.commons.querygen.CompositeFilterCondition; +import com.epam.ta.reportportal.commons.querygen.Condition; +import com.epam.ta.reportportal.commons.querygen.Filter; +import com.epam.ta.reportportal.commons.querygen.FilterCondition; +import com.epam.ta.reportportal.commons.querygen.Queryable; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.commons.validation.Suppliers; import com.epam.ta.reportportal.core.jasper.GetJasperReportHandler; @@ -30,13 +42,18 @@ import com.epam.ta.reportportal.entity.project.ProjectInfo; import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.project.ProjectResource; +import com.epam.ta.reportportal.model.user.SearchUserResource; +import com.epam.ta.reportportal.model.user.UserResource; import com.epam.ta.reportportal.ws.converter.PagedResourcesAssembler; import com.epam.ta.reportportal.ws.converter.converters.ProjectConverter; import com.epam.ta.reportportal.ws.converter.converters.UserConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.project.ProjectResource; -import com.epam.ta.reportportal.ws.model.user.SearchUserResource; -import com.epam.ta.reportportal.ws.model.user.UserResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import java.io.OutputStream; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; @@ -48,157 +65,156 @@ import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; -import java.io.OutputStream; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_PROJECT; -import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_PROJECT_ID; -import static com.epam.ta.reportportal.commons.querygen.constant.UserCriteriaConstant.*; -import static com.epam.ta.reportportal.core.analyzer.auto.impl.AnalyzerUtils.getAnalyzerConfig; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; - /** * @author Pavel Bortnik */ @Service public class GetProjectHandlerImpl implements GetProjectHandler { - private static final String LENGTH_LESS_THAN_1_SYMBOL_MSG = "Length of the filtering string " - + "'{}' is less than 1 symbol"; - - private final ProjectRepository projectRepository; - - private final UserRepository userRepository; - - private final GetJasperReportHandler jasperReportHandler; - - private final ProjectConverter projectConverter; - - @Autowired - public GetProjectHandlerImpl(ProjectRepository projectRepository, UserRepository userRepository, - @Qualifier("projectJasperReportHandler") GetJasperReportHandler jasperReportHandler, - ProjectConverter projectConverter) { - this.projectRepository = projectRepository; - this.userRepository = userRepository; - this.jasperReportHandler = jasperReportHandler; - this.projectConverter = projectConverter; - } - - @Override - public Iterable getProjectUsers(String projectName, Filter filter, Pageable pageable) { - Project project = projectRepository.findByName(projectName) - .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, projectName)); - if (CollectionUtils.isEmpty(project.getUsers())) { - return Collections.emptyList(); - } - filter.withCondition(new FilterCondition(Condition.EQUALS, false, String.valueOf(project.getId()), CRITERIA_PROJECT_ID)); - Page users = userRepository.findByFilterExcluding(filter, pageable, "email"); - return PagedResourcesAssembler.pageConverter(UserConverter.TO_RESOURCE).apply(users); - } - - @Override - public boolean exists(Long id) { - return projectRepository.existsById(id); - } - - @Override - public Project get(ReportPortalUser.ProjectDetails projectDetails) { - return projectRepository.findById(projectDetails.getProjectId()) - .orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, projectDetails.getProjectName())); - } - - @Override - public Project get(Long id) { - return projectRepository.findById(id).orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, id)); - } - - @Override - public Project get(String name) { - return projectRepository.findByName(name).orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, name)); - } - - @Override - public Project getRaw(String name) { - return projectRepository.findRawByName(name).orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, name)); - } - - @Override - public ProjectResource getResource(String projectName, ReportPortalUser user) { - - Project project = projectRepository.findByName(projectName) - .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, projectName)); - - return projectConverter.TO_PROJECT_RESOURCE.apply(project); - } - - @Override - public List getUserNames(ReportPortalUser.ProjectDetails projectDetails, String value) { - checkBusinessRuleLessThan1Symbol(value); - return userRepository.findNamesByProject(projectDetails.getProjectId(), value); - } - - private void checkBusinessRuleLessThan1Symbol(String value) { - BusinessRule.expect(value.length() >= 1, Predicates.equalTo(true)) - .verify(ErrorType.INCORRECT_FILTER_PARAMETERS, - Suppliers.formattedSupplier(LENGTH_LESS_THAN_1_SYMBOL_MSG, value)); - } - - @Override - public Iterable getUserNames(String value, ReportPortalUser.ProjectDetails projectDetails, Pageable pageable) { - checkBusinessRuleLessThan1Symbol(value); - - final CompositeFilterCondition userCondition = getUserSearchCondition(value); - - final Filter filter = Filter.builder() - .withTarget(User.class) - .withCondition(userCondition) - .withCondition(new FilterCondition(Operator.AND, Condition.ANY, true, projectDetails.getProjectName(), CRITERIA_PROJECT)) - .build(); - - return PagedResourcesAssembler.pageConverter(UserConverter.TO_SEARCH_RESOURCE) - .apply(userRepository.findByFilterExcludingProjects(filter, pageable)); - } - - private CompositeFilterCondition getUserSearchCondition(String value) { - return new CompositeFilterCondition(List.of(new FilterCondition(Operator.OR, Condition.CONTAINS, false, value, CRITERIA_USER), - new FilterCondition(Operator.OR, Condition.CONTAINS, false, value, CRITERIA_FULL_NAME), - new FilterCondition(Operator.OR, Condition.CONTAINS, false, value, CRITERIA_EMAIL) - ), Operator.AND); - } - - @Override - public List getAllProjectNames() { - return projectRepository.findAllProjectNames(); - } - - @Override - public List getAllProjectNamesByTerm(String term) { - return projectRepository.findAllProjectNamesByTerm(term); - } - - @Override - public void exportProjects(ReportFormat reportFormat, Queryable filter, OutputStream outputStream) { - - List projects = projectRepository.findProjectInfoByFilter(filter); - - List> data = projects.stream().map(jasperReportHandler::convertParams).collect(Collectors.toList()); - - JRDataSource jrDataSource = new JRBeanCollectionDataSource(data); - - //don't provide any params to not overwrite params from the Jasper template - JasperPrint jasperPrint = jasperReportHandler.getJasperPrint(null, jrDataSource); - - jasperReportHandler.writeReport(reportFormat, outputStream, jasperPrint); - } - - @Override - public Map getAnalyzerIndexingStatus() { - return projectRepository.findAll() - .stream() - .collect(Collectors.toMap(Project::getName, it -> getAnalyzerConfig(it).isIndexingRunning())); - } + private static final String LENGTH_LESS_THAN_1_SYMBOL_MSG = + "Length of the filtering string " + "'{}' is less than 1 symbol"; + + private final ProjectRepository projectRepository; + + private final UserRepository userRepository; + + private final GetJasperReportHandler jasperReportHandler; + + private final ProjectConverter projectConverter; + + @Autowired + public GetProjectHandlerImpl(ProjectRepository projectRepository, UserRepository userRepository, + @Qualifier("projectJasperReportHandler") + GetJasperReportHandler jasperReportHandler, ProjectConverter projectConverter) { + this.projectRepository = projectRepository; + this.userRepository = userRepository; + this.jasperReportHandler = jasperReportHandler; + this.projectConverter = projectConverter; + } + + @Override + public Iterable getProjectUsers(String projectName, Filter filter, + Pageable pageable) { + Project project = projectRepository.findByName(projectName) + .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, projectName)); + if (CollectionUtils.isEmpty(project.getUsers())) { + return Collections.emptyList(); + } + filter.withCondition( + new FilterCondition(Condition.EQUALS, false, String.valueOf(project.getId()), + CRITERIA_PROJECT_ID + )); + Page users = userRepository.findByFilterExcluding(filter, pageable, "email"); + return PagedResourcesAssembler.pageConverter(UserConverter.TO_RESOURCE).apply(users); + } + + @Override + public boolean exists(Long id) { + return projectRepository.existsById(id); + } + + @Override + public Project get(ReportPortalUser.ProjectDetails projectDetails) { + return projectRepository.findById(projectDetails.getProjectId()).orElseThrow( + () -> new ReportPortalException(PROJECT_NOT_FOUND, projectDetails.getProjectName())); + } + + @Override + public Project get(Long id) { + return projectRepository.findById(id) + .orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, id)); + } + + @Override + public Project get(String name) { + return projectRepository.findByName(name) + .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, name)); + } + + @Override + public Project getRaw(String name) { + return projectRepository.findRawByName(name) + .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, name)); + } + + @Override + public ProjectResource getResource(String projectName, ReportPortalUser user) { + + Project project = projectRepository.findByName(projectName) + .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, projectName)); + + return projectConverter.TO_PROJECT_RESOURCE.apply(project); + } + + @Override + public List getUserNames(ReportPortalUser.ProjectDetails projectDetails, String value) { + checkBusinessRuleLessThan1Symbol(value); + return userRepository.findNamesByProject(projectDetails.getProjectId(), value); + } + + private void checkBusinessRuleLessThan1Symbol(String value) { + BusinessRule.expect(value.length() >= 1, Predicates.equalTo(true)) + .verify(ErrorType.INCORRECT_FILTER_PARAMETERS, + Suppliers.formattedSupplier(LENGTH_LESS_THAN_1_SYMBOL_MSG, value) + ); + } + + @Override + public Iterable getUserNames(String value, + ReportPortalUser.ProjectDetails projectDetails, Pageable pageable) { + checkBusinessRuleLessThan1Symbol(value); + + final CompositeFilterCondition userCondition = getUserSearchCondition(value); + + final Filter filter = Filter.builder().withTarget(User.class).withCondition(userCondition) + .withCondition( + new FilterCondition(Operator.AND, Condition.ANY, true, projectDetails.getProjectName(), + CRITERIA_PROJECT + )).build(); + + return PagedResourcesAssembler.pageConverter(UserConverter.TO_SEARCH_RESOURCE) + .apply(userRepository.findByFilterExcludingProjects(filter, pageable)); + } + + private CompositeFilterCondition getUserSearchCondition(String value) { + return new CompositeFilterCondition( + List.of(new FilterCondition(Operator.OR, Condition.CONTAINS, false, value, CRITERIA_USER), + new FilterCondition(Operator.OR, Condition.CONTAINS, false, value, CRITERIA_FULL_NAME), + new FilterCondition(Operator.OR, Condition.CONTAINS, false, value, CRITERIA_EMAIL) + ), Operator.AND); + } + + @Override + public List getAllProjectNames() { + return projectRepository.findAllProjectNames(); + } + + @Override + public List getAllProjectNamesByTerm(String term) { + return projectRepository.findAllProjectNamesByTerm(term); + } + + @Override + public void exportProjects(ReportFormat reportFormat, Queryable filter, + OutputStream outputStream) { + + List projects = projectRepository.findProjectInfoByFilter(filter); + + List> data = + projects.stream().map(jasperReportHandler::convertParams).collect(Collectors.toList()); + + JRDataSource jrDataSource = new JRBeanCollectionDataSource(data); + + //don't provide any params to not overwrite params from the Jasper template + JasperPrint jasperPrint = jasperReportHandler.getJasperPrint(null, jrDataSource); + + jasperReportHandler.writeReport(reportFormat, outputStream, jasperPrint); + } + + @Override + public Map getAnalyzerIndexingStatus() { + return projectRepository.findAll().stream().collect( + Collectors.toMap(Project::getName, it -> getAnalyzerConfig(it).isIndexingRunning())); + } } diff --git a/src/main/java/com/epam/ta/reportportal/core/project/impl/GetProjectInfoHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/impl/GetProjectInfoHandlerImpl.java index 964109deb6..4f58e10dea 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/impl/GetProjectInfoHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/impl/GetProjectInfoHandlerImpl.java @@ -35,8 +35,8 @@ import static com.epam.ta.reportportal.entity.activity.ActivityAction.UPDATE_ITEM; import static com.epam.ta.reportportal.ws.converter.converters.ActivityConverter.TO_RESOURCE; import static com.epam.ta.reportportal.ws.converter.converters.ActivityConverter.TO_RESOURCE_WITH_USER; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; @@ -62,13 +62,13 @@ import com.epam.ta.reportportal.entity.project.email.ProjectInfoWidget; import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.project.LaunchesPerUser; +import com.epam.ta.reportportal.model.project.ProjectInfoResource; import com.epam.ta.reportportal.ws.converter.PagedResourcesAssembler; import com.epam.ta.reportportal.ws.converter.converters.LaunchConverter; import com.epam.ta.reportportal.ws.converter.converters.ProjectSettingsConverter; import com.epam.ta.reportportal.ws.model.ActivityResource; -import com.epam.ta.reportportal.ws.model.launch.Mode; -import com.epam.ta.reportportal.ws.model.project.LaunchesPerUser; -import com.epam.ta.reportportal.ws.model.project.ProjectInfoResource; +import com.epam.ta.reportportal.ws.reporting.Mode; import com.google.common.collect.Lists; import java.math.RoundingMode; import java.sql.Timestamp; @@ -96,201 +96,196 @@ @Service public class GetProjectInfoHandlerImpl implements GetProjectInfoHandler { - private static final Double WEEKS_IN_MONTH = 4.4; - private static final int LIMIT = 150; - private static final Predicate ACTIVITIES_PROJECT_FILTER = it -> it == UPDATE_DEFECT || it == DELETE_DEFECT - || it == LINK_ISSUE || it == LINK_ISSUE_AA || it == UNLINK_ISSUE || it == UPDATE_ITEM; - private final ProjectRepository projectRepository; - - private final LaunchRepository launchRepository; - - private final ActivityRepository activityRepository; - - private final ProjectInfoWidgetDataConverter dataConverter; - - private final LaunchConverter launchConverter; - - private final UserRepository userRepository; - - private final TicketRepository ticketRepository; - - private final DecimalFormat formatter = new DecimalFormat("###.##"); - - @Autowired - public GetProjectInfoHandlerImpl(ProjectRepository projectRepository, LaunchRepository launchRepository, - ActivityRepository activityRepository, ProjectInfoWidgetDataConverter dataConverter, LaunchConverter launchConverter, - UserRepository userRepository, TicketRepository ticketRepository) { - this.projectRepository = projectRepository; - this.launchRepository = launchRepository; - this.activityRepository = activityRepository; - this.dataConverter = dataConverter; - this.launchConverter = launchConverter; - this.userRepository = userRepository; - this.ticketRepository = ticketRepository; - } - - /** - * Utility method for calculation of start interval date - * - * @param interval Back interval - * @return Now minus interval - */ - private static LocalDateTime getStartIntervalDate(InfoInterval interval) { - return LocalDateTime.now(Clock.systemUTC()).minusMonths(interval.getCount()); - } - - /** - * Filter that gets project info from selected date. - * - * @param project Project - * @param infoInterval Date interval - * @return {@link Filter} - */ - private static Filter projectInfoFilter(Project project, InfoInterval infoInterval) { - return Filter.builder() - .withTarget(ProjectInfo.class) - .withCondition(new FilterCondition(EQUALS, false, project.getName(), CRITERIA_PROJECT_NAME)) - .withCondition(new FilterCondition(GREATER_THAN_OR_EQUALS, - false, - String.valueOf(getStartIntervalDate(infoInterval).toInstant(ZoneOffset.UTC).toEpochMilli()), - CRITERIA_PROJECT_CREATION_DATE - )) - .build(); - } - - @Override - public Iterable getAllProjectsInfo(Queryable filter, Pageable pageable) { - return PagedResourcesAssembler.pageConverter(ProjectSettingsConverter.TO_PROJECT_INFO_RESOURCE) - .apply(projectRepository.findProjectInfoByFilter(filter, pageable)); - } - - @Override - public ProjectInfoResource getProjectInfo(String projectName, String interval) { - - Project project = projectRepository.findByName(normalizeId(projectName)) - .orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, projectName)); - - InfoInterval infoInterval = InfoInterval.findByInterval(interval) - .orElseThrow(() -> new ReportPortalException(BAD_REQUEST_ERROR, interval)); - - Filter filter = Filter.builder() - .withTarget(ProjectInfo.class) - .withCondition(FilterCondition.builder().eq(CRITERIA_PROJECT_NAME, project.getName()).build()) - .build(); - - Page result = projectRepository.findProjectInfoByFilter(filter, Pageable.unpaged()); - ProjectInfoResource projectInfoResource = ProjectSettingsConverter.TO_PROJECT_INFO_RESOURCE.apply(result.get() - .findFirst() - .orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, projectName))); - - LocalDateTime startIntervalDate = getStartIntervalDate(infoInterval); - - Map countPerUser = launchRepository.countLaunchesGroupedByOwner(project.getId(), - LaunchModeEnum.DEFAULT.toString(), - startIntervalDate - ); - - projectInfoResource.setUniqueTickets(ticketRepository.findUniqueCountByProjectBefore(project.getId(), startIntervalDate)); - - projectInfoResource.setLaunchesPerUser(countPerUser.entrySet() - .stream() - .map(e -> new LaunchesPerUser(e.getKey(), e.getValue())) - .collect(Collectors.toList())); - - if (projectInfoResource.getLaunchesQuantity() != 0) { - formatter.setRoundingMode(RoundingMode.HALF_UP); - double value = projectInfoResource.getLaunchesQuantity() / (infoInterval.getCount() * WEEKS_IN_MONTH); - projectInfoResource.setLaunchesPerWeek(formatter.format(value)); - } else { - projectInfoResource.setLaunchesPerWeek(formatter.format(0)); - } - return projectInfoResource; - } - - @Override - public Map getProjectInfoWidgetContent(String projectName, String interval, String widgetCode) { - Project project = projectRepository.findByName(projectName) - .orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, projectName)); - - InfoInterval infoInterval = InfoInterval.findByInterval(interval) - .orElseThrow(() -> new ReportPortalException(BAD_REQUEST_ERROR, interval)); - - ProjectInfoWidget widgetType = ProjectInfoWidget.findByCode(widgetCode) - .orElseThrow(() -> new ReportPortalException(BAD_REQUEST_ERROR, widgetCode)); - - List launches = launchRepository.findByProjectIdAndStartTimeGreaterThanAndMode(project.getId(), - getStartIntervalDate(infoInterval), - LaunchModeEnum.DEFAULT - ); - - Map result; - - switch (widgetType) { - case INVESTIGATED: - result = dataConverter.getInvestigatedProjectInfo(launches, infoInterval); - break; - case CASES_STATISTIC: - result = dataConverter.getTestCasesStatisticsProjectInfo(launches); - break; - case LAUNCHES_QUANTITY: - result = dataConverter.getLaunchesQuantity(launches, infoInterval); - break; - case ISSUES_CHART: - result = dataConverter.getLaunchesIssues(launches, infoInterval); - break; - case ACTIVITIES: - result = getActivities(project, infoInterval); - break; - case LAST_LAUNCH: - result = getLastLaunchStatistics(project.getId()); - break; - default: - // empty result - result = Collections.emptyMap(); - } - - return result; - } - - private Map getLastLaunchStatistics(Long projectId) { - Optional launchOptional = launchRepository.findLastRun(projectId, Mode.DEFAULT.name()); - return launchOptional.isPresent() ? - Collections.singletonMap(RESULT, launchConverter.TO_RESOURCE.apply(launchOptional.get())) : - Collections.emptyMap(); - } - - private Map> getActivities(Project project, - InfoInterval infoInterval) { - String value = Arrays.stream(ActivityAction.values()) - .filter(not(ACTIVITIES_PROJECT_FILTER)) - .map(ActivityAction::getValue) - .collect(joining(",")); - Filter filter = new Filter(Activity.class, - Lists.newArrayList(new FilterCondition(IN, false, value, CRITERIA_EVENT_NAME), - new FilterCondition(EQUALS, false, String.valueOf(project.getId()), - CRITERIA_PROJECT_ID), - new FilterCondition(GREATER_THAN_OR_EQUALS, - false, - String.valueOf(Timestamp.valueOf(getStartIntervalDate(infoInterval)).getTime()), - CRITERIA_CREATED_AT - ) - )); - List activities = activityRepository.findByFilter(filter, - PageRequest.of(0, LIMIT, Sort.by(Sort.Direction.DESC, CRITERIA_CREATED_AT)) - ).getContent(); - - Map userIdLoginMapping = userRepository.findAllById(activities.stream() - .filter(a -> a.getSubjectId() != null && a.getSubjectType() == EventSubject.USER) - .map(Activity::getSubjectId) - .collect(Collectors.toSet())).stream().collect(toMap(User::getId, User::getLogin)); - - return Collections.singletonMap(RESULT, - activities.stream() - .map(a -> ofNullable(a.getSubjectId()).map( - userId -> TO_RESOURCE_WITH_USER.apply(a, userIdLoginMapping.get(userId))) - .orElseGet(() -> TO_RESOURCE.apply(a))) - .peek(resource -> resource.setProjectName(project.getName())) - .collect(toList()) - ); - } + private static final Double WEEKS_IN_MONTH = 4.4; + private static final int LIMIT = 150; + private static final Predicate ACTIVITIES_PROJECT_FILTER = + it -> it == UPDATE_DEFECT || it == DELETE_DEFECT || it == LINK_ISSUE || it == LINK_ISSUE_AA + || it == UNLINK_ISSUE || it == UPDATE_ITEM; + private final ProjectRepository projectRepository; + + private final LaunchRepository launchRepository; + + private final ActivityRepository activityRepository; + + private final ProjectInfoWidgetDataConverter dataConverter; + + private final LaunchConverter launchConverter; + + private final UserRepository userRepository; + + private final TicketRepository ticketRepository; + + private final DecimalFormat formatter = new DecimalFormat("###.##"); + + @Autowired + public GetProjectInfoHandlerImpl(ProjectRepository projectRepository, + LaunchRepository launchRepository, ActivityRepository activityRepository, + ProjectInfoWidgetDataConverter dataConverter, LaunchConverter launchConverter, + UserRepository userRepository, TicketRepository ticketRepository) { + this.projectRepository = projectRepository; + this.launchRepository = launchRepository; + this.activityRepository = activityRepository; + this.dataConverter = dataConverter; + this.launchConverter = launchConverter; + this.userRepository = userRepository; + this.ticketRepository = ticketRepository; + } + + /** + * Utility method for calculation of start interval date + * + * @param interval Back interval + * @return Now minus interval + */ + private static LocalDateTime getStartIntervalDate(InfoInterval interval) { + return LocalDateTime.now(Clock.systemUTC()).minusMonths(interval.getCount()); + } + + /** + * Filter that gets project info from selected date. + * + * @param project Project + * @param infoInterval Date interval + * @return {@link Filter} + */ + private static Filter projectInfoFilter(Project project, InfoInterval infoInterval) { + return Filter.builder().withTarget(ProjectInfo.class) + .withCondition(new FilterCondition(EQUALS, false, project.getName(), CRITERIA_PROJECT_NAME)) + .withCondition(new FilterCondition(GREATER_THAN_OR_EQUALS, false, String.valueOf( + getStartIntervalDate(infoInterval).toInstant(ZoneOffset.UTC).toEpochMilli()), + CRITERIA_PROJECT_CREATION_DATE + )).build(); + } + + @Override + public Iterable getAllProjectsInfo(Queryable filter, Pageable pageable) { + return PagedResourcesAssembler.pageConverter(ProjectSettingsConverter.TO_PROJECT_INFO_RESOURCE) + .apply(projectRepository.findProjectInfoByFilter(filter, pageable)); + } + + @Override + public ProjectInfoResource getProjectInfo(String projectName, String interval) { + + Project project = projectRepository.findByName(normalizeId(projectName)) + .orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, projectName)); + + InfoInterval infoInterval = InfoInterval.findByInterval(interval) + .orElseThrow(() -> new ReportPortalException(BAD_REQUEST_ERROR, interval)); + + Filter filter = Filter.builder().withTarget(ProjectInfo.class).withCondition( + FilterCondition.builder().eq(CRITERIA_PROJECT_NAME, project.getName()).build()).build(); + + Page result = + projectRepository.findProjectInfoByFilter(filter, Pageable.unpaged()); + ProjectInfoResource projectInfoResource = + ProjectSettingsConverter.TO_PROJECT_INFO_RESOURCE.apply(result.get().findFirst() + .orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, projectName))); + + LocalDateTime startIntervalDate = getStartIntervalDate(infoInterval); + + Map countPerUser = + launchRepository.countLaunchesGroupedByOwner(project.getId(), + LaunchModeEnum.DEFAULT.toString(), startIntervalDate + ); + + projectInfoResource.setUniqueTickets( + ticketRepository.findUniqueCountByProjectBefore(project.getId(), startIntervalDate)); + + projectInfoResource.setLaunchesPerUser( + countPerUser.entrySet().stream().map(e -> new LaunchesPerUser(e.getKey(), e.getValue())) + .collect(Collectors.toList())); + + if (projectInfoResource.getLaunchesQuantity() != 0) { + formatter.setRoundingMode(RoundingMode.HALF_UP); + double value = + projectInfoResource.getLaunchesQuantity() / (infoInterval.getCount() * WEEKS_IN_MONTH); + projectInfoResource.setLaunchesPerWeek(formatter.format(value)); + } else { + projectInfoResource.setLaunchesPerWeek(formatter.format(0)); + } + return projectInfoResource; + } + + @Override + public Map getProjectInfoWidgetContent(String projectName, String interval, + String widgetCode) { + Project project = projectRepository.findByName(projectName) + .orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, projectName)); + + InfoInterval infoInterval = InfoInterval.findByInterval(interval) + .orElseThrow(() -> new ReportPortalException(BAD_REQUEST_ERROR, interval)); + + ProjectInfoWidget widgetType = ProjectInfoWidget.findByCode(widgetCode) + .orElseThrow(() -> new ReportPortalException(BAD_REQUEST_ERROR, widgetCode)); + + List launches = + launchRepository.findByProjectIdAndStartTimeGreaterThanAndMode(project.getId(), + getStartIntervalDate(infoInterval), LaunchModeEnum.DEFAULT + ); + + Map result; + + switch (widgetType) { + case INVESTIGATED: + result = dataConverter.getInvestigatedProjectInfo(launches, infoInterval); + break; + case CASES_STATISTIC: + result = dataConverter.getTestCasesStatisticsProjectInfo(launches); + break; + case LAUNCHES_QUANTITY: + result = dataConverter.getLaunchesQuantity(launches, infoInterval); + break; + case ISSUES_CHART: + result = dataConverter.getLaunchesIssues(launches, infoInterval); + break; + case ACTIVITIES: + result = getActivities(project, infoInterval); + break; + case LAST_LAUNCH: + result = getLastLaunchStatistics(project.getId()); + break; + default: + // empty result + result = Collections.emptyMap(); + } + + return result; + } + + private Map getLastLaunchStatistics(Long projectId) { + Optional launchOptional = launchRepository.findLastRun(projectId, Mode.DEFAULT.name()); + return launchOptional.isPresent() ? + Collections.singletonMap(RESULT, launchConverter.TO_RESOURCE.apply(launchOptional.get())) : + Collections.emptyMap(); + } + + private Map> getActivities(Project project, + InfoInterval infoInterval) { + String value = Arrays.stream(ActivityAction.values()).filter(not(ACTIVITIES_PROJECT_FILTER)) + .map(ActivityAction::getValue).collect(joining(",")); + Filter filter = new Filter(Activity.class, + Lists.newArrayList(new FilterCondition(IN, false, value, CRITERIA_EVENT_NAME), + new FilterCondition(EQUALS, false, String.valueOf(project.getId()), + CRITERIA_PROJECT_ID + ), new FilterCondition(GREATER_THAN_OR_EQUALS, false, + String.valueOf(Timestamp.valueOf(getStartIntervalDate(infoInterval)).getTime()), + CRITERIA_CREATED_AT + ) + ) + ); + List activities = activityRepository.findByFilter(filter, + PageRequest.of(0, LIMIT, Sort.by(Sort.Direction.DESC, CRITERIA_CREATED_AT)) + ).getContent(); + + Map userIdLoginMapping = userRepository.findAllById(activities.stream() + .filter(a -> a.getSubjectId() != null && a.getSubjectType() == EventSubject.USER) + .map(Activity::getSubjectId).collect(Collectors.toSet())).stream() + .collect(toMap(User::getId, User::getLogin)); + + return Collections.singletonMap(RESULT, activities.stream().map( + a -> ofNullable(a.getSubjectId()).map( + userId -> TO_RESOURCE_WITH_USER.apply(a, userIdLoginMapping.get(userId))) + .orElseGet(() -> TO_RESOURCE.apply(a))) + .peek(resource -> resource.setProjectName(project.getName())).collect(toList())); + } } diff --git a/src/main/java/com/epam/ta/reportportal/core/project/impl/ProjectInfoWidgetDataConverter.java b/src/main/java/com/epam/ta/reportportal/core/project/impl/ProjectInfoWidgetDataConverter.java index fd5ca58e5f..3d35fb1f42 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/impl/ProjectInfoWidgetDataConverter.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/impl/ProjectInfoWidgetDataConverter.java @@ -30,7 +30,7 @@ import com.epam.ta.reportportal.entity.enums.InfoInterval; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.entity.statistics.Statistics; -import com.epam.ta.reportportal.ws.model.widget.ChartObject; +import com.epam.ta.reportportal.model.widget.ChartObject; import com.google.common.collect.Lists; import java.text.DecimalFormat; import java.time.LocalDate; @@ -70,24 +70,20 @@ public ProjectInfoWidgetDataConverter( } public enum ProjectInfoGroup { - BY_DAY, - BY_WEEK, - BY_NAME + BY_DAY, BY_WEEK, BY_NAME } - private static DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendValue( - IsoFields.WEEK_BASED_YEAR, 4) - .appendLiteral("-W") - .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2) - .toFormatter(); + private static DateTimeFormatter formatter = + new DateTimeFormatterBuilder().appendValue(IsoFields.WEEK_BASED_YEAR, 4).appendLiteral("-W") + .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2).toFormatter(); /** * Percentage Of Investigation project info widget content * - * @param initial A list of {@link Launch} objects to calculate investigation percentages - * @param interval An {@link InfoInterval} representing the grouping interval (e.g., daily, weekly) + * @param initial A list of {@link Launch} objects to calculate investigation percentages + * @param interval An {@link InfoInterval} representing the grouping interval (e.g., daily, weekly) * @return A {@link Map} with keys representing interval group names and values containing - * {@link List} of {@link ChartObject} instances with investigated and to-investigate percentage information + * {@link List} of {@link ChartObject} instances with investigated and to-investigate percentage information */ public Map> getInvestigatedProjectInfo(List initial, InfoInterval interval) { @@ -111,12 +107,11 @@ public Map> getInvestigatedProjectInfo(List in for (Launch one : group) { investigated = investigated + extractStatisticsCount(DEFECTS_PRODUCT_BUG_TOTAL, one.getStatistics()) - + extractStatisticsCount( - DEFECTS_SYSTEM_ISSUE_TOTAL, - one.getStatistics() - ) + extractStatisticsCount(DEFECTS_AUTOMATION_BUG_TOTAL, one.getStatistics()); + + extractStatisticsCount(DEFECTS_SYSTEM_ISSUE_TOTAL, one.getStatistics()) + + extractStatisticsCount(DEFECTS_AUTOMATION_BUG_TOTAL, one.getStatistics()); toInvestigate = toInvestigate + extractStatisticsCount(DEFECTS_TO_INVESTIGATE_TOTAL, - one.getStatistics()); + one.getStatistics() + ); } if ((investigated + toInvestigate) > 0) { double investigatedPercent = (investigated / (investigated + toInvestigate)) * 100; @@ -140,7 +135,7 @@ public Map> getInvestigatedProjectInfo(List in * * @param initial A list of {@link Launch} objects to calculate test-case statistics * @return A {@link Map} with keys representing launch names and values containing - * {@link List} of {@link ChartObject} instances with min, max, and average statistics + * {@link List} of {@link ChartObject} instances with min, max, and average statistics */ public Map> getTestCasesStatisticsProjectInfo(List initial) { DecimalFormat formatter = new DecimalFormat("#####.##"); @@ -161,14 +156,10 @@ public Map> getTestCasesStatisticsProjectInfo(List values = new HashMap<>(); List group = pair.getValue(); - DoubleSummaryStatistics statistics = group.stream() - .mapToDouble(launch -> launch.getStatistics() - .stream() + DoubleSummaryStatistics statistics = group.stream().mapToDouble( + launch -> launch.getStatistics().stream() .filter(it -> it.getStatisticsField().getName().equalsIgnoreCase(EXECUTIONS_TOTAL)) - .findFirst() - .orElse(new Statistics()) - .getCounter()) - .summaryStatistics(); + .findFirst().orElse(new Statistics()).getCounter()).summaryStatistics(); values.put(MIN, String.valueOf(statistics.getMin())); values.put(MAX, String.valueOf(statistics.getMax())); @@ -189,10 +180,10 @@ public Map> getTestCasesStatisticsProjectInfo(ListQuantity of Launches project info widget content * - * @param initial A list of {@link Launch} objects to calculate the quantity of launches + * @param initial A list of {@link Launch} objects to calculate the quantity of launches * @param interval An {@link InfoInterval} representing the grouping interval (e.g., daily, weekly) * @return A {@link Map} with keys representing interval group names and values containing - * {@link List} of {@link ChartObject} instances with launch quantity information + * {@link List} of {@link ChartObject} instances with launch quantity information */ public Map> getLaunchesQuantity(List initial, InfoInterval interval) { @@ -217,7 +208,8 @@ public Map> getLaunchesQuantity(List initial, DateTime parse = DateTime.parse(entry.getKey()); // TODO remove Yoda time. replace with JDK8 values.put(START_PERIOD, - parse.withDayOfWeek(DateTimeConstants.MONDAY).toString("yyy-MM-dd")); + parse.withDayOfWeek(DateTimeConstants.MONDAY).toString("yyy-MM-dd") + ); values.put(END_PERIOD, parse.withDayOfWeek(DateTimeConstants.SUNDAY).toString("yyy-MM-dd")); } else { values.put(START_PERIOD, entry.getKey()); @@ -232,10 +224,10 @@ public Map> getLaunchesQuantity(List initial, /** * Launch statistics line chart project info widget content * - * @param initial A list of {@link Launch} objects to calculate the issues + * @param initial A list of {@link Launch} objects to calculate the issues * @param interval An {@link InfoInterval} representing the grouping interval (e.g., daily, weekly) * @return A {@link Map} with keys representing interval group names and values containing - * {@link List} of {@link ChartObject} instances with issue count information + * {@link List} of {@link ChartObject} instances with issue count information */ public Map> getLaunchesIssues(List initial, InfoInterval interval) { @@ -280,7 +272,7 @@ public Map> getLaunchesIssues(List initial, * @param initial A list of {@link Launch} objects to be grouped * @param criteria The {@link ProjectInfoGroup} criteria that determines the grouping key * @return A map where the keys represent the grouping parameters (e.g., launch names or formatted dates) - * and the values are lists of {@link Launch} objects grouped under that key + * and the values are lists of {@link Launch} objects grouped under that key */ private static Map> groupBy(List initial, ProjectInfoGroup criteria) { diff --git a/src/main/java/com/epam/ta/reportportal/core/project/impl/ProjectUserHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/impl/ProjectUserHandlerImpl.java index 671868258d..31b8c3bba7 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/impl/ProjectUserHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/impl/ProjectUserHandlerImpl.java @@ -7,7 +7,7 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.ProjectUser; import com.epam.ta.reportportal.entity.user.User; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; +import com.epam.ta.reportportal.model.activity.UserActivityResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Service; @@ -28,13 +28,14 @@ public ProjectUserHandlerImpl(ApplicationEventPublisher eventPublisher, @Override public ProjectUser assign(User user, Project project, ProjectRole projectRole, User creator, boolean isSystemEvent) { - final ProjectUser projectUser = new ProjectUser().withProjectRole(projectRole) - .withUser(user) - .withProject(project); + final ProjectUser projectUser = + new ProjectUser().withProjectRole(projectRole).withUser(user).withProject(project); projectUserRepository.save(projectUser); - AssignUserEvent assignUserEvent = new AssignUserEvent(getUserActivityResource(user, project), - creator.getId(), creator.getLogin(), isSystemEvent); + AssignUserEvent assignUserEvent = + new AssignUserEvent(getUserActivityResource(user, project), creator.getId(), + creator.getLogin(), isSystemEvent + ); eventPublisher.publishEvent(assignUserEvent); return projectUser; diff --git a/src/main/java/com/epam/ta/reportportal/core/project/impl/UpdateProjectHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/impl/UpdateProjectHandlerImpl.java index 685702ac58..14c5e5b498 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/impl/UpdateProjectHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/impl/UpdateProjectHandlerImpl.java @@ -31,12 +31,12 @@ import static com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum.AUTO_PATTERN_ANALYZER_ENABLED; import static com.epam.ta.reportportal.entity.enums.SendCase.findByName; import static com.epam.ta.reportportal.ws.converter.converters.ProjectActivityConverter.TO_ACTIVITY_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.ROLE_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.UNABLE_ASSIGN_UNASSIGN_USER_TO_PROJECT; -import static com.epam.ta.reportportal.ws.model.ErrorType.USER_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ROLE_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.UNABLE_ASSIGN_UNASSIGN_USER_TO_PROJECT; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.USER_NOT_FOUND; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; @@ -77,25 +77,25 @@ import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.entity.user.UserType; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.activity.ProjectAttributesActivityResource; +import com.epam.ta.reportportal.model.activity.UserActivityResource; +import com.epam.ta.reportportal.model.project.AssignUsersRQ; +import com.epam.ta.reportportal.model.project.ProjectResource; +import com.epam.ta.reportportal.model.project.UnassignUsersRQ; +import com.epam.ta.reportportal.model.project.UpdateProjectRQ; +import com.epam.ta.reportportal.model.project.config.ProjectConfigurationUpdate; +import com.epam.ta.reportportal.model.project.email.ProjectNotificationConfigDTO; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; import com.epam.ta.reportportal.util.ProjectExtractor; import com.epam.ta.reportportal.util.email.EmailRulesValidator; import com.epam.ta.reportportal.util.email.MailServiceFactory; import com.epam.ta.reportportal.ws.converter.converters.NotificationConfigConverter; import com.epam.ta.reportportal.ws.converter.converters.ProjectConverter; import com.epam.ta.reportportal.ws.converter.converters.UserConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.epam.ta.reportportal.ws.model.ValidationConstraints; -import com.epam.ta.reportportal.ws.model.activity.ProjectAttributesActivityResource; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.project.AssignUsersRQ; -import com.epam.ta.reportportal.ws.model.project.ProjectResource; -import com.epam.ta.reportportal.ws.model.project.UnassignUsersRQ; -import com.epam.ta.reportportal.ws.model.project.UpdateProjectRQ; -import com.epam.ta.reportportal.ws.model.project.config.ProjectConfigurationUpdate; -import com.epam.ta.reportportal.ws.model.project.email.ProjectNotificationConfigDTO; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; import com.google.common.cache.Cache; import com.google.common.collect.Lists; import java.util.List; @@ -150,13 +150,11 @@ public class UpdateProjectHandlerImpl implements UpdateProjectHandler { @Autowired public UpdateProjectHandlerImpl(ProjectExtractor projectExtractor, - ProjectAttributeValidator projectAttributeValidator, - ProjectRepository projectRepository, UserRepository userRepository, - UserPreferenceRepository preferenceRepository, + ProjectAttributeValidator projectAttributeValidator, ProjectRepository projectRepository, + UserRepository userRepository, UserPreferenceRepository preferenceRepository, MessageBus messageBus, ProjectUserRepository projectUserRepository, - ApplicationEventPublisher applicationEventPublisher, - MailServiceFactory mailServiceFactory, AnalyzerStatusCache analyzerStatusCache, - IndexerStatusCache indexerStatusCache, + ApplicationEventPublisher applicationEventPublisher, MailServiceFactory mailServiceFactory, + AnalyzerStatusCache analyzerStatusCache, IndexerStatusCache indexerStatusCache, AnalyzerServiceClient analyzerServiceClient, LogIndexer logIndexer, ProjectConverter projectConverter) { this.projectExtractor = projectExtractor; @@ -196,27 +194,22 @@ public OperationCompletionRS updateProject(String projectName, UpdateProjectRQ u @Override public OperationCompletionRS updateProjectNotificationConfig(String projectName, - ReportPortalUser user, - ProjectNotificationConfigDTO updateProjectNotificationConfigRQ) { + ReportPortalUser user, ProjectNotificationConfigDTO updateProjectNotificationConfigRQ) { Project project = projectRepository.findByName(projectName) .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, projectName)); ProjectResource before = projectConverter.TO_PROJECT_RESOURCE.apply(project); updateSenderCases(project, updateProjectNotificationConfigRQ.getSenderCases()); - project.getProjectAttributes() - .stream() - .filter(it -> it.getAttribute().getName() - .equalsIgnoreCase(ProjectAttributeEnum.NOTIFICATIONS_ENABLED.getAttribute())) - .findAny() + project.getProjectAttributes().stream().filter(it -> it.getAttribute().getName() + .equalsIgnoreCase(ProjectAttributeEnum.NOTIFICATIONS_ENABLED.getAttribute())).findAny() .ifPresent( pa -> pa.setValue(String.valueOf(updateProjectNotificationConfigRQ.isEnabled()))); - messageBus.publishActivity(new NotificationsConfigUpdatedEvent(before, - updateProjectNotificationConfigRQ, - user.getUserId(), - user.getUsername() - )); + messageBus.publishActivity( + new NotificationsConfigUpdatedEvent(before, updateProjectNotificationConfigRQ, + user.getUserId(), user.getUsername() + )); return new OperationCompletionRS( "Notification configuration of project - '" + projectName + "' is successfully updated."); } @@ -233,9 +226,7 @@ public OperationCompletionRS unassignUsers(String projectName, UnassignUsersRQ u .orElseThrow(() -> new ReportPortalException(USER_NOT_FOUND, user.getUsername())); if (!UserRole.ADMINISTRATOR.equals(modifier.getRole())) { expect(unassignUsersRQ.getUsernames(), not(contains(equalTo(modifier.getLogin())))).verify( - UNABLE_ASSIGN_UNASSIGN_USER_TO_PROJECT, - "User should not unassign himself from project." - ); + UNABLE_ASSIGN_UNASSIGN_USER_TO_PROJECT, "User should not unassign himself from project."); } List unassignedUsers = @@ -244,21 +235,19 @@ public OperationCompletionRS unassignUsers(String projectName, UnassignUsersRQ u ProjectUtils.excludeProjectRecipients( unassignedUsers.stream().map(ProjectUser::getUser).collect(Collectors.toSet()), project); unassignedUsers.forEach(it -> preferenceRepository.removeByProjectIdAndUserId(project.getId(), - it.getUser().getId())); + it.getUser().getId() + )); - return new OperationCompletionRS( - "User(s) with username(s)='" + unassignUsersRQ.getUsernames() - + "' was successfully un-assigned from project='" - + project.getName() + "'"); + return new OperationCompletionRS("User(s) with username(s)='" + unassignUsersRQ.getUsernames() + + "' was successfully un-assigned from project='" + project.getName() + "'"); } @Override public OperationCompletionRS assignUsers(String projectName, AssignUsersRQ assignUsersRQ, ReportPortalUser user) { if (UserRole.ADMINISTRATOR.equals(user.getUserRole())) { - Project project = projectRepository.findByName(normalizeId(projectName)) - .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, - normalizeId(projectName))); + Project project = projectRepository.findByName(normalizeId(projectName)).orElseThrow( + () -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, normalizeId(projectName))); List assignedUsernames = project.getUsers().stream().map(u -> u.getUser().getLogin()).collect(toList()); @@ -269,16 +258,15 @@ public OperationCompletionRS assignUsers(String projectName, AssignUsersRQ assig }); } else { expect(assignUsersRQ.getUserNames().keySet(), - not(Preconditions.contains(equalTo(user.getUsername())))).verify( - UNABLE_ASSIGN_UNASSIGN_USER_TO_PROJECT, + not(Preconditions.contains(equalTo(user.getUsername()))) + ).verify(UNABLE_ASSIGN_UNASSIGN_USER_TO_PROJECT, "User should not assign himself to project." ); ReportPortalUser.ProjectDetails projectDetails = projectExtractor.extractProjectDetails(user, projectName); - Project project = projectRepository.findById(projectDetails.getProjectId()) - .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, - normalizeId(projectName))); + Project project = projectRepository.findById(projectDetails.getProjectId()).orElseThrow( + () -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, normalizeId(projectName))); List assignedUsernames = project.getUsers().stream().map(u -> u.getUser().getLogin()).collect(toList()); @@ -295,16 +283,13 @@ public OperationCompletionRS assignUsers(String projectName, AssignUsersRQ assig return new OperationCompletionRS( "User(s) with username='" + assignUsersRQ.getUserNames().keySet() - + "' was successfully assigned to project='" - + normalizeId(projectName) + "'"); + + "' was successfully assigned to project='" + normalizeId(projectName) + "'"); } @Override public OperationCompletionRS indexProjectData(String projectName, ReportPortalUser user) { expect(analyzerServiceClient.hasClients(), Predicate.isEqual(true)).verify( - ErrorType.UNABLE_INTERACT_WITH_INTEGRATION, - "There are no analyzer deployed." - ); + ErrorType.UNABLE_INTERACT_WITH_INTEGRATION, "There are no analyzer deployed."); Project project = projectRepository.findByName(projectName) .orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, projectName)); @@ -318,20 +303,20 @@ public OperationCompletionRS indexProjectData(String projectName, ReportPortalUs .orElseThrow( () -> new ReportPortalException(ErrorType.ANALYZER_NOT_FOUND, AUTO_ANALYZER_KEY)); expect(analyzeStatus.asMap().containsValue(project.getId()), equalTo(false)).verify( - ErrorType.FORBIDDEN_OPERATION, - "Index can not be removed until auto-analysis proceeds." - ); + ErrorType.FORBIDDEN_OPERATION, "Index can not be removed until auto-analysis proceeds."); logIndexer.deleteIndex(project.getId()); - logIndexer.index(project.getId(), AnalyzerUtils.getAnalyzerConfig(project)) - .thenAcceptAsync(indexedCount -> mailServiceFactory.getDefaultEmailService(true) + logIndexer.index(project.getId(), AnalyzerUtils.getAnalyzerConfig(project)).thenAcceptAsync( + indexedCount -> mailServiceFactory.getDefaultEmailService(true) .sendIndexFinishedEmail("Index generation has been finished", user.getEmail(), - indexedCount)); + indexedCount + )); messageBus.publishActivity( new ProjectIndexEvent(user.getUserId(), user.getUsername(), project.getId(), - project.getName(), true)); + project.getName(), true + )); return new OperationCompletionRS("Log indexing has been started"); } @@ -354,18 +339,16 @@ private List unassignUsers(List usernames, User modifier, P usernames.forEach(username -> { User userForUnassign = userRepository.findByLogin(username) .orElseThrow(() -> new ReportPortalException(USER_NOT_FOUND, username)); - ProjectUser projectUser = userForUnassign.getProjects() - .stream() - .filter(it -> Objects.equals(it.getProject().getId(), project.getId())) - .findFirst() - .orElseThrow(() -> new ReportPortalException(USER_NOT_FOUND, - userForUnassign.getLogin(), + ProjectUser projectUser = userForUnassign.getProjects().stream() + .filter(it -> Objects.equals(it.getProject().getId(), project.getId())).findFirst() + .orElseThrow(() -> new ReportPortalException(USER_NOT_FOUND, userForUnassign.getLogin(), String.format("User not found in project %s", project.getName()) )); - expect(projectDetails.getProjectRole().sameOrHigherThan(projectUser.getProjectRole()), - BooleanUtils::isTrue).verify( - ACCESS_DENIED); + expect( + projectDetails.getProjectRole().sameOrHigherThan(projectUser.getProjectRole()), + BooleanUtils::isTrue + ).verify(ACCESS_DENIED); validateUnassigningUser(modifier, userForUnassign, project.getId(), project); unassignedUsers.add(unassignUser(project, username, userForUnassign, user)); @@ -378,18 +361,16 @@ private List unassignUsers(List usernames, User modifier, P private ProjectUser unassignUser(Project project, String username, User userForUnassign, ReportPortalUser authorizedUser) { - ProjectUser projectUser = project.getUsers() - .stream() - .filter(it -> it.getUser().getLogin().equalsIgnoreCase(username)) - .findFirst() - .orElseThrow(() -> new ReportPortalException(USER_NOT_FOUND, username)); + ProjectUser projectUser = + project.getUsers().stream().filter(it -> it.getUser().getLogin().equalsIgnoreCase(username)) + .findFirst().orElseThrow(() -> new ReportPortalException(USER_NOT_FOUND, username)); project.getUsers().remove(projectUser); userForUnassign.getProjects().remove(projectUser); - UnassignUserEvent unassignUserEvent = new UnassignUserEvent( - convertUserToResource(userForUnassign, projectUser), - authorizedUser.getUserId(), - authorizedUser.getUsername()); + UnassignUserEvent unassignUserEvent = + new UnassignUserEvent(convertUserToResource(userForUnassign, projectUser), + authorizedUser.getUserId(), authorizedUser.getUsername() + ); applicationEventPublisher.publishEvent(unassignUserEvent); return projectUser; @@ -418,20 +399,22 @@ private void assignUser(String name, ProjectRole projectRole, List assig projectUser.setProject(project); project.getUsers().add(projectUser); - AssignUserEvent assignUserEvent = new AssignUserEvent( - convertUserToResource(modifyingUser, projectUser), - authorizedUser.getUserId(), - authorizedUser.getUsername(), - false); + AssignUserEvent assignUserEvent = + new AssignUserEvent(convertUserToResource(modifyingUser, projectUser), + authorizedUser.getUserId(), authorizedUser.getUsername(), false + ); applicationEventPublisher.publishEvent(assignUserEvent); } private void validateUnassigningUser(User modifier, User userForUnassign, Long projectId, Project project) { if (ProjectUtils.isPersonalForUser(project.getProjectType(), project.getName(), - userForUnassign.getLogin())) { - fail().withError(UNABLE_ASSIGN_UNASSIGN_USER_TO_PROJECT, - "Unable to unassign user from his personal project"); + userForUnassign.getLogin() + )) { + fail().withError( + UNABLE_ASSIGN_UNASSIGN_USER_TO_PROJECT, + "Unable to unassign user from his personal project" + ); } if (ProjectType.UPSA.equals(project.getProjectType()) && UserType.UPSA.equals( userForUnassign.getUserType())) { @@ -439,7 +422,8 @@ private void validateUnassigningUser(User modifier, User userForUnassign, Long p } if (!ProjectUtils.doesHaveUser(project, userForUnassign.getLogin())) { fail().withError(USER_NOT_FOUND, userForUnassign.getLogin(), - String.format("User not found in project %s", project.getName())); + String.format("User not found in project %s", project.getName()) + ); } } @@ -464,10 +448,9 @@ private void updateProjectUserRoles(Map userRoles, Project proje if (UserRole.ADMINISTRATOR != user.getUserRole()) { ProjectRole principalRole = projectExtractor.extractProjectDetails(user, project.getName()).getProjectRole(); - ProjectRole updatingUserRole = ofNullable(ProjectUtils.findUserConfigByLogin(project, - key - )).orElseThrow(() -> new ReportPortalException(ErrorType.USER_NOT_FOUND, key)) - .getProjectRole(); + ProjectRole updatingUserRole = + ofNullable(ProjectUtils.findUserConfigByLogin(project, key)).orElseThrow( + () -> new ReportPortalException(ErrorType.USER_NOT_FOUND, key)).getProjectRole(); /* * Validate principal role level is high enough */ @@ -490,17 +473,20 @@ private void updateProjectUserRoles(Map userRoles, Project proje private void publishChangeRoleEvent(ReportPortalUser loggedUser, ProjectUser updatingProjectUser, String oldRole) { String newRole = updatingProjectUser.getProjectRole().getRoleName(); - ChangeRoleEvent changeRoleEvent = getChangeRoleEvent(updatingProjectUser.getUser(), - updatingProjectUser.getProject().getId(), loggedUser, oldRole, newRole); + ChangeRoleEvent changeRoleEvent = + getChangeRoleEvent(updatingProjectUser.getUser(), updatingProjectUser.getProject().getId(), + loggedUser, oldRole, newRole + ); applicationEventPublisher.publishEvent(changeRoleEvent); } private ChangeRoleEvent getChangeRoleEvent(User updatingUser, Long projectId, ReportPortalUser loggedUser, String oldRole, String newRole) { - UserActivityResource userActivityResource = new UserActivityResource(updatingUser.getId(), - projectId, updatingUser.getLogin()); + UserActivityResource userActivityResource = + new UserActivityResource(updatingUser.getId(), projectId, updatingUser.getLogin()); return new ChangeRoleEvent(userActivityResource, oldRole, newRole, loggedUser.getUserId(), - loggedUser.getUsername()); + loggedUser.getUsername() + ); } private void updateProjectConfiguration(ProjectConfigurationUpdate configuration, @@ -509,10 +495,8 @@ private void updateProjectConfiguration(ProjectConfigurationUpdate configuration .ifPresent(attributes -> { projectAttributeValidator.verifyProjectAttributes( ProjectUtils.getConfigParameters(project.getProjectAttributes()), attributes); - attributes.forEach((attribute, value) -> project.getProjectAttributes() - .stream() - .filter(it -> it.getAttribute().getName().equalsIgnoreCase(attribute)) - .findFirst() + attributes.forEach((attribute, value) -> project.getProjectAttributes().stream() + .filter(it -> it.getAttribute().getName().equalsIgnoreCase(attribute)).findFirst() .ifPresent(attr -> attr.setValue(value))); }); } @@ -525,7 +509,8 @@ private void updateSenderCases(Project project, List cases) { expect(findByName(sendCase.getSendCase()).isPresent(), equalTo(true)).verify( BAD_REQUEST_ERROR, sendCase.getSendCase()); expect(sendCase.getRecipients(), notNull()).verify(BAD_REQUEST_ERROR, - "Recipients list should not be null"); + "Recipients list should not be null" + ); expect(sendCase.getRecipients().isEmpty(), equalTo(false)).verify(BAD_REQUEST_ERROR, formattedSupplier("Empty recipients list for email case '{}' ", sendCase) ); @@ -550,11 +535,9 @@ private void updateSenderCases(Project project, List cases) { }); /* If project email settings */ - Set withoutDuplicateCases = cases.stream() - .distinct() - .map(NotificationConfigConverter.TO_CASE_MODEL) - .peek(sc -> sc.setProject(project)) - .collect(toSet()); + Set withoutDuplicateCases = + cases.stream().distinct().map(NotificationConfigConverter.TO_CASE_MODEL) + .peek(sc -> sc.setProject(project)).collect(toSet()); if (cases.size() != withoutDuplicateCases.size()) { fail().withError(BAD_REQUEST_ERROR, "Project email settings contain duplicate cases"); } @@ -578,9 +561,9 @@ private void cutAttributeToMaxLength(ItemAttributeResource entity) { /** * Resolves and publishes activities according to changed attributes * - * @param before Object before update - * @param after Object after update - * @param user User + * @param before Object before update + * @param after Object after update + * @param user User * @param updateConfiguration Configuration fields that has been updated */ private void publishUpdatedAttributesActivities(ProjectAttributesActivityResource before, @@ -594,13 +577,15 @@ private void publishUpdatedAttributesActivities(ProjectAttributesActivityResourc if (ActivityDetailsUtil.configChanged(before.getConfig(), after.getConfig(), Prefix.ANALYZER)) { if (ActivityDetailsUtil.extractConfigByPrefix(updateConfiguration.getProjectAttributes(), - AUTO_PATTERN_ANALYZER_ENABLED.getAttribute()).isEmpty()) { + AUTO_PATTERN_ANALYZER_ENABLED.getAttribute() + ).isEmpty()) { applicationEventPublisher.publishEvent( new ProjectAnalyzerConfigEvent(before, after, user.getUserId(), user.getUsername())); } else { applicationEventPublisher.publishEvent( new ProjectPatternAnalyzerUpdateEvent(before, after, user.getUserId(), - user.getUsername())); + user.getUsername() + )); } } } diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/CreateProjectSettingsHandler.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/CreateProjectSettingsHandler.java index e0e3297479..bf64d06762 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/CreateProjectSettingsHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/CreateProjectSettingsHandler.java @@ -17,10 +17,10 @@ package com.epam.ta.reportportal.core.project.settings; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.project.config.CreateIssueSubTypeRQ; -import com.epam.ta.reportportal.ws.model.project.config.IssueSubTypeCreatedRS; -import com.epam.ta.reportportal.ws.model.project.config.pattern.CreatePatternTemplateRQ; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.project.config.CreateIssueSubTypeRQ; +import com.epam.ta.reportportal.model.project.config.IssueSubTypeCreatedRS; +import com.epam.ta.reportportal.model.project.config.pattern.CreatePatternTemplateRQ; /** * @author Ihar Kahadouski diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/DeleteProjectSettingsHandler.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/DeleteProjectSettingsHandler.java index 92cc4db052..1386e34521 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/DeleteProjectSettingsHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/DeleteProjectSettingsHandler.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.core.project.settings; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * @author Ihar Kahadouski diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/GetProjectSettingsHandler.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/GetProjectSettingsHandler.java index f3b4e0f644..9cfb8a39b0 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/GetProjectSettingsHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/GetProjectSettingsHandler.java @@ -16,7 +16,7 @@ package com.epam.ta.reportportal.core.project.settings; -import com.epam.ta.reportportal.ws.model.project.config.ProjectSettingsResource; +import com.epam.ta.reportportal.model.project.config.ProjectSettingsResource; /** * @author Ihar Kahadouski diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/UpdateProjectSettingsHandler.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/UpdateProjectSettingsHandler.java index 91461da027..01876b8d0a 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/UpdateProjectSettingsHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/UpdateProjectSettingsHandler.java @@ -17,9 +17,9 @@ package com.epam.ta.reportportal.core.project.settings; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.project.config.UpdateIssueSubTypeRQ; -import com.epam.ta.reportportal.ws.model.project.config.pattern.UpdatePatternTemplateRQ; +import com.epam.ta.reportportal.model.project.config.UpdateIssueSubTypeRQ; +import com.epam.ta.reportportal.model.project.config.pattern.UpdatePatternTemplateRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * @author Ihar Kahadouski @@ -47,6 +47,5 @@ OperationCompletionRS updateProjectIssueSubType(String projectName, ReportPortal * @return {@link OperationCompletionRS} */ OperationCompletionRS updatePatternTemplate(Long id, String projectName, - UpdatePatternTemplateRQ updatePatternTemplateRQ, - ReportPortalUser user); + UpdatePatternTemplateRQ updatePatternTemplateRQ, ReportPortalUser user); } diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/CreateProjectSettingsHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/CreateProjectSettingsHandlerImpl.java index 7389c85fb6..deafb9cace 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/CreateProjectSettingsHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/CreateProjectSettingsHandlerImpl.java @@ -25,9 +25,9 @@ import static com.epam.ta.reportportal.entity.enums.TestItemIssueGroup.SYSTEM_ISSUE; import static com.epam.ta.reportportal.entity.enums.TestItemIssueGroup.TO_INVESTIGATE; import static com.epam.ta.reportportal.ws.converter.converters.IssueTypeConverter.TO_ACTIVITY_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.validation.Suppliers; @@ -50,14 +50,14 @@ import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.entity.widget.WidgetType; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.project.config.CreateIssueSubTypeRQ; +import com.epam.ta.reportportal.model.project.config.IssueSubTypeCreatedRS; +import com.epam.ta.reportportal.model.project.config.pattern.CreatePatternTemplateRQ; import com.epam.ta.reportportal.ws.converter.builders.IssueTypeBuilder; import com.epam.ta.reportportal.ws.converter.converters.PatternTemplateConverter; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.epam.ta.reportportal.ws.model.ValidationConstraints; -import com.epam.ta.reportportal.ws.model.project.config.CreateIssueSubTypeRQ; -import com.epam.ta.reportportal.ws.model.project.config.IssueSubTypeCreatedRS; -import com.epam.ta.reportportal.ws.model.project.config.pattern.CreatePatternTemplateRQ; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import java.nio.ByteBuffer; @@ -77,13 +77,10 @@ @Transactional public class CreateProjectSettingsHandlerImpl implements CreateProjectSettingsHandler { - private static final Map PREFIX = ImmutableMap.builder() - .put(AUTOMATION_BUG.getValue(), "ab_") - .put(PRODUCT_BUG.getValue(), "pb_") - .put(SYSTEM_ISSUE.getValue(), "si_") - .put(NO_DEFECT.getValue(), "nd_") - .put(TO_INVESTIGATE.getValue(), "ti_") - .build(); + private static final Map PREFIX = + ImmutableMap.builder().put(AUTOMATION_BUG.getValue(), "ab_") + .put(PRODUCT_BUG.getValue(), "pb_").put(SYSTEM_ISSUE.getValue(), "si_") + .put(NO_DEFECT.getValue(), "nd_").put(TO_INVESTIGATE.getValue(), "ti_").build(); private final ProjectRepository projectRepository; @@ -99,9 +96,9 @@ public class CreateProjectSettingsHandlerImpl implements CreateProjectSettingsHa @Autowired public CreateProjectSettingsHandlerImpl(ProjectRepository projectRepository, - WidgetRepository widgetRepository, - IssueGroupRepository issueGroupRepository, IssueTypeRepository issueTypeRepository, - @Qualifier("createPatternTemplateMapping") Map createPatternTemplateMapping, + WidgetRepository widgetRepository, IssueGroupRepository issueGroupRepository, + IssueTypeRepository issueTypeRepository, @Qualifier("createPatternTemplateMapping") + Map createPatternTemplateMapping, MessageBus messageBus) { this.projectRepository = projectRepository; this.widgetRepository = widgetRepository; @@ -118,9 +115,7 @@ public IssueSubTypeCreatedRS createProjectIssueSubType(String projectName, Repor .orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, projectName)); expect(NOT_ISSUE_FLAG.getValue().equalsIgnoreCase(rq.getTypeRef()), equalTo(false)).verify( - INCORRECT_REQUEST, - "Impossible to create sub-type for 'Not Issue' type." - ); + INCORRECT_REQUEST, "Impossible to create sub-type for 'Not Issue' type."); /* Check if global issue type reference is valid */ TestItemIssueGroup expectedGroup = TestItemIssueGroup.fromValue(rq.getTypeRef()) @@ -128,16 +123,13 @@ public IssueSubTypeCreatedRS createProjectIssueSubType(String projectName, Repor expect( project.getProjectIssueTypes().size() < ValidationConstraints.MAX_ISSUE_TYPES_AND_SUBTYPES, - equalTo(true)).verify(INCORRECT_REQUEST, - "Sub Issues count is bound of size limit" - ); + equalTo(true) + ).verify(INCORRECT_REQUEST, "Sub Issues count is bound of size limit"); String locator = PREFIX.get(expectedGroup.getValue()) + shortUUID(); IssueType subType = new IssueTypeBuilder().addLocator(locator) .addIssueGroup(issueGroupRepository.findByTestItemIssueGroup(expectedGroup)) - .addLongName(rq.getLongName()) - .addShortName(rq.getShortName()) - .addHexColor(rq.getColor()) + .addLongName(rq.getLongName()).addShortName(rq.getShortName()).addHexColor(rq.getColor()) .get(); ProjectIssueType projectIssueType = new ProjectIssueType(); @@ -151,11 +143,10 @@ public IssueSubTypeCreatedRS createProjectIssueSubType(String projectName, Repor updateWidgets(project, subType); - messageBus.publishActivity(new DefectTypeCreatedEvent(TO_ACTIVITY_RESOURCE.apply(subType), - user.getUserId(), - user.getUsername(), - project.getId() - )); + messageBus.publishActivity( + new DefectTypeCreatedEvent(TO_ACTIVITY_RESOURCE.apply(subType), user.getUserId(), + user.getUsername(), project.getId() + )); return new IssueSubTypeCreatedRS(subType.getId(), subType.getLocator()); } @@ -172,11 +163,8 @@ private void updateWidgets(Project project, IssueType issueType) { "statistics$defects$" + issueType.getIssueGroup().getTestItemIssueGroup().getValue() .toLowerCase() + "$"; widgetRepository.findAllByProjectIdAndWidgetTypeInAndContentFieldContaining(project.getId(), - Arrays.stream(WidgetType.values()) - .filter(WidgetType::isIssueTypeUpdateSupported) - .map(WidgetType::getType) - .collect(Collectors.toList()), - issueGroupContentField + Arrays.stream(WidgetType.values()).filter(WidgetType::isIssueTypeUpdateSupported) + .map(WidgetType::getType).collect(Collectors.toList()), issueGroupContentField ).forEach(widget -> { widget.getContentFields().add(issueGroupContentField + issueType.getLocator()); widgetRepository.save(widget); @@ -185,21 +173,20 @@ private void updateWidgets(Project project, IssueType issueType) { @Override public EntryCreatedRS createPatternTemplate(String projectName, - CreatePatternTemplateRQ createPatternTemplateRQ, - ReportPortalUser user) { + CreatePatternTemplateRQ createPatternTemplateRQ, ReportPortalUser user) { Project project = projectRepository.findByName(projectName) .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, projectName)); PatternTemplate patternTemplate = createPatternTemplateMapping.get( - PatternTemplateType.fromString(createPatternTemplateRQ.getType()) - .orElseThrow(() -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, + PatternTemplateType.fromString(createPatternTemplateRQ.getType()).orElseThrow( + () -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, Suppliers.formattedSupplier("Unknown pattern template type - '{}'", - createPatternTemplateRQ.getType()).get() + createPatternTemplateRQ.getType() + ).get() ))).createPatternTemplate(project.getId(), createPatternTemplateRQ); - messageBus.publishActivity(new PatternCreatedEvent(user.getUserId(), - user.getUsername(), + messageBus.publishActivity(new PatternCreatedEvent(user.getUserId(), user.getUsername(), PatternTemplateConverter.TO_ACTIVITY_RESOURCE.apply(patternTemplate) )); return new EntryCreatedRS(patternTemplate.getId()); diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/DeleteProjectSettingsHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/DeleteProjectSettingsHandlerImpl.java index e8f24456e2..e16baa848b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/DeleteProjectSettingsHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/DeleteProjectSettingsHandlerImpl.java @@ -31,10 +31,10 @@ import com.epam.ta.reportportal.entity.project.ProjectIssueType; import com.epam.ta.reportportal.entity.widget.WidgetType; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.activity.PatternTemplateActivityResource; import com.epam.ta.reportportal.ws.converter.converters.PatternTemplateConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.activity.PatternTemplateActivityResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.common.collect.Sets; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; @@ -50,7 +50,7 @@ import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.entity.enums.TestItemIssueGroup.*; import static com.epam.ta.reportportal.ws.converter.converters.IssueTypeConverter.TO_ACTIVITY_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.*; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.*; /** * @author Ihar Kahadouski diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/GetProjectSettingsHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/GetProjectSettingsHandlerImpl.java index f7f14e91ec..376f9451db 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/GetProjectSettingsHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/GetProjectSettingsHandlerImpl.java @@ -20,9 +20,9 @@ import com.epam.ta.reportportal.dao.ProjectRepository; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.project.config.ProjectSettingsResource; import com.epam.ta.reportportal.ws.converter.converters.ProjectSettingsConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.project.config.ProjectSettingsResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/UpdateProjectSettingsHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/UpdateProjectSettingsHandlerImpl.java index 7c99aab66f..0588a9117d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/UpdateProjectSettingsHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/impl/UpdateProjectSettingsHandlerImpl.java @@ -26,9 +26,9 @@ import static com.epam.ta.reportportal.entity.enums.TestItemIssueGroup.SYSTEM_ISSUE; import static com.epam.ta.reportportal.entity.enums.TestItemIssueGroup.TO_INVESTIGATE; import static com.epam.ta.reportportal.ws.converter.converters.IssueTypeConverter.TO_ACTIVITY_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.FORBIDDEN_OPERATION; -import static com.epam.ta.reportportal.ws.model.ErrorType.ISSUE_TYPE_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FORBIDDEN_OPERATION; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ISSUE_TYPE_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; import static java.util.Optional.ofNullable; import com.epam.ta.reportportal.commons.ReportPortalUser; @@ -46,14 +46,14 @@ import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectIssueType; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.activity.IssueTypeActivityResource; +import com.epam.ta.reportportal.model.activity.PatternTemplateActivityResource; +import com.epam.ta.reportportal.model.project.config.UpdateIssueSubTypeRQ; +import com.epam.ta.reportportal.model.project.config.UpdateOneIssueSubTypeRQ; +import com.epam.ta.reportportal.model.project.config.pattern.UpdatePatternTemplateRQ; import com.epam.ta.reportportal.ws.converter.converters.PatternTemplateConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.activity.IssueTypeActivityResource; -import com.epam.ta.reportportal.ws.model.activity.PatternTemplateActivityResource; -import com.epam.ta.reportportal.ws.model.project.config.UpdateIssueSubTypeRQ; -import com.epam.ta.reportportal.ws.model.project.config.UpdateOneIssueSubTypeRQ; -import com.epam.ta.reportportal.ws.model.project.config.pattern.UpdatePatternTemplateRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.common.collect.Sets; import java.util.List; import java.util.stream.Collectors; @@ -77,8 +77,7 @@ public class UpdateProjectSettingsHandlerImpl implements UpdateProjectSettingsHa @Autowired public UpdateProjectSettingsHandlerImpl(ProjectRepository projectRepository, - PatternTemplateRepository patternTemplateRepository, - MessageBus messageBus) { + PatternTemplateRepository patternTemplateRepository, MessageBus messageBus) { this.projectRepository = projectRepository; this.patternTemplateRepository = patternTemplateRepository; this.messageBus = messageBus; @@ -94,61 +93,56 @@ public OperationCompletionRS updateProjectIssueSubType(String projectName, Repor Project project = projectRepository.findByName(projectName) .orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, projectName)); - List issueTypeActivityResources = updateIssueSubTypeRQ.getIds() - .stream() - .map(subTypeRQ -> TO_ACTIVITY_RESOURCE.apply(validateAndUpdate(subTypeRQ, - project.getProjectIssueTypes().stream().map(ProjectIssueType::getIssueType) - .collect(Collectors.toList()) - ))) - .collect(Collectors.toList()); + List issueTypeActivityResources = + updateIssueSubTypeRQ.getIds().stream().map(subTypeRQ -> TO_ACTIVITY_RESOURCE.apply( + validateAndUpdate(subTypeRQ, + project.getProjectIssueTypes().stream().map(ProjectIssueType::getIssueType) + .collect(Collectors.toList()) + ))).collect(Collectors.toList()); projectRepository.save(project); - issueTypeActivityResources.forEach( - it -> messageBus.publishActivity(new DefectTypeUpdatedEvent(it, - user.getUserId(), - user.getUsername(), - project.getId() - ))); + issueTypeActivityResources.forEach(it -> messageBus.publishActivity( + new DefectTypeUpdatedEvent(it, user.getUserId(), user.getUsername(), project.getId()))); return new OperationCompletionRS("Issue sub-type(s) was updated successfully."); } @Override public OperationCompletionRS updatePatternTemplate(Long id, String projectName, - UpdatePatternTemplateRQ updatePatternTemplateRQ, - ReportPortalUser user) { + UpdatePatternTemplateRQ updatePatternTemplateRQ, ReportPortalUser user) { Project project = projectRepository.findByName(projectName) .orElseThrow(() -> new ReportPortalException(ErrorType.PROJECT_NOT_FOUND, projectName)); - PatternTemplate patternTemplate = patternTemplateRepository.findById(id) - .orElseThrow( - () -> new ReportPortalException(ErrorType.PATTERN_TEMPLATE_NOT_FOUND_IN_PROJECT, id, - project.getId())); + PatternTemplate patternTemplate = patternTemplateRepository.findById(id).orElseThrow( + () -> new ReportPortalException(ErrorType.PATTERN_TEMPLATE_NOT_FOUND_IN_PROJECT, id, + project.getId() + )); final String name = StringUtils.trim(updatePatternTemplateRQ.getName()); if (!patternTemplate.getName().equalsIgnoreCase(name)) { - BusinessRule.expect(patternTemplateRepository.existsByProjectIdAndNameIgnoreCase( - project.getId(), name - ), equalTo(false)).verify(ErrorType.RESOURCE_ALREADY_EXISTS, name); + BusinessRule.expect( + patternTemplateRepository.existsByProjectIdAndNameIgnoreCase(project.getId(), name), + equalTo(false) + ).verify(ErrorType.RESOURCE_ALREADY_EXISTS, name); } - PatternTemplateActivityResource before = PatternTemplateConverter.TO_ACTIVITY_RESOURCE.apply( - patternTemplate); + PatternTemplateActivityResource before = + PatternTemplateConverter.TO_ACTIVITY_RESOURCE.apply(patternTemplate); patternTemplate.setName(name); patternTemplate.setEnabled(updatePatternTemplateRQ.getEnabled()); - PatternTemplateActivityResource after = PatternTemplateConverter.TO_ACTIVITY_RESOURCE.apply( - patternTemplate); + PatternTemplateActivityResource after = + PatternTemplateConverter.TO_ACTIVITY_RESOURCE.apply(patternTemplate); messageBus.publishActivity( new PatternUpdatedEvent(user.getUserId(), user.getUsername(), before, after)); return new OperationCompletionRS( Suppliers.formattedSupplier("Pattern template with ID = '{}' has been successfully updated", - id) - .get()); + id + ).get()); } @@ -161,23 +155,17 @@ private IssueType validateAndUpdate(UpdateOneIssueSubTypeRQ issueSubTypeRQ, IssueType exist = issueTypes.stream() .filter(issueType -> issueType.getLocator().equalsIgnoreCase(issueSubTypeRQ.getLocator())) - .findFirst() - .orElseThrow( + .findFirst().orElseThrow( () -> new ReportPortalException(ISSUE_TYPE_NOT_FOUND, issueSubTypeRQ.getLocator())); expect(exist.getIssueGroup().getTestItemIssueGroup().equals(expectedGroup), - equalTo(true)).verify(FORBIDDEN_OPERATION, - "You cannot change sub-type references to global type." - ); + equalTo(true) + ).verify(FORBIDDEN_OPERATION, "You cannot change sub-type references to global type."); - expect(exist.getLocator(), - not(in(Sets.newHashSet(AUTOMATION_BUG.getLocator(), - PRODUCT_BUG.getLocator(), - SYSTEM_ISSUE.getLocator(), - NO_DEFECT.getLocator(), - TO_INVESTIGATE.getLocator() - ))) - ).verify(FORBIDDEN_OPERATION, "You cannot remove predefined global issue types."); + expect(exist.getLocator(), not(in( + Sets.newHashSet(AUTOMATION_BUG.getLocator(), PRODUCT_BUG.getLocator(), + SYSTEM_ISSUE.getLocator(), NO_DEFECT.getLocator(), TO_INVESTIGATE.getLocator() + )))).verify(FORBIDDEN_OPERATION, "You cannot remove predefined global issue types."); ofNullable(issueSubTypeRQ.getLongName()).ifPresent(exist::setLongName); ofNullable(issueSubTypeRQ.getShortName()).ifPresent(exist::setShortName); diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/CreateProjectNotificationHandler.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/CreateProjectNotificationHandler.java index 55cd982c36..62abba41f9 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/CreateProjectNotificationHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/CreateProjectNotificationHandler.java @@ -18,8 +18,8 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.entity.project.Project; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; /** * @author Chingiskhan Kalanov diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/CreateProjectNotificationHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/CreateProjectNotificationHandlerImpl.java index 29879a1487..58b5e888be 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/CreateProjectNotificationHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/CreateProjectNotificationHandlerImpl.java @@ -25,13 +25,13 @@ import com.epam.ta.reportportal.dao.SenderCaseRepository; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.email.SenderCase; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.project.ProjectResource; +import com.epam.ta.reportportal.model.project.email.ProjectNotificationConfigDTO; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; import com.epam.ta.reportportal.ws.converter.converters.NotificationConfigConverter; import com.epam.ta.reportportal.ws.converter.converters.ProjectConverter; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.project.ProjectResource; -import com.epam.ta.reportportal.ws.model.project.email.ProjectNotificationConfigDTO; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Optional; import org.springframework.stereotype.Service; @@ -47,8 +47,7 @@ public class CreateProjectNotificationHandlerImpl implements CreateProjectNotifi private final ProjectNotificationValidator projectNotificationValidator; public CreateProjectNotificationHandlerImpl(SenderCaseRepository senderCaseRepository, - MessageBus messageBus, - ProjectConverter projectConverter, + MessageBus messageBus, ProjectConverter projectConverter, ProjectNotificationValidator projectNotificationValidator) { this.senderCaseRepository = senderCaseRepository; this.messageBus = messageBus; @@ -60,9 +59,9 @@ public CreateProjectNotificationHandlerImpl(SenderCaseRepository senderCaseRepos public EntryCreatedRS createNotification(Project project, SenderCaseDTO createNotificationRQ, ReportPortalUser user) { expect(senderCaseRepository.findByProjectIdAndRuleNameIgnoreCase(project.getId(), - createNotificationRQ.getRuleName()), - Optional::isEmpty) - .verify(ErrorType.RESOURCE_ALREADY_EXISTS, createNotificationRQ.getRuleName()); + createNotificationRQ.getRuleName() + ), Optional::isEmpty).verify( + ErrorType.RESOURCE_ALREADY_EXISTS, createNotificationRQ.getRuleName()); projectNotificationValidator.validateCreateRQ(project, createNotificationRQ); @@ -72,14 +71,12 @@ public EntryCreatedRS createNotification(Project project, SenderCaseDTO createNo senderCaseRepository.save(senderCase); ProjectResource projectResource = projectConverter.TO_PROJECT_RESOURCE.apply(project); - ProjectNotificationConfigDTO projectNotificationConfigDTO = projectResource.getConfiguration() - .getProjectConfig(); + ProjectNotificationConfigDTO projectNotificationConfigDTO = + projectResource.getConfiguration().getProjectConfig(); projectNotificationConfigDTO.getSenderCases().add(createNotificationRQ); messageBus.publishActivity(new NotificationsConfigUpdatedEvent(projectResource, - projectResource.getConfiguration().getProjectConfig(), - user.getUserId(), - user.getUsername() + projectResource.getConfiguration().getProjectConfig(), user.getUserId(), user.getUsername() )); return new EntryCreatedRS(senderCase.getId()); diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/DeleteProjectNotificationHandler.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/DeleteProjectNotificationHandler.java index 28e6165771..33472d099e 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/DeleteProjectNotificationHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/DeleteProjectNotificationHandler.java @@ -20,7 +20,7 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.entity.project.Project; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * @author Chingiskhan Kalanov diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/DeleteProjectNotificationHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/DeleteProjectNotificationHandlerImpl.java index 9c914c8203..02369c2255 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/DeleteProjectNotificationHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/DeleteProjectNotificationHandlerImpl.java @@ -28,11 +28,11 @@ import com.epam.ta.reportportal.dao.SenderCaseRepository; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.email.SenderCase; +import com.epam.ta.reportportal.model.project.ProjectResource; +import com.epam.ta.reportportal.model.project.email.ProjectNotificationConfigDTO; import com.epam.ta.reportportal.ws.converter.converters.ProjectConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.project.ProjectResource; -import com.epam.ta.reportportal.ws.model.project.email.ProjectNotificationConfigDTO; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; @@ -49,8 +49,7 @@ public class DeleteProjectNotificationHandlerImpl implements DeleteProjectNotifi private final ProjectConverter projectConverter; public DeleteProjectNotificationHandlerImpl(SenderCaseRepository senderCaseRepository, - MessageBus messageBus, - ProjectConverter projectConverter) { + MessageBus messageBus, ProjectConverter projectConverter) { this.senderCaseRepository = senderCaseRepository; this.messageBus = messageBus; this.projectConverter = projectConverter; @@ -60,30 +59,23 @@ public DeleteProjectNotificationHandlerImpl(SenderCaseRepository senderCaseRepos public OperationCompletionRS deleteNotification(Project project, Long notificationId, ReportPortalUser user) { Optional senderCase = senderCaseRepository.findById(notificationId); - expect(senderCase, - (notification) -> notification.map( - ntf -> Objects.equals(ntf.getProject().getId(), project.getId())).orElse(false)) - .verify( - ErrorType.BAD_REQUEST_ERROR, - Suppliers.formattedSupplier( - "Notification '{}' not found. Did you use correct Notification ID?", - notificationId).get() - ); + expect(senderCase, (notification) -> notification.map( + ntf -> Objects.equals(ntf.getProject().getId(), project.getId())).orElse(false)).verify( + ErrorType.BAD_REQUEST_ERROR, Suppliers.formattedSupplier( + "Notification '{}' not found. Did you use correct Notification ID?", notificationId) + .get()); senderCaseRepository.deleteSenderCaseById(notificationId); ProjectResource projectResource = projectConverter.TO_PROJECT_RESOURCE.apply(project); - ProjectNotificationConfigDTO projectNotificationConfigDTO = projectResource.getConfiguration() - .getProjectConfig(); + ProjectNotificationConfigDTO projectNotificationConfigDTO = + projectResource.getConfiguration().getProjectConfig(); ofNullable(projectNotificationConfigDTO.getSenderCases()).ifPresent( scs -> projectNotificationConfigDTO.setSenderCases( scs.stream().filter(sc -> !Objects.equals(sc.getId(), notificationId)) - .collect(Collectors.toList()) - )); + .collect(Collectors.toList()))); messageBus.publishActivity(new NotificationsConfigUpdatedEvent(projectResource, - projectResource.getConfiguration().getProjectConfig(), - user.getUserId(), - user.getUsername() + projectResource.getConfiguration().getProjectConfig(), user.getUserId(), user.getUsername() )); return new OperationCompletionRS("Notification rule was deleted successfully."); diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/GetProjectNotificationsHandler.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/GetProjectNotificationsHandler.java index 052be9282d..32fca57b36 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/GetProjectNotificationsHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/GetProjectNotificationsHandler.java @@ -16,7 +16,7 @@ package com.epam.ta.reportportal.core.project.settings.notification; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; import java.util.List; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/GetProjectNotificationsHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/GetProjectNotificationsHandlerImpl.java index ebb99190b6..7559b798b0 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/GetProjectNotificationsHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/GetProjectNotificationsHandlerImpl.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.core.project.settings.notification; import com.epam.ta.reportportal.dao.SenderCaseRepository; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; import com.epam.ta.reportportal.ws.converter.converters.NotificationConfigConverter; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; @@ -40,7 +40,6 @@ public GetProjectNotificationsHandlerImpl(SenderCaseRepository senderCaseReposit @Override public List getProjectNotifications(Long projectId) { return senderCaseRepository.findAllByProjectId(projectId).stream() - .map(NotificationConfigConverter.TO_CASE_RESOURCE) - .collect(Collectors.toList()); + .map(NotificationConfigConverter.TO_CASE_RESOURCE).collect(Collectors.toList()); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/UpdateProjectNotificationHandler.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/UpdateProjectNotificationHandler.java index 11e785b0b5..b200159c15 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/UpdateProjectNotificationHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/UpdateProjectNotificationHandler.java @@ -20,8 +20,8 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.entity.project.Project; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * @author Chingiskhan Kalanov diff --git a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/UpdateProjectNotificationHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/UpdateProjectNotificationHandlerImpl.java index 4a51f5be29..d8b31dac07 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/UpdateProjectNotificationHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/settings/notification/UpdateProjectNotificationHandlerImpl.java @@ -28,13 +28,13 @@ import com.epam.ta.reportportal.dao.SenderCaseRepository; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.email.SenderCase; +import com.epam.ta.reportportal.model.project.ProjectResource; +import com.epam.ta.reportportal.model.project.email.ProjectNotificationConfigDTO; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; import com.epam.ta.reportportal.ws.converter.converters.NotificationConfigConverter; import com.epam.ta.reportportal.ws.converter.converters.ProjectConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.project.ProjectResource; -import com.epam.ta.reportportal.ws.model.project.email.ProjectNotificationConfigDTO; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.Objects; import org.springframework.stereotype.Service; @@ -50,8 +50,7 @@ public class UpdateProjectNotificationHandlerImpl implements UpdateProjectNotifi private final ProjectNotificationValidator projectNotificationValidator; public UpdateProjectNotificationHandlerImpl(SenderCaseRepository senderCaseRepository, - MessageBus messageBus, - ProjectConverter projectConverter, + MessageBus messageBus, ProjectConverter projectConverter, ProjectNotificationValidator projectNotificationValidator) { this.senderCaseRepository = senderCaseRepository; this.messageBus = messageBus; @@ -63,29 +62,27 @@ public UpdateProjectNotificationHandlerImpl(SenderCaseRepository senderCaseRepos public OperationCompletionRS updateNotification(Project project, SenderCaseDTO updateNotificationRQ, ReportPortalUser user) { expect(updateNotificationRQ.getId(), Objects::nonNull).verify(ErrorType.BAD_REQUEST_ERROR, - "Please specify notification Id"); + "Please specify notification Id" + ); expect(senderCaseRepository.findById(updateNotificationRQ.getId()), (notification) -> notification.map( - ntf -> Objects.equals(ntf.getProject().getId(), project.getId())).orElse(false)) - .verify(ErrorType.BAD_REQUEST_ERROR, - Suppliers.formattedSupplier( - "Notification '{}' not found. Did you use correct Notification ID?", - updateNotificationRQ.getId()).get() - ); + ntf -> Objects.equals(ntf.getProject().getId(), project.getId())).orElse(false) + ).verify(ErrorType.BAD_REQUEST_ERROR, Suppliers.formattedSupplier( + "Notification '{}' not found. Did you use correct Notification ID?", + updateNotificationRQ.getId() + ).get()); projectNotificationValidator.validateUpdateRQ(project, updateNotificationRQ); SenderCase notification = NotificationConfigConverter.TO_CASE_MODEL.apply(updateNotificationRQ); notification.setProject(project); senderCaseRepository.save(notification); ProjectResource projectResource = projectConverter.TO_PROJECT_RESOURCE.apply(project); - ProjectNotificationConfigDTO projectNotificationConfigDTO = projectResource.getConfiguration() - .getProjectConfig(); + ProjectNotificationConfigDTO projectNotificationConfigDTO = + projectResource.getConfiguration().getProjectConfig(); projectNotificationConfigDTO.getSenderCases().add(updateNotificationRQ); messageBus.publishActivity(new NotificationsConfigUpdatedEvent(projectResource, - projectResource.getConfiguration().getProjectConfig(), - user.getUserId(), - user.getUsername() + projectResource.getConfiguration().getProjectConfig(), user.getUserId(), user.getUsername() )); return new OperationCompletionRS("Notification rule was updated successfully."); diff --git a/src/main/java/com/epam/ta/reportportal/core/project/validator/attribute/DelayBoundValidator.java b/src/main/java/com/epam/ta/reportportal/core/project/validator/attribute/DelayBoundValidator.java index ae44312b20..58e69d28b8 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/validator/attribute/DelayBoundValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/validator/attribute/DelayBoundValidator.java @@ -2,7 +2,7 @@ import static com.epam.ta.reportportal.commons.Predicates.equalTo; import static com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum.FOREVER_ALIAS; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; import static java.util.Optional.ofNullable; import com.epam.ta.reportportal.commons.validation.BusinessRule; diff --git a/src/main/java/com/epam/ta/reportportal/core/project/validator/attribute/ProjectAttributeValidator.java b/src/main/java/com/epam/ta/reportportal/core/project/validator/attribute/ProjectAttributeValidator.java index cb7f9649b9..63b2692456 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/validator/attribute/ProjectAttributeValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/validator/attribute/ProjectAttributeValidator.java @@ -3,7 +3,7 @@ import static com.epam.ta.reportportal.commons.Predicates.isPresent; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum.FOREVER_ALIAS; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toSet; @@ -11,7 +11,6 @@ import com.epam.ta.reportportal.entity.AnalyzeMode; import com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; import java.util.List; import java.util.Map; import java.util.Set; @@ -37,7 +36,7 @@ public void verifyProjectAttributes(Map currentAttributes, ofNullable(newAttributes.get(ProjectAttributeEnum.AUTO_ANALYZER_MODE.getAttribute())).ifPresent( analyzerMode -> expect(AnalyzeMode.fromString( - analyzerMode), isPresent()).verify(ErrorType.BAD_REQUEST_ERROR, analyzerMode)); + analyzerMode), isPresent()).verify(BAD_REQUEST_ERROR, analyzerMode)); ofNullable(newAttributes.get( ProjectAttributeEnum.SEARCH_LOGS_MIN_SHOULD_MATCH.getAttribute())).ifPresent( diff --git a/src/main/java/com/epam/ta/reportportal/core/project/validator/notification/ProjectNotificationValidator.java b/src/main/java/com/epam/ta/reportportal/core/project/validator/notification/ProjectNotificationValidator.java index d71e8aef83..1fb83e97cc 100644 --- a/src/main/java/com/epam/ta/reportportal/core/project/validator/notification/ProjectNotificationValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/project/validator/notification/ProjectNotificationValidator.java @@ -23,15 +23,15 @@ import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; import static com.epam.ta.reportportal.entity.enums.SendCase.findByName; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toList; import com.epam.ta.reportportal.dao.SenderCaseRepository; import com.epam.ta.reportportal.entity.project.Project; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; import com.epam.ta.reportportal.util.email.EmailRulesValidator; import com.epam.ta.reportportal.ws.converter.converters.NotificationConfigConverter; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -58,13 +58,13 @@ public void validateCreateRQ(Project project, SenderCaseDTO senderCaseDTO) { normalizeCreateNotificationRQ(project, senderCaseDTO); - Optional duplicate = senderCaseRepository.findAllByProjectId(project.getId()) - .stream() - .map(NotificationConfigConverter.TO_CASE_RESOURCE) - .filter(existing -> equalsWithoutRuleName(existing, senderCaseDTO)) - .findFirst(); + Optional duplicate = + senderCaseRepository.findAllByProjectId(project.getId()).stream() + .map(NotificationConfigConverter.TO_CASE_RESOURCE) + .filter(existing -> equalsWithoutRuleName(existing, senderCaseDTO)).findFirst(); expect(duplicate, Optional::isEmpty).verify(BAD_REQUEST_ERROR, - "Project email settings contain duplicate cases"); + "Project email settings contain duplicate cases" + ); } public void validateUpdateRQ(Project project, SenderCaseDTO senderCaseDTO) { @@ -72,24 +72,24 @@ public void validateUpdateRQ(Project project, SenderCaseDTO senderCaseDTO) { normalizeCreateNotificationRQ(project, senderCaseDTO); - Optional duplicate = senderCaseRepository.findAllByProjectId(project.getId()) - .stream() - .filter(senderCase -> !Objects.equals(senderCase.getId(), senderCaseDTO.getId())) - .map(NotificationConfigConverter.TO_CASE_RESOURCE) - .filter(o1 -> equalsWithoutRuleName(o1, senderCaseDTO)) - .findFirst(); + Optional duplicate = + senderCaseRepository.findAllByProjectId(project.getId()).stream() + .filter(senderCase -> !Objects.equals(senderCase.getId(), senderCaseDTO.getId())) + .map(NotificationConfigConverter.TO_CASE_RESOURCE) + .filter(o1 -> equalsWithoutRuleName(o1, senderCaseDTO)).findFirst(); expect(duplicate, Optional::isEmpty).verify(BAD_REQUEST_ERROR, - "Project email settings contain duplicate cases"); + "Project email settings contain duplicate cases" + ); } private void validateRecipients(SenderCaseDTO senderCaseDTO) { List recipients = senderCaseDTO.getRecipients(); - expect(findByName(senderCaseDTO.getSendCase()), Optional::isPresent) - .verify(BAD_REQUEST_ERROR, senderCaseDTO.getSendCase()); + expect(findByName(senderCaseDTO.getSendCase()), Optional::isPresent).verify( + BAD_REQUEST_ERROR, senderCaseDTO.getSendCase()); expect(recipients, notNull()).verify(BAD_REQUEST_ERROR, "Recipients list should not be null"); - expect(recipients.isEmpty(), equalTo(false)) - .verify(BAD_REQUEST_ERROR, - formattedSupplier("Empty recipients list for email case '{}' ", senderCaseDTO)); + expect(recipients.isEmpty(), equalTo(false)).verify(BAD_REQUEST_ERROR, + formattedSupplier("Empty recipients list for email case '{}' ", senderCaseDTO) + ); } private void normalizeCreateNotificationRQ(Project project, SenderCaseDTO createNotificationRQ) { @@ -97,30 +97,25 @@ private void normalizeCreateNotificationRQ(Project project, SenderCaseDTO create createNotificationRQ.getRecipients().stream().map(recipient -> { EmailRulesValidator.validateRecipient(project, recipient); return recipient.trim(); - }).distinct().collect(toList()) - ); + }).distinct().collect(toList())); ofNullable(createNotificationRQ.getLaunchNames()).ifPresent( - launchNames -> createNotificationRQ.setLaunchNames( - launchNames.stream().map(name -> { - EmailRulesValidator.validateLaunchName(name); - return name.trim(); - }).distinct().collect(toList())) - ); + launchNames -> createNotificationRQ.setLaunchNames(launchNames.stream().map(name -> { + EmailRulesValidator.validateLaunchName(name); + return name.trim(); + }).distinct().collect(toList()))); ofNullable(createNotificationRQ.getAttributes()).ifPresent( - attributes -> createNotificationRQ.setAttributes( - attributes.stream().peek(attribute -> { - EmailRulesValidator.validateLaunchAttribute(attribute); - attribute.setValue(attribute.getValue().trim()); - }).collect(Collectors.toSet())) - ); + attributes -> createNotificationRQ.setAttributes(attributes.stream().peek(attribute -> { + EmailRulesValidator.validateLaunchAttribute(attribute); + attribute.setValue(attribute.getValue().trim()); + }).collect(Collectors.toSet()))); } private boolean equalsWithoutRuleName(SenderCaseDTO senderCase, SenderCaseDTO toCompare) { return CollectionUtils.isEqualCollection(senderCase.getRecipients(), toCompare.getRecipients()) && Objects.equals(senderCase.getSendCase(), toCompare.getSendCase()) && CollectionUtils.isEqualCollection(senderCase.getLaunchNames(), - toCompare.getLaunchNames()) - && CollectionUtils.isEqualCollection(senderCase.getAttributes(), toCompare.getAttributes()) + toCompare.getLaunchNames() + ) && CollectionUtils.isEqualCollection(senderCase.getAttributes(), toCompare.getAttributes()) && Objects.equals(senderCase.getAttributesOperator(), toCompare.getAttributesOperator()); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/statistics/StatisticsHelper.java b/src/main/java/com/epam/ta/reportportal/core/statistics/StatisticsHelper.java index 5d84cf435b..76942a0259 100644 --- a/src/main/java/com/epam/ta/reportportal/core/statistics/StatisticsHelper.java +++ b/src/main/java/com/epam/ta/reportportal/core/statistics/StatisticsHelper.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.entity.statistics.Statistics; import com.epam.ta.reportportal.entity.statistics.StatisticsField; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Arrays; import java.util.Set; import java.util.function.Predicate; diff --git a/src/main/java/com/epam/ta/reportportal/core/user/ApiKeyHandler.java b/src/main/java/com/epam/ta/reportportal/core/user/ApiKeyHandler.java index ab0d953176..b5091c89e2 100644 --- a/src/main/java/com/epam/ta/reportportal/core/user/ApiKeyHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/user/ApiKeyHandler.java @@ -16,10 +16,10 @@ package com.epam.ta.reportportal.core.user; -import com.epam.ta.reportportal.ws.model.ApiKeyRQ; -import com.epam.ta.reportportal.ws.model.ApiKeyRS; -import com.epam.ta.reportportal.ws.model.ApiKeysRS; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.model.ApiKeyRQ; +import com.epam.ta.reportportal.model.ApiKeyRS; +import com.epam.ta.reportportal.model.ApiKeysRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * Api keys handler. @@ -32,7 +32,7 @@ public interface ApiKeyHandler { * Generate api key for user. * * @param keyName name of Api Key - * @param userId User id + * @param userId User id * @return generated api key. */ ApiKeyRS createApiKey(String keyName, Long userId); diff --git a/src/main/java/com/epam/ta/reportportal/core/user/CreateUserHandler.java b/src/main/java/com/epam/ta/reportportal/core/user/CreateUserHandler.java index b10b1c7ea7..d4142416ad 100644 --- a/src/main/java/com/epam/ta/reportportal/core/user/CreateUserHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/user/CreateUserHandler.java @@ -17,15 +17,15 @@ package com.epam.ta.reportportal.core.user; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.YesNoRS; -import com.epam.ta.reportportal.ws.model.user.CreateUserBidRS; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQ; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQConfirm; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQFull; -import com.epam.ta.reportportal.ws.model.user.CreateUserRS; -import com.epam.ta.reportportal.ws.model.user.ResetPasswordRQ; -import com.epam.ta.reportportal.ws.model.user.RestorePasswordRQ; +import com.epam.ta.reportportal.model.YesNoRS; +import com.epam.ta.reportportal.model.user.CreateUserBidRS; +import com.epam.ta.reportportal.model.user.CreateUserRQ; +import com.epam.ta.reportportal.model.user.CreateUserRQConfirm; +import com.epam.ta.reportportal.model.user.CreateUserRQFull; +import com.epam.ta.reportportal.model.user.CreateUserRS; +import com.epam.ta.reportportal.model.user.ResetPasswordRQ; +import com.epam.ta.reportportal.model.user.RestorePasswordRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * Post request handler diff --git a/src/main/java/com/epam/ta/reportportal/core/user/DeleteUserHandler.java b/src/main/java/com/epam/ta/reportportal/core/user/DeleteUserHandler.java index b14a0c9b4f..ca35de6142 100644 --- a/src/main/java/com/epam/ta/reportportal/core/user/DeleteUserHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/user/DeleteUserHandler.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.core.user; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.DeleteBulkRS; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.model.DeleteBulkRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.List; /** @@ -38,6 +38,6 @@ public interface DeleteUserHandler { */ OperationCompletionRS deleteUser(Long userId, ReportPortalUser currentUser); - DeleteBulkRS deleteUsers(List ids, ReportPortalUser currentUser); + DeleteBulkRS deleteUsers(List ids, ReportPortalUser currentUser); } diff --git a/src/main/java/com/epam/ta/reportportal/core/user/EditUserHandler.java b/src/main/java/com/epam/ta/reportportal/core/user/EditUserHandler.java index bd79cc62f0..db74381164 100644 --- a/src/main/java/com/epam/ta/reportportal/core/user/EditUserHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/user/EditUserHandler.java @@ -17,9 +17,9 @@ package com.epam.ta.reportportal.core.user; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.user.ChangePasswordRQ; -import com.epam.ta.reportportal.ws.model.user.EditUserRQ; +import com.epam.ta.reportportal.model.user.ChangePasswordRQ; +import com.epam.ta.reportportal.model.user.EditUserRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import org.springframework.web.multipart.MultipartFile; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/user/GetUserHandler.java b/src/main/java/com/epam/ta/reportportal/core/user/GetUserHandler.java index 11ad6bd045..9f2605452c 100644 --- a/src/main/java/com/epam/ta/reportportal/core/user/GetUserHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/user/GetUserHandler.java @@ -20,9 +20,9 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.querygen.Queryable; import com.epam.ta.reportportal.entity.jasper.ReportFormat; -import com.epam.ta.reportportal.ws.model.YesNoRS; -import com.epam.ta.reportportal.ws.model.user.UserBidRS; -import com.epam.ta.reportportal.ws.model.user.UserResource; +import com.epam.ta.reportportal.model.YesNoRS; +import com.epam.ta.reportportal.model.user.UserBidRS; +import com.epam.ta.reportportal.model.user.UserResource; import java.io.OutputStream; import java.util.Map; import javax.servlet.http.HttpServletResponse; diff --git a/src/main/java/com/epam/ta/reportportal/core/user/impl/ApiKeyHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/user/impl/ApiKeyHandlerImpl.java index bc81adebd3..121323a645 100644 --- a/src/main/java/com/epam/ta/reportportal/core/user/impl/ApiKeyHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/user/impl/ApiKeyHandlerImpl.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.core.user.impl; import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; -import static com.epam.ta.reportportal.ws.model.ErrorType.NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.NOT_FOUND; import com.epam.ta.reportportal.commons.Predicates; import com.epam.ta.reportportal.commons.validation.Suppliers; @@ -27,11 +27,11 @@ import com.epam.ta.reportportal.dao.ApiKeyRepository; import com.epam.ta.reportportal.entity.user.ApiKey; import com.epam.ta.reportportal.entity.user.User; +import com.epam.ta.reportportal.model.ApiKeyRS; +import com.epam.ta.reportportal.model.ApiKeysRS; import com.epam.ta.reportportal.ws.converter.converters.ApiKeyConverter; -import com.epam.ta.reportportal.ws.model.ApiKeyRS; -import com.epam.ta.reportportal.ws.model.ApiKeysRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.common.annotations.VisibleForTesting; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; diff --git a/src/main/java/com/epam/ta/reportportal/core/user/impl/CreateUserHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/user/impl/CreateUserHandlerImpl.java index 5baa5625e9..88e03bfdf5 100644 --- a/src/main/java/com/epam/ta/reportportal/core/user/impl/CreateUserHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/user/impl/CreateUserHandlerImpl.java @@ -26,14 +26,14 @@ import static com.epam.ta.reportportal.entity.project.ProjectRole.forName; import static com.epam.ta.reportportal.entity.project.ProjectUtils.findUserConfigByLogin; import static com.epam.ta.reportportal.ws.converter.converters.UserConverter.TO_ACTIVITY_RESOURCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.ACCESS_DENIED; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; -import static com.epam.ta.reportportal.ws.model.ErrorType.EMAIL_CONFIGURATION_IS_INCORRECT; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; -import static com.epam.ta.reportportal.ws.model.ErrorType.RESOURCE_ALREADY_EXISTS; -import static com.epam.ta.reportportal.ws.model.ErrorType.ROLE_NOT_FOUND; -import static com.epam.ta.reportportal.ws.model.ErrorType.USER_ALREADY_EXISTS; -import static com.epam.ta.reportportal.ws.model.ErrorType.USER_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ACCESS_DENIED; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.EMAIL_CONFIGURATION_IS_INCORRECT; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.RESOURCE_ALREADY_EXISTS; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.ROLE_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.USER_ALREADY_EXISTS; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.USER_NOT_FOUND; import com.epam.ta.reportportal.auth.authenticator.UserAuthenticator; import com.epam.ta.reportportal.commons.ReportPortalUser; @@ -60,23 +60,23 @@ import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.entity.user.UserType; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.YesNoRS; +import com.epam.ta.reportportal.model.activity.UserActivityResource; +import com.epam.ta.reportportal.model.user.CreateUserBidRS; +import com.epam.ta.reportportal.model.user.CreateUserRQ; +import com.epam.ta.reportportal.model.user.CreateUserRQConfirm; +import com.epam.ta.reportportal.model.user.CreateUserRQFull; +import com.epam.ta.reportportal.model.user.CreateUserRS; +import com.epam.ta.reportportal.model.user.ResetPasswordRQ; +import com.epam.ta.reportportal.model.user.RestorePasswordRQ; import com.epam.ta.reportportal.util.Predicates; import com.epam.ta.reportportal.util.UserUtils; import com.epam.ta.reportportal.util.email.MailServiceFactory; import com.epam.ta.reportportal.ws.converter.builders.UserBuilder; import com.epam.ta.reportportal.ws.converter.converters.RestorePasswordBidConverter; import com.epam.ta.reportportal.ws.converter.converters.UserCreationBidConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.YesNoRS; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; -import com.epam.ta.reportportal.ws.model.user.CreateUserBidRS; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQ; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQConfirm; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQFull; -import com.epam.ta.reportportal.ws.model.user.CreateUserRS; -import com.epam.ta.reportportal.ws.model.user.ResetPasswordRQ; -import com.epam.ta.reportportal.ws.model.user.RestorePasswordRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.common.collect.Maps; import java.util.Map; import java.util.Optional; diff --git a/src/main/java/com/epam/ta/reportportal/core/user/impl/DeleteUserHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/user/impl/DeleteUserHandlerImpl.java index db4e29382a..1f5e5cfd94 100644 --- a/src/main/java/com/epam/ta/reportportal/core/user/impl/DeleteUserHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/user/impl/DeleteUserHandlerImpl.java @@ -36,12 +36,12 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.DeleteBulkRS; +import com.epam.ta.reportportal.model.activity.UserActivityResource; import com.epam.ta.reportportal.util.email.strategy.EmailNotificationStrategy; import com.epam.ta.reportportal.util.email.strategy.EmailTemplate; -import com.epam.ta.reportportal.ws.model.DeleteBulkRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; diff --git a/src/main/java/com/epam/ta/reportportal/core/user/impl/EditUserHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/user/impl/EditUserHandlerImpl.java index 2d230c7e31..ad3cc22504 100644 --- a/src/main/java/com/epam/ta/reportportal/core/user/impl/EditUserHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/user/impl/EditUserHandlerImpl.java @@ -32,13 +32,12 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.user.ChangePasswordRQ; +import com.epam.ta.reportportal.model.user.EditUserRQ; import com.epam.ta.reportportal.util.UserUtils; import com.epam.ta.reportportal.util.email.MailServiceFactory; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; -import com.epam.ta.reportportal.ws.model.user.ChangePasswordRQ; -import com.epam.ta.reportportal.ws.model.user.EditUserRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import org.apache.tika.io.TikaInputStream; import org.apache.tika.metadata.Metadata; import org.apache.tika.mime.MediaType; @@ -66,7 +65,7 @@ import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import static com.epam.ta.reportportal.commons.validation.BusinessRule.fail; import static com.epam.ta.reportportal.entity.user.UserType.INTERNAL; -import static com.epam.ta.reportportal.ws.model.ErrorType.*; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.*; import static com.epam.ta.reportportal.ws.model.ValidationConstraints.*; import static java.util.Optional.ofNullable; diff --git a/src/main/java/com/epam/ta/reportportal/core/user/impl/GetUserHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/user/impl/GetUserHandlerImpl.java index 6459fbf948..44858a486c 100644 --- a/src/main/java/com/epam/ta/reportportal/core/user/impl/GetUserHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/user/impl/GetUserHandlerImpl.java @@ -42,13 +42,13 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserCreationBid; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.YesNoRS; +import com.epam.ta.reportportal.model.user.UserBidRS; +import com.epam.ta.reportportal.model.user.UserResource; import com.epam.ta.reportportal.util.PersonalProjectService; import com.epam.ta.reportportal.ws.converter.PagedResourcesAssembler; import com.epam.ta.reportportal.ws.converter.converters.UserConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.YesNoRS; -import com.epam.ta.reportportal.ws.model.user.UserBidRS; -import com.epam.ta.reportportal.ws.model.user.UserResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.base.Preconditions; import java.io.OutputStream; import java.util.List; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/CreateWidgetHandler.java b/src/main/java/com/epam/ta/reportportal/core/widget/CreateWidgetHandler.java index 1d5c8cf0ab..73c073785e 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/CreateWidgetHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/CreateWidgetHandler.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.core.widget; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.widget.WidgetRQ; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.widget.WidgetRQ; /** * @author Pavel Bortnik diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/GetWidgetHandler.java b/src/main/java/com/epam/ta/reportportal/core/widget/GetWidgetHandler.java index 422f7cf00c..2afccb76e3 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/GetWidgetHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/GetWidgetHandler.java @@ -18,8 +18,8 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Filter; -import com.epam.ta.reportportal.ws.model.widget.WidgetPreviewRQ; -import com.epam.ta.reportportal.ws.model.widget.WidgetResource; +import com.epam.ta.reportportal.model.widget.WidgetPreviewRQ; +import com.epam.ta.reportportal.model.widget.WidgetResource; import org.springframework.data.domain.Pageable; import org.springframework.util.MultiValueMap; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/UpdateWidgetHandler.java b/src/main/java/com/epam/ta/reportportal/core/widget/UpdateWidgetHandler.java index df8f2bea0d..bba93afbcc 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/UpdateWidgetHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/UpdateWidgetHandler.java @@ -17,10 +17,8 @@ package com.epam.ta.reportportal.core.widget; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.entity.widget.Widget; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.widget.WidgetRQ; -import java.util.Collection; +import com.epam.ta.reportportal.model.widget.WidgetRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; /** * @author Pavel Bortnik @@ -30,14 +28,13 @@ public interface UpdateWidgetHandler { /** * Update a widget with a specified id. * - * @param widgetId The ID of the widget to be updated - * @param updateRQ The {@link WidgetRQ} containing the updated information for the widget + * @param widgetId The ID of the widget to be updated + * @param updateRQ The {@link WidgetRQ} containing the updated information for the widget * @param projectDetails The {@link ReportPortalUser.ProjectDetails} for the project associated with the widget - * @param user The {@link ReportPortalUser} who is updating the widget + * @param user The {@link ReportPortalUser} who is updating the widget * @return An {@link OperationCompletionRS} instance indicating the result of the update operation */ OperationCompletionRS updateWidget(Long widgetId, WidgetRQ updateRQ, - ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user); + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user); } \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/MaterializedLoadContentStrategyImpl.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/MaterializedLoadContentStrategyImpl.java index 5d2593a3fb..6f232048f4 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/MaterializedLoadContentStrategyImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/MaterializedLoadContentStrategyImpl.java @@ -8,7 +8,7 @@ import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.entity.widget.WidgetState; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/constant/ContentLoaderConstants.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/constant/ContentLoaderConstants.java index 571dccd381..def2d45c94 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/constant/ContentLoaderConstants.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/constant/ContentLoaderConstants.java @@ -39,6 +39,8 @@ public final class ContentLoaderConstants { public static final String TIMELINE = "timeline"; public static final String ATTRIBUTE_KEYS = "attributeKeys"; public static final String MIN_PASSING_RATE = "minPassingRate"; + public static final String EXCLUDE_SKIPPED = "excludeSkipped"; + private ContentLoaderConstants() { //static only diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/filter/GeneralLaunchFilterStrategy.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/filter/GeneralLaunchFilterStrategy.java index b389158520..382f00b3a3 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/filter/GeneralLaunchFilterStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/filter/GeneralLaunchFilterStrategy.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.commons.querygen.FilterCondition; import com.epam.ta.reportportal.entity.enums.StatusEnum; import com.epam.ta.reportportal.entity.widget.Widget; -import com.epam.ta.reportportal.ws.model.launch.Mode; +import com.epam.ta.reportportal.ws.reporting.Mode; import com.google.common.collect.Lists; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/filter/LaunchHistoryFilterStrategy.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/filter/LaunchHistoryFilterStrategy.java index ff500d15ff..c1356c906c 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/filter/LaunchHistoryFilterStrategy.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/filter/LaunchHistoryFilterStrategy.java @@ -29,7 +29,7 @@ import com.epam.ta.reportportal.entity.enums.StatusEnum; import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/ActivityContentLoader.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/ActivityContentLoader.java index 5168341422..1e6d3b41e9 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/ActivityContentLoader.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/ActivityContentLoader.java @@ -37,7 +37,7 @@ import com.epam.ta.reportportal.entity.widget.WidgetOptions; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.model.ActivityResource; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Arrays; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/ComponentHealthCheckContentLoader.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/ComponentHealthCheckContentLoader.java index 574804d49b..e2113a56bd 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/ComponentHealthCheckContentLoader.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/ComponentHealthCheckContentLoader.java @@ -24,6 +24,7 @@ import static com.epam.ta.reportportal.commons.querygen.constant.TestItemCriteriaConstant.CRITERIA_STATUS; import static com.epam.ta.reportportal.commons.querygen.constant.TestItemCriteriaConstant.CRITERIA_TYPE; import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.ATTRIBUTE_KEYS; +import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.EXCLUDE_SKIPPED; import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.LATEST_OPTION; import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.RESULT; import static com.epam.ta.reportportal.core.widget.util.WidgetFilterUtil.GROUP_FILTERS; @@ -46,7 +47,7 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.widget.WidgetOptions; import com.epam.ta.reportportal.entity.widget.content.healthcheck.ComponentHealthCheckContent; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Lists; import java.util.Arrays; import java.util.Collections; @@ -105,7 +106,8 @@ public Map loadContent(List contentFields, latestMode, limit, testItemFilter, - currentLevelKey + currentLevelKey, + WidgetOptionUtil.getBooleanByKey(EXCLUDE_SKIPPED, widgetOptions) ); return CollectionUtils.isNotEmpty(content) ? Collections.singletonMap(RESULT, content) diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/materialized/CumulativeTrendChartContentLoaderImpl.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/materialized/CumulativeTrendChartContentLoaderImpl.java index 5e29129ce2..6476f03a0b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/materialized/CumulativeTrendChartContentLoaderImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/materialized/CumulativeTrendChartContentLoaderImpl.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.dao.WidgetContentRepository; import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.entity.widget.content.CumulativeTrendChartEntry; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.ImmutableMap; import java.util.Collections; import java.util.List; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/materialized/HealthCheckTableReadyContentLoader.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/materialized/HealthCheckTableReadyContentLoader.java index 8e68f5a94d..aa8f8f39dd 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/materialized/HealthCheckTableReadyContentLoader.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/materialized/HealthCheckTableReadyContentLoader.java @@ -2,6 +2,7 @@ import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.ATTRIBUTES; import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.ATTRIBUTE_KEYS; +import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.EXCLUDE_SKIPPED; import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.RESULT; import static com.epam.ta.reportportal.core.widget.content.loader.materialized.handler.MaterializedWidgetStateHandler.VIEW_NAME; import static com.epam.ta.reportportal.dao.constant.WidgetContentRepositoryConstants.EXECUTIONS_PASSED; @@ -19,8 +20,8 @@ import com.epam.ta.reportportal.entity.widget.content.healthcheck.HealthCheckTableGetParams; import com.epam.ta.reportportal.entity.widget.content.healthcheck.LevelEntry; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.widget.SortEntry; +import com.epam.ta.reportportal.model.widget.SortEntry; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; @@ -47,7 +48,6 @@ public class HealthCheckTableReadyContentLoader implements MaterializedWidgetCon public static final String SORT = "sort"; public static final String CUSTOM_COLUMN = "customColumn"; - public static final String TOTAL = "total"; public static final String STATISTICS = "statistics"; public static final String PASSING_RATE = "passingRate"; @@ -64,31 +64,25 @@ public HealthCheckTableReadyContentLoader(WidgetContentRepository widgetContentR @Override public Map loadContent(Widget widget, MultiValueMap params) { - HealthCheckTableGetParams getParams = getParams(widget.getWidgetOptions(), - ofNullable(params.get(ATTRIBUTES)).map(attributes -> attributes.stream() - .filter(StringUtils::isNotBlank) - .collect(Collectors.toList())).orElseGet(Collections::emptyList) - ); - List content = widgetContentRepository.componentHealthCheckTable( - getParams); + HealthCheckTableGetParams getParams = + getParams(widget.getWidgetOptions(), ofNullable(params.get(ATTRIBUTES)).map( + attributes -> attributes.stream().filter(StringUtils::isNotBlank) + .collect(Collectors.toList())).orElseGet(Collections::emptyList)); + List content = + widgetContentRepository.componentHealthCheckTable(getParams); if (CollectionUtils.isEmpty(content)) { return emptyMap(); } - Map totalStatistics = content.stream() - .map(HealthCheckTableContent::getStatistics) - .map(Map::entrySet) - .flatMap(Collection::stream) - .collect(groupingBy(Map.Entry::getKey, Collectors.summingInt(Map.Entry::getValue))); + Map totalStatistics = + content.stream().map(HealthCheckTableContent::getStatistics).map(Map::entrySet) + .flatMap(Collection::stream) + .collect(groupingBy(Map.Entry::getKey, Collectors.summingInt(Map.Entry::getValue))); return ImmutableMap.builder().put(RESULT, content) - .put(TOTAL, - ImmutableMap.builder().put(STATISTICS, totalStatistics) - .put(PASSING_RATE, calculatePassingRate(totalStatistics)) - .build() - ) - .build(); + .put(TOTAL, ImmutableMap.builder().put(STATISTICS, totalStatistics) + .put(PASSING_RATE, calculatePassingRate(totalStatistics)).build()).build(); } private HealthCheckTableGetParams getParams(WidgetOptions widgetOptions, @@ -98,21 +92,18 @@ private HealthCheckTableGetParams getParams(WidgetOptions widgetOptions, BusinessRule.expect(attributeKeys, keys -> keys.size() > currentLevel) .verify(ErrorType.UNABLE_LOAD_WIDGET_CONTENT, "Incorrect level definition"); - String viewName = ofNullable( - WidgetOptionUtil.getValueByKey(VIEW_NAME, widgetOptions)).orElseThrow( - () -> new ReportPortalException( - ErrorType.UNABLE_LOAD_WIDGET_CONTENT, - "Widget view name not provided" - )); + String viewName = + ofNullable(WidgetOptionUtil.getValueByKey(VIEW_NAME, widgetOptions)).orElseThrow( + () -> new ReportPortalException(ErrorType.UNABLE_LOAD_WIDGET_CONTENT, + "Widget view name not provided" + )); String currentLevelKey = attributeKeys.get(currentLevel); - boolean includeCustomColumn = ofNullable( - WidgetOptionUtil.getValueByKey(CUSTOM_COLUMN, widgetOptions)).isPresent(); - - return HealthCheckTableGetParams.of(viewName, - currentLevelKey, - resolveSort(widgetOptions), - includeCustomColumn, - getLevelEntries(attributeKeys, attributeValues) + boolean includeCustomColumn = + ofNullable(WidgetOptionUtil.getValueByKey(CUSTOM_COLUMN, widgetOptions)).isPresent(); + + return HealthCheckTableGetParams.of(viewName, currentLevelKey, resolveSort(widgetOptions), + includeCustomColumn, getLevelEntries(attributeKeys, attributeValues), + WidgetOptionUtil.getBooleanByKey(EXCLUDE_SKIPPED, widgetOptions) ); } @@ -121,16 +112,19 @@ private Sort resolveSort(WidgetOptions widgetOptions) { return ofNullable(widgetOptions).flatMap( wo -> ofNullable(wo.getOptions()).map(options -> options.get(SORT))).map(s -> { try { - SortEntry sortEntry = objectMapper.readValue(objectMapper.writeValueAsString(s), - SortEntry.class); + SortEntry sortEntry = + objectMapper.readValue(objectMapper.writeValueAsString(s), SortEntry.class); return Sort.by(sortEntry.isAsc() ? Sort.Direction.ASC : Sort.Direction.DESC, - sortEntry.getSortingColumn()); + sortEntry.getSortingColumn() + ); } catch (JsonProcessingException e) { throw new ReportPortalException(ErrorType.UNABLE_LOAD_WIDGET_CONTENT, - "Sort format error: " + e.getMessage()); + "Sort format error: " + e.getMessage() + ); } }).orElseThrow(() -> new ReportPortalException(ErrorType.UNABLE_LOAD_WIDGET_CONTENT, - "Sort parameter not provided")); + "Sort parameter not provided" + )); } private List getLevelEntries(List attributeKeys, @@ -146,7 +140,7 @@ private double calculatePassingRate(Map totalStatistics) { double passingRate = 100.0 * totalStatistics.getOrDefault(EXECUTIONS_PASSED, 0) / totalStatistics.getOrDefault( EXECUTIONS_TOTAL, 1); - return new BigDecimal(passingRate).setScale(2, RoundingMode.HALF_UP).doubleValue(); + return BigDecimal.valueOf(passingRate).setScale(2, RoundingMode.HALF_UP).doubleValue(); } } diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/materialized/handler/ReadyMaterializedWidgetStateHandler.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/materialized/handler/ReadyMaterializedWidgetStateHandler.java index 1bd3eb099b..17c7e4503e 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/materialized/handler/ReadyMaterializedWidgetStateHandler.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/materialized/handler/ReadyMaterializedWidgetStateHandler.java @@ -7,7 +7,7 @@ import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.entity.widget.WidgetType; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Collections; import java.util.Map; import org.apache.commons.lang3.BooleanUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/util/ProductStatusContentLoaderManager.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/util/ProductStatusContentLoaderManager.java index 93daa4e7eb..7524bc06eb 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/util/ProductStatusContentLoaderManager.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/loader/util/ProductStatusContentLoaderManager.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.core.widget.util.WidgetOptionUtil; import com.epam.ta.reportportal.entity.widget.WidgetOptions; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/materialized/state/WidgetStateResolver.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/materialized/state/WidgetStateResolver.java index c04bb3c612..dcb66a5ca6 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/materialized/state/WidgetStateResolver.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/materialized/state/WidgetStateResolver.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.entity.widget.WidgetOptions; import com.epam.ta.reportportal.entity.widget.WidgetState; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.springframework.stereotype.Component; /** diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ActivityContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ActivityContentValidator.java index e5c1d36b58..e1ea2f0932 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ActivityContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ActivityContentValidator.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/BugTrendChartContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/BugTrendChartContentValidator.java index 5c66db1dad..e3f2badc90 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/BugTrendChartContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/BugTrendChartContentValidator.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.core.widget.util.ContentFieldMatcherUtil; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/CasesTrendContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/CasesTrendContentValidator.java index af92dacbc6..4bc315a59b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/CasesTrendContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/CasesTrendContentValidator.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.core.widget.util.ContentFieldMatcherUtil; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ChartInvestigatedContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ChartInvestigatedContentValidator.java index cf52c58ce0..879d5a3504 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ChartInvestigatedContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ChartInvestigatedContentValidator.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ComponentHealthCheckContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ComponentHealthCheckContentValidator.java index 4d317b31bf..f78c8c85e8 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ComponentHealthCheckContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ComponentHealthCheckContentValidator.java @@ -17,6 +17,7 @@ package com.epam.ta.reportportal.core.widget.content.updater.validator; import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.ATTRIBUTE_KEYS; +import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.EXCLUDE_SKIPPED; import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.MIN_PASSING_RATE; import static java.util.Optional.ofNullable; @@ -25,7 +26,7 @@ import com.epam.ta.reportportal.core.widget.util.WidgetOptionUtil; import com.epam.ta.reportportal.entity.widget.WidgetOptions; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -77,6 +78,12 @@ private void validateWidgetOptions(WidgetOptions widgetOptions) { .orElseThrow(() -> new ReportPortalException(ErrorType.UNABLE_LOAD_WIDGET_CONTENT, "Minimum passing rate option was not specified" )); + + BusinessRule.expect(WidgetOptionUtil.isBooleanPresent(EXCLUDE_SKIPPED, widgetOptions), + isPresent -> isPresent) + .verify(ErrorType.UNABLE_LOAD_WIDGET_CONTENT, + "Exclude skipped tests option was not specified"); + BusinessRule.expect(passingRate, v -> v >= 0 && v <= 100) .verify(ErrorType.UNABLE_LOAD_WIDGET_CONTENT, "Minimum passing rate value should be greater or equal to 0 and less or equal to 100" @@ -87,4 +94,4 @@ private void validateAttributeValues(List attributeValues) { attributeValues.forEach(value -> BusinessRule.expect(value, Objects::nonNull) .verify(ErrorType.BAD_REQUEST_ERROR, "Attribute value should be not null")); } -} \ No newline at end of file +} diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/CumulativeTrendChartValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/CumulativeTrendChartValidator.java index 9a43600aec..53ac981b2d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/CumulativeTrendChartValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/CumulativeTrendChartValidator.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.core.widget.util.ContentFieldMatcherUtil; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/FlakyCasesTableContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/FlakyCasesTableContentValidator.java index 5bd00c4856..887b461754 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/FlakyCasesTableContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/FlakyCasesTableContentValidator.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.core.widget.util.WidgetOptionUtil; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchExecutionAndIssueStatisticsContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchExecutionAndIssueStatisticsContentValidator.java index c3520738cd..e0a7bf179b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchExecutionAndIssueStatisticsContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchExecutionAndIssueStatisticsContentValidator.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.core.widget.util.ContentFieldMatcherUtil; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchesComparisonContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchesComparisonContentValidator.java index 24e5b15175..b53544d5e7 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchesComparisonContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchesComparisonContentValidator.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.core.widget.util.ContentFieldMatcherUtil; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchesDurationContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchesDurationContentValidator.java index 7419b57e7e..2db1c2ee32 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchesDurationContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchesDurationContentValidator.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchesTableContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchesTableContentValidator.java index 56eae71d8a..b4342e83cf 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchesTableContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LaunchesTableContentValidator.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LineChartContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LineChartContentValidator.java index dd2ea8f2e7..8ddae39cbf 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LineChartContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/LineChartContentValidator.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.core.widget.util.ContentFieldMatcherUtil; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/MostTimeConsumingContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/MostTimeConsumingContentValidator.java index 6764f9062e..ec9edebafd 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/MostTimeConsumingContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/MostTimeConsumingContentValidator.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.core.widget.util.WidgetOptionUtil; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/NotPassedTestsContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/NotPassedTestsContentValidator.java index ce922ca15d..60c2987060 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/NotPassedTestsContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/NotPassedTestsContentValidator.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/OverallStatisticsContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/OverallStatisticsContentValidator.java index 1d7a6652a2..77dc70c1c7 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/OverallStatisticsContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/OverallStatisticsContentValidator.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/PassingRatePerLaunchContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/PassingRatePerLaunchContentValidator.java index 4b6dca07e4..2696465bdb 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/PassingRatePerLaunchContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/PassingRatePerLaunchContentValidator.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.core.widget.util.WidgetOptionUtil; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/PassingRateSummaryContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/PassingRateSummaryContentValidator.java index bf23857362..178e8e9a5d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/PassingRateSummaryContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/PassingRateSummaryContentValidator.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ProductStatusContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ProductStatusContentValidator.java index 2c0aa0d1d1..a0198de27b 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ProductStatusContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ProductStatusContentValidator.java @@ -5,7 +5,7 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/TopPatternContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/TopPatternContentValidator.java index 636166d07c..5d3855f896 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/TopPatternContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/TopPatternContentValidator.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/TopTestCasesContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/TopTestCasesContentValidator.java index 52c976971b..7061bc64ca 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/TopTestCasesContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/TopTestCasesContentValidator.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import java.util.function.Predicate; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/UniqueBugContentValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/UniqueBugContentValidator.java index 7c0066a3fb..0e69e9edb0 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/UniqueBugContentValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/UniqueBugContentValidator.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/WidgetContentFieldsValidator.java b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/WidgetContentFieldsValidator.java index 9482202977..c4b1229862 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/WidgetContentFieldsValidator.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/content/updater/validator/WidgetContentFieldsValidator.java @@ -6,7 +6,7 @@ import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.entity.widget.WidgetType; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Lists; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/impl/CreateWidgetHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/widget/impl/CreateWidgetHandlerImpl.java index c77fdbf3a3..f6cf7e994d 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/impl/CreateWidgetHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/impl/CreateWidgetHandlerImpl.java @@ -16,6 +16,10 @@ package com.epam.ta.reportportal.core.widget.impl; +import static com.epam.ta.reportportal.commons.Predicates.not; +import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_ID; +import static com.epam.ta.reportportal.ws.converter.converters.WidgetConverter.TO_ACTIVITY_RESOURCE; + import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Condition; import com.epam.ta.reportportal.commons.querygen.Filter; @@ -31,85 +35,89 @@ import com.epam.ta.reportportal.dao.WidgetRepository; import com.epam.ta.reportportal.entity.filter.UserFilter; import com.epam.ta.reportportal.entity.widget.Widget; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.widget.WidgetRQ; import com.epam.ta.reportportal.ws.converter.builders.WidgetBuilder; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.widget.WidgetRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.BooleanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import static com.epam.ta.reportportal.commons.Predicates.not; -import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_ID; -import static com.epam.ta.reportportal.ws.converter.converters.WidgetConverter.TO_ACTIVITY_RESOURCE; - /** * @author Pavel Bortnik */ @Service public class CreateWidgetHandlerImpl implements CreateWidgetHandler { - private final WidgetRepository widgetRepository; - - private final UserFilterRepository filterRepository; - - private final MessageBus messageBus; - - private final UpdateUserFilterHandler updateUserFilterHandler; - - private final List widgetPostProcessors; - - private final WidgetValidator widgetContentFieldsValidator; - - @Autowired - public CreateWidgetHandlerImpl(WidgetRepository widgetRepository, UserFilterRepository filterRepository, MessageBus messageBus, - UpdateUserFilterHandler updateUserFilterHandler, - List widgetPostProcessors, WidgetValidator widgetContentFieldsValidator) { - this.widgetRepository = widgetRepository; - this.filterRepository = filterRepository; - this.messageBus = messageBus; - this.updateUserFilterHandler = updateUserFilterHandler; - this.widgetPostProcessors = widgetPostProcessors; - this.widgetContentFieldsValidator = widgetContentFieldsValidator; - } - - @Override - public EntryCreatedRS createWidget(WidgetRQ createWidgetRQ, ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { - List userFilter = getUserFilters(createWidgetRQ.getFilterIds(), projectDetails.getProjectId(), user.getUsername()); - - Widget widget = new WidgetBuilder().addWidgetRq(createWidgetRQ) - .addProject(projectDetails.getProjectId()) - .addFilters(userFilter) - .addOwner(user.getUsername()) - .get(); - - widgetContentFieldsValidator.validate(widget); - - widgetPostProcessors.stream() - .filter(widgetPostProcessor -> widgetPostProcessor.supports(widget)) - .forEach(widgetPostProcessor -> widgetPostProcessor.postProcess(widget)); - - widgetRepository.save(widget); - - messageBus.publishActivity(new WidgetCreatedEvent(TO_ACTIVITY_RESOURCE.apply(widget), user.getUserId(), user.getUsername())); - return new EntryCreatedRS(widget.getId()); - } - - private List getUserFilters(List filterIds, Long projectId, String username) { - if (CollectionUtils.isNotEmpty(filterIds)) { - String ids = filterIds.stream().map(String::valueOf).collect(Collectors.joining(",")); - Filter defaultFilter = new Filter(UserFilter.class, Condition.IN, false, ids, CRITERIA_ID); - List userFilters = filterRepository.findByFilter(ProjectFilter.of(defaultFilter, projectId), Pageable.unpaged()) - .getContent(); - BusinessRule.expect(userFilters, not(List::isEmpty)).verify(ErrorType.USER_FILTER_NOT_FOUND, filterIds, projectId, username); - return userFilters; - } - return Collections.emptyList(); - } + private final WidgetRepository widgetRepository; + + private final UserFilterRepository filterRepository; + + private final MessageBus messageBus; + + private final UpdateUserFilterHandler updateUserFilterHandler; + + private final List widgetPostProcessors; + + private final WidgetValidator widgetContentFieldsValidator; + + @Autowired + public CreateWidgetHandlerImpl(WidgetRepository widgetRepository, + UserFilterRepository filterRepository, MessageBus messageBus, + UpdateUserFilterHandler updateUserFilterHandler, + List widgetPostProcessors, + WidgetValidator widgetContentFieldsValidator) { + this.widgetRepository = widgetRepository; + this.filterRepository = filterRepository; + this.messageBus = messageBus; + this.updateUserFilterHandler = updateUserFilterHandler; + this.widgetPostProcessors = widgetPostProcessors; + this.widgetContentFieldsValidator = widgetContentFieldsValidator; + } + + @Override + public EntryCreatedRS createWidget(WidgetRQ createWidgetRQ, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { + List userFilter = + getUserFilters(createWidgetRQ.getFilterIds(), projectDetails.getProjectId(), + user.getUsername() + ); + + Widget widget = + new WidgetBuilder().addWidgetRq(createWidgetRQ).addProject(projectDetails.getProjectId()) + .addFilters(userFilter).addOwner(user.getUsername()).get(); + + widgetContentFieldsValidator.validate(widget); + + widgetPostProcessors.stream() + .filter(widgetPostProcessor -> widgetPostProcessor.supports(widget)) + .forEach(widgetPostProcessor -> widgetPostProcessor.postProcess(widget)); + + widgetRepository.save(widget); + + messageBus.publishActivity( + new WidgetCreatedEvent(TO_ACTIVITY_RESOURCE.apply(widget), user.getUserId(), + user.getUsername() + )); + return new EntryCreatedRS(widget.getId()); + } + + private List getUserFilters(List filterIds, Long projectId, String username) { + if (CollectionUtils.isNotEmpty(filterIds)) { + String ids = filterIds.stream().map(String::valueOf).collect(Collectors.joining(",")); + Filter defaultFilter = new Filter(UserFilter.class, Condition.IN, false, ids, CRITERIA_ID); + List userFilters = + filterRepository.findByFilter(ProjectFilter.of(defaultFilter, projectId), + Pageable.unpaged() + ).getContent(); + BusinessRule.expect(userFilters, not(List::isEmpty)) + .verify(ErrorType.USER_FILTER_NOT_FOUND, filterIds, projectId, username); + return userFilters; + } + return Collections.emptyList(); + } } diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/impl/GetWidgetHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/widget/impl/GetWidgetHandlerImpl.java index 28ed1ecbe3..85a308cd09 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/impl/GetWidgetHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/impl/GetWidgetHandlerImpl.java @@ -16,6 +16,11 @@ package com.epam.ta.reportportal.core.widget.impl; +import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; +import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; +import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.ATTRIBUTES; +import static java.util.Optional.ofNullable; + import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.querygen.ProjectFilter; @@ -30,13 +35,19 @@ import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.entity.widget.WidgetType; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.widget.WidgetPreviewRQ; +import com.epam.ta.reportportal.model.widget.WidgetResource; import com.epam.ta.reportportal.ws.converter.PagedResourcesAssembler; import com.epam.ta.reportportal.ws.converter.builders.WidgetBuilder; import com.epam.ta.reportportal.ws.converter.converters.WidgetConverter; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.widget.WidgetPreviewRQ; -import com.epam.ta.reportportal.ws.model.widget.WidgetResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Lists; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Predicate; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -45,199 +56,197 @@ import org.springframework.stereotype.Service; import org.springframework.util.MultiValueMap; -import java.util.*; -import java.util.function.Predicate; - -import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; -import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; -import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.ATTRIBUTES; -import static java.util.Optional.ofNullable; - /** * @author Pavel Bortnik */ @Service public class GetWidgetHandlerImpl implements GetWidgetHandler { - private Map buildFilterStrategyMapping; - - private Map loadContentStrategy; - - private Map multilevelLoadContentStrategy; - - private MaterializedLoadContentStrategy materializedLoadContentStrategy; - - private Set unfilteredWidgetTypes; - - @Autowired - private WidgetRepository widgetRepository; - - @Autowired - private GetUserFilterHandler getUserFilterHandler; - - @Autowired - @Qualifier("buildFilterStrategy") - public void setBuildFilterStrategy(Map buildFilterStrategyMapping) { - this.buildFilterStrategyMapping = buildFilterStrategyMapping; - } - - @Autowired - @Qualifier("contentLoader") - public void setLoadContentStrategy(Map loadContentStrategy) { - this.loadContentStrategy = loadContentStrategy; - } - - @Autowired - @Qualifier("multilevelContentLoader") - public void setMultilevelLoadContentStrategy(Map multilevelLoadContentStrategy) { - this.multilevelLoadContentStrategy = multilevelLoadContentStrategy; - } - - @Autowired - public void setMaterializedLoadContentStrategy(MaterializedLoadContentStrategy materializedLoadContentStrategy) { - this.materializedLoadContentStrategy = materializedLoadContentStrategy; - } - - @Autowired - @Qualifier("unfilteredWidgetTypes") - public void setUnfilteredWidgetTypes(Set unfilteredWidgetTypes) { - this.unfilteredWidgetTypes = unfilteredWidgetTypes; - } - - @Override - public WidgetResource getWidget(Long widgetId, ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { - Widget widget = widgetRepository.findByIdAndProjectId(widgetId, projectDetails.getProjectId()) - .orElseThrow(() -> new ReportPortalException(ErrorType.WIDGET_NOT_FOUND_IN_PROJECT, - widgetId, - projectDetails.getProjectName() - )); - - WidgetType widgetType = WidgetType.findByName(widget.getWidgetType()) - .orElseThrow(() -> new ReportPortalException(ErrorType.INCORRECT_REQUEST, - formattedSupplier("Unsupported widget type '{}'", widget.getWidgetType()) - )); - - expect(widgetType.isSupportMultilevelStructure(), Predicate.isEqual(false)).verify(ErrorType.INCORRECT_REQUEST, - formattedSupplier("Unsupported widget type '{}'", widgetType) - ); - - Map content; - - if (unfilteredWidgetTypes.contains(widgetType) || isFilteredContentLoadAllowed(widget.getFilters(), projectDetails, user)) { - content = loadContentStrategy.get(widgetType).loadContent(Lists.newArrayList(widget.getContentFields()), - buildFilterStrategyMapping.get(widgetType).buildFilter(widget), - widget.getWidgetOptions(), - widget.getItemsCount() - ); - } else { - content = Collections.emptyMap(); - } - - WidgetResource resource = WidgetConverter.TO_WIDGET_RESOURCE.apply(widget); - resource.setContent(content); - return resource; - } - - @Override - public WidgetResource getWidget(Long widgetId, String[] attributes, MultiValueMap params, - ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { - Widget widget = widgetRepository.findByIdAndProjectId(widgetId, projectDetails.getProjectId()) - .orElseThrow(() -> new ReportPortalException(ErrorType.WIDGET_NOT_FOUND_IN_PROJECT, - widgetId, - projectDetails.getProjectName() - )); - - WidgetType widgetType = WidgetType.findByName(widget.getWidgetType()) - .orElseThrow(() -> new ReportPortalException(ErrorType.INCORRECT_REQUEST, - formattedSupplier("Unsupported widget type '{}'", widget.getWidgetType()) - )); - - expect(widgetType.isSupportMultilevelStructure(), Predicate.isEqual(true)).verify(ErrorType.INCORRECT_REQUEST, - formattedSupplier("Widget type '{}' does not support multilevel structure.", widgetType) - ); - Map content; - - if (unfilteredWidgetTypes.contains(widgetType) || isFilteredContentLoadAllowed(widget.getFilters(), projectDetails, user)) { - params.put(ATTRIBUTES, Lists.newArrayList(attributes)); - content = ofNullable(multilevelLoadContentStrategy.get(widgetType)).map(strategy -> strategy.loadContent(Lists.newArrayList( - widget.getContentFields()), - buildFilterStrategyMapping.get(widgetType).buildFilter(widget), - widget.getWidgetOptions(), - attributes, - params, - widget.getItemsCount() - )).orElseGet(() -> materializedLoadContentStrategy.loadContent(widget, params)); - - } else { - content = Collections.emptyMap(); - } - - WidgetResource resource = WidgetConverter.TO_WIDGET_RESOURCE.apply(widget); - resource.setContent(content); - return resource; - } - - private Boolean isFilteredContentLoadAllowed(Collection userFilters, ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user) { - - if (CollectionUtils.isEmpty(userFilters)) { - return false; - } - - Long[] ids = userFilters.stream().map(UserFilter::getId).toArray(Long[]::new); - List permittedFilters = getPermittedFilters(ids, projectDetails, user); - return userFilters.size() == permittedFilters.size(); - - } - - @Override - public Map getWidgetPreview(WidgetPreviewRQ previewRQ, ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user) { - - WidgetType widgetType = WidgetType.findByName(previewRQ.getWidgetType()) - .orElseThrow(() -> new ReportPortalException(ErrorType.INCORRECT_REQUEST, - formattedSupplier("Unsupported widget type '{}'", previewRQ.getWidgetType()) - )); - - List userFilter = null; - if (CollectionUtils.isNotEmpty(previewRQ.getFilterIds())) { - userFilter = getPermittedFilters(previewRQ.getFilterIds().toArray(Long[]::new), projectDetails, user); - } - - if (!unfilteredWidgetTypes.contains(widgetType) && CollectionUtils.isEmpty(userFilter)) { - return Collections.emptyMap(); - } - - Widget widget = new WidgetBuilder().addWidgetPreviewRq(previewRQ) - .addProject(projectDetails.getProjectId()) - .addFilters(userFilter) - .get(); - - if (widgetType.isSupportMultilevelStructure()) { - return multilevelLoadContentStrategy.get(widgetType).loadContent(Lists.newArrayList(widget.getContentFields()), - buildFilterStrategyMapping.get(widgetType).buildFilter(widget), - widget.getWidgetOptions(), - null, - null, - widget.getItemsCount() - ); - } else { - return loadContentStrategy.get(widgetType).loadContent(Lists.newArrayList(widget.getContentFields()), - buildFilterStrategyMapping.get(widgetType).buildFilter(widget), - widget.getWidgetOptions(), - widget.getItemsCount() - ); - } - } - - List getPermittedFilters(Long[] ids, ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { - return getUserFilterHandler.getFiltersById(ids, projectDetails, user); - } - - @Override - public Iterable getOwnNames(ReportPortalUser.ProjectDetails projectDetails, Pageable pageable, Filter filter, - ReportPortalUser user) { - final Page widgets = widgetRepository.findByFilter(ProjectFilter.of(filter, projectDetails.getProjectId()), pageable); - return PagedResourcesAssembler.pageConverter().apply(widgets.map(Widget::getName)); - } + private Map buildFilterStrategyMapping; + + private Map loadContentStrategy; + + private Map multilevelLoadContentStrategy; + + private MaterializedLoadContentStrategy materializedLoadContentStrategy; + + private Set unfilteredWidgetTypes; + + @Autowired + private WidgetRepository widgetRepository; + + @Autowired + private GetUserFilterHandler getUserFilterHandler; + + @Autowired + @Qualifier("buildFilterStrategy") + public void setBuildFilterStrategy( + Map buildFilterStrategyMapping) { + this.buildFilterStrategyMapping = buildFilterStrategyMapping; + } + + @Autowired + @Qualifier("contentLoader") + public void setLoadContentStrategy(Map loadContentStrategy) { + this.loadContentStrategy = loadContentStrategy; + } + + @Autowired + @Qualifier("multilevelContentLoader") + public void setMultilevelLoadContentStrategy( + Map multilevelLoadContentStrategy) { + this.multilevelLoadContentStrategy = multilevelLoadContentStrategy; + } + + @Autowired + public void setMaterializedLoadContentStrategy( + MaterializedLoadContentStrategy materializedLoadContentStrategy) { + this.materializedLoadContentStrategy = materializedLoadContentStrategy; + } + + @Autowired + @Qualifier("unfilteredWidgetTypes") + public void setUnfilteredWidgetTypes(Set unfilteredWidgetTypes) { + this.unfilteredWidgetTypes = unfilteredWidgetTypes; + } + + @Override + public WidgetResource getWidget(Long widgetId, ReportPortalUser.ProjectDetails projectDetails, + ReportPortalUser user) { + Widget widget = widgetRepository.findByIdAndProjectId(widgetId, projectDetails.getProjectId()) + .orElseThrow( + () -> new ReportPortalException(ErrorType.WIDGET_NOT_FOUND_IN_PROJECT, widgetId, + projectDetails.getProjectName() + )); + + WidgetType widgetType = WidgetType.findByName(widget.getWidgetType()).orElseThrow( + () -> new ReportPortalException(ErrorType.INCORRECT_REQUEST, + formattedSupplier("Unsupported widget type '{}'", widget.getWidgetType()) + )); + + expect(widgetType.isSupportMultilevelStructure(), Predicate.isEqual(false)).verify( + ErrorType.INCORRECT_REQUEST, formattedSupplier("Unsupported widget type '{}'", widgetType)); + + Map content; + + if (unfilteredWidgetTypes.contains(widgetType) || isFilteredContentLoadAllowed( + widget.getFilters(), projectDetails, user)) { + content = loadContentStrategy.get(widgetType) + .loadContent(Lists.newArrayList(widget.getContentFields()), + buildFilterStrategyMapping.get(widgetType).buildFilter(widget), + widget.getWidgetOptions(), widget.getItemsCount() + ); + } else { + content = Collections.emptyMap(); + } + + WidgetResource resource = WidgetConverter.TO_WIDGET_RESOURCE.apply(widget); + resource.setContent(content); + return resource; + } + + @Override + public WidgetResource getWidget(Long widgetId, String[] attributes, + MultiValueMap params, ReportPortalUser.ProjectDetails projectDetails, + ReportPortalUser user) { + Widget widget = widgetRepository.findByIdAndProjectId(widgetId, projectDetails.getProjectId()) + .orElseThrow( + () -> new ReportPortalException(ErrorType.WIDGET_NOT_FOUND_IN_PROJECT, widgetId, + projectDetails.getProjectName() + )); + + WidgetType widgetType = WidgetType.findByName(widget.getWidgetType()).orElseThrow( + () -> new ReportPortalException(ErrorType.INCORRECT_REQUEST, + formattedSupplier("Unsupported widget type '{}'", widget.getWidgetType()) + )); + + expect(widgetType.isSupportMultilevelStructure(), Predicate.isEqual(true)).verify( + ErrorType.INCORRECT_REQUEST, + formattedSupplier("Widget type '{}' does not support multilevel structure.", widgetType) + ); + Map content; + + if (unfilteredWidgetTypes.contains(widgetType) || isFilteredContentLoadAllowed( + widget.getFilters(), projectDetails, user)) { + params.put(ATTRIBUTES, Lists.newArrayList(attributes)); + content = ofNullable(multilevelLoadContentStrategy.get(widgetType)).map( + strategy -> strategy.loadContent(Lists.newArrayList(widget.getContentFields()), + buildFilterStrategyMapping.get(widgetType).buildFilter(widget), + widget.getWidgetOptions(), attributes, params, widget.getItemsCount() + )).orElseGet(() -> materializedLoadContentStrategy.loadContent(widget, params)); + + } else { + content = Collections.emptyMap(); + } + + WidgetResource resource = WidgetConverter.TO_WIDGET_RESOURCE.apply(widget); + resource.setContent(content); + return resource; + } + + private Boolean isFilteredContentLoadAllowed(Collection userFilters, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { + + if (CollectionUtils.isEmpty(userFilters)) { + return false; + } + + Long[] ids = userFilters.stream().map(UserFilter::getId).toArray(Long[]::new); + List permittedFilters = getPermittedFilters(ids, projectDetails, user); + return userFilters.size() == permittedFilters.size(); + + } + + @Override + public Map getWidgetPreview(WidgetPreviewRQ previewRQ, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { + + WidgetType widgetType = WidgetType.findByName(previewRQ.getWidgetType()).orElseThrow( + () -> new ReportPortalException(ErrorType.INCORRECT_REQUEST, + formattedSupplier("Unsupported widget type '{}'", previewRQ.getWidgetType()) + )); + + List userFilter = null; + if (CollectionUtils.isNotEmpty(previewRQ.getFilterIds())) { + userFilter = + getPermittedFilters(previewRQ.getFilterIds().toArray(Long[]::new), projectDetails, user); + } + + if (!unfilteredWidgetTypes.contains(widgetType) && CollectionUtils.isEmpty(userFilter)) { + return Collections.emptyMap(); + } + + Widget widget = + new WidgetBuilder().addWidgetPreviewRq(previewRQ).addProject(projectDetails.getProjectId()) + .addFilters(userFilter).get(); + + if (widgetType.isSupportMultilevelStructure()) { + return multilevelLoadContentStrategy.get(widgetType) + .loadContent(Lists.newArrayList(widget.getContentFields()), + buildFilterStrategyMapping.get(widgetType).buildFilter(widget), + widget.getWidgetOptions(), null, null, widget.getItemsCount() + ); + } else { + return loadContentStrategy.get(widgetType) + .loadContent(Lists.newArrayList(widget.getContentFields()), + buildFilterStrategyMapping.get(widgetType).buildFilter(widget), + widget.getWidgetOptions(), widget.getItemsCount() + ); + } + } + + List getPermittedFilters(Long[] ids, ReportPortalUser.ProjectDetails projectDetails, + ReportPortalUser user) { + return getUserFilterHandler.getFiltersById(ids, projectDetails, user); + } + + @Override + public Iterable getOwnNames(ReportPortalUser.ProjectDetails projectDetails, + Pageable pageable, Filter filter, ReportPortalUser user) { + final Page widgets = + widgetRepository.findByFilter(ProjectFilter.of(filter, projectDetails.getProjectId()), + pageable + ); + return PagedResourcesAssembler.pageConverter().apply(widgets.map(Widget::getName)); + } } \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/impl/UpdateWidgetHandlerImpl.java b/src/main/java/com/epam/ta/reportportal/core/widget/impl/UpdateWidgetHandlerImpl.java index c14f34e8eb..a4af63bb70 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/impl/UpdateWidgetHandlerImpl.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/impl/UpdateWidgetHandlerImpl.java @@ -16,6 +16,9 @@ package com.epam.ta.reportportal.core.widget.impl; +import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_ID; +import static com.epam.ta.reportportal.ws.converter.converters.WidgetConverter.TO_ACTIVITY_RESOURCE; + import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Condition; import com.epam.ta.reportportal.commons.querygen.Filter; @@ -31,105 +34,97 @@ import com.epam.ta.reportportal.entity.filter.UserFilter; import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.activity.WidgetActivityResource; +import com.epam.ta.reportportal.model.widget.WidgetRQ; import com.epam.ta.reportportal.ws.converter.builders.WidgetBuilder; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.activity.WidgetActivityResource; -import com.epam.ta.reportportal.ws.model.widget.WidgetRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.BooleanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_ID; -import static com.epam.ta.reportportal.ws.converter.converters.WidgetConverter.TO_ACTIVITY_RESOURCE; - /** * @author Pavel Bortnik */ @Service public class UpdateWidgetHandlerImpl implements UpdateWidgetHandler { - private final WidgetRepository widgetRepository; - private final UserFilterRepository filterRepository; - private final MessageBus messageBus; - private final ObjectMapper objectMapper; - private final WidgetValidator widgetContentFieldsValidator; - - @Autowired - public UpdateWidgetHandlerImpl(WidgetRepository widgetRepository, UserFilterRepository filterRepository, MessageBus messageBus, - ObjectMapper objectMapper, WidgetValidator widgetContentFieldsValidator) { - this.widgetRepository = widgetRepository; - this.filterRepository = filterRepository; - this.messageBus = messageBus; - this.objectMapper = objectMapper; - this.widgetContentFieldsValidator = widgetContentFieldsValidator; - } - - @Override - public OperationCompletionRS updateWidget(Long widgetId, WidgetRQ updateRQ, ReportPortalUser.ProjectDetails projectDetails, - ReportPortalUser user) { - Widget widget = widgetRepository.findByIdAndProjectId(widgetId, projectDetails.getProjectId()) - .orElseThrow(() -> new ReportPortalException(ErrorType.WIDGET_NOT_FOUND_IN_PROJECT, - widgetId, - projectDetails.getProjectName() - )); - - widgetContentFieldsValidator.validate(widget); - - if (!widget.getName().equals(updateRQ.getName())) { - BusinessRule.expect(widgetRepository.existsByNameAndOwnerAndProjectId(updateRQ.getName(), - user.getUsername(), - projectDetails.getProjectId() - ), BooleanUtils::isFalse) - .verify(ErrorType.RESOURCE_ALREADY_EXISTS, updateRQ.getName()); - } - - WidgetActivityResource before = TO_ACTIVITY_RESOURCE.apply(widget); - - List userFilter = getUserFilters(updateRQ.getFilterIds(), projectDetails.getProjectId()); - String widgetOptionsBefore = parseWidgetOptions(widget); - - widget = new WidgetBuilder(widget).addWidgetRq(updateRQ).addFilters(userFilter).get(); - widgetRepository.save(widget); - - messageBus.publishActivity(new WidgetUpdatedEvent(before, - TO_ACTIVITY_RESOURCE.apply(widget), - widgetOptionsBefore, - parseWidgetOptions(widget), - user.getUserId(), - user.getUsername() - )); - return new OperationCompletionRS("Widget with ID = '" + widget.getId() + "' successfully updated."); - } - - private List getUserFilters(List filterIds, Long projectId) { - if (CollectionUtils.isNotEmpty(filterIds)) { - Filter defaultFilter = new Filter(UserFilter.class, - Condition.IN, - false, - filterIds.stream().map(String::valueOf).collect(Collectors.joining(",")), - CRITERIA_ID - ); - return filterRepository.findByFilter(ProjectFilter.of(defaultFilter, projectId), Pageable.unpaged()).getContent(); - } - return Collections.emptyList(); - } - - private String parseWidgetOptions(Widget widget) { - try { - return objectMapper.writeValueAsString(widget.getWidgetOptions()); - } catch (JsonProcessingException e) { - throw new ReportPortalException(ErrorType.INCORRECT_REQUEST, - Suppliers.formattedSupplier("Error during parsing new widget options of widget with id = ", widget.getId()) - ); - } - } + private final WidgetRepository widgetRepository; + private final UserFilterRepository filterRepository; + private final MessageBus messageBus; + private final ObjectMapper objectMapper; + private final WidgetValidator widgetContentFieldsValidator; + + @Autowired + public UpdateWidgetHandlerImpl(WidgetRepository widgetRepository, + UserFilterRepository filterRepository, MessageBus messageBus, ObjectMapper objectMapper, + WidgetValidator widgetContentFieldsValidator) { + this.widgetRepository = widgetRepository; + this.filterRepository = filterRepository; + this.messageBus = messageBus; + this.objectMapper = objectMapper; + this.widgetContentFieldsValidator = widgetContentFieldsValidator; + } + + @Override + public OperationCompletionRS updateWidget(Long widgetId, WidgetRQ updateRQ, + ReportPortalUser.ProjectDetails projectDetails, ReportPortalUser user) { + Widget widget = widgetRepository.findByIdAndProjectId(widgetId, projectDetails.getProjectId()) + .orElseThrow( + () -> new ReportPortalException(ErrorType.WIDGET_NOT_FOUND_IN_PROJECT, widgetId, + projectDetails.getProjectName() + )); + + widgetContentFieldsValidator.validate(widget); + + if (!widget.getName().equals(updateRQ.getName())) { + BusinessRule.expect( + widgetRepository.existsByNameAndOwnerAndProjectId(updateRQ.getName(), user.getUsername(), + projectDetails.getProjectId() + ), BooleanUtils::isFalse).verify(ErrorType.RESOURCE_ALREADY_EXISTS, updateRQ.getName()); + } + + WidgetActivityResource before = TO_ACTIVITY_RESOURCE.apply(widget); + + List userFilter = + getUserFilters(updateRQ.getFilterIds(), projectDetails.getProjectId()); + String widgetOptionsBefore = parseWidgetOptions(widget); + + widget = new WidgetBuilder(widget).addWidgetRq(updateRQ).addFilters(userFilter).get(); + widgetRepository.save(widget); + + messageBus.publishActivity( + new WidgetUpdatedEvent(before, TO_ACTIVITY_RESOURCE.apply(widget), widgetOptionsBefore, + parseWidgetOptions(widget), user.getUserId(), user.getUsername() + )); + return new OperationCompletionRS( + "Widget with ID = '" + widget.getId() + "' successfully updated."); + } + + private List getUserFilters(List filterIds, Long projectId) { + if (CollectionUtils.isNotEmpty(filterIds)) { + Filter defaultFilter = new Filter(UserFilter.class, Condition.IN, false, + filterIds.stream().map(String::valueOf).collect(Collectors.joining(",")), CRITERIA_ID + ); + return filterRepository.findByFilter( + ProjectFilter.of(defaultFilter, projectId), Pageable.unpaged()).getContent(); + } + return Collections.emptyList(); + } + + private String parseWidgetOptions(Widget widget) { + try { + return objectMapper.writeValueAsString(widget.getWidgetOptions()); + } catch (JsonProcessingException e) { + throw new ReportPortalException(ErrorType.INCORRECT_REQUEST, Suppliers.formattedSupplier( + "Error during parsing new widget options of widget with id = ", widget.getId())); + } + } } diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/util/WidgetFilterUtil.java b/src/main/java/com/epam/ta/reportportal/core/widget/util/WidgetFilterUtil.java index 370bf584c2..3bd1babfbf 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/util/WidgetFilterUtil.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/util/WidgetFilterUtil.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.collect.Lists; import java.util.Collection; import java.util.Set; diff --git a/src/main/java/com/epam/ta/reportportal/core/widget/util/WidgetOptionUtil.java b/src/main/java/com/epam/ta/reportportal/core/widget/util/WidgetOptionUtil.java index 39a035942d..a2d0306ce6 100644 --- a/src/main/java/com/epam/ta/reportportal/core/widget/util/WidgetOptionUtil.java +++ b/src/main/java/com/epam/ta/reportportal/core/widget/util/WidgetOptionUtil.java @@ -22,7 +22,7 @@ import com.epam.ta.reportportal.commons.validation.Suppliers; import com.epam.ta.reportportal.entity.widget.WidgetOptions; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Collections; import java.util.List; import java.util.Map; @@ -75,6 +75,16 @@ public static boolean getBooleanByKey(String key, WidgetOptions widgetOptions) { .orElse(false); } + public static boolean isBooleanPresent(String key, WidgetOptions widgetOptions) { + return ofNullable(widgetOptions) + .map(wo -> MapUtils.isNotEmpty(wo.getOptions()) && + ofNullable(wo.getOptions().get(key)) + .map(String::valueOf) + .map(BooleanUtils::toBooleanObject) + .isPresent()) + .orElse(false); + } + public static Optional getIntegerByKey(String key, WidgetOptions widgetOptions) { return ofNullable(widgetOptions).flatMap( wo -> ofNullable(wo.getOptions()).map(options -> options.get(key))).map(value -> { diff --git a/src/main/java/com/epam/ta/reportportal/demodata/DemoDataController.java b/src/main/java/com/epam/ta/reportportal/demodata/DemoDataController.java index 123cdfa3f1..437e0a86f6 100644 --- a/src/main/java/com/epam/ta/reportportal/demodata/DemoDataController.java +++ b/src/main/java/com/epam/ta/reportportal/demodata/DemoDataController.java @@ -21,7 +21,8 @@ import com.epam.ta.reportportal.demodata.model.DemoDataRs; import com.epam.ta.reportportal.demodata.service.DemoDataService; import com.epam.ta.reportportal.util.ProjectExtractor; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.validation.annotation.Validated; @@ -35,6 +36,7 @@ @RestController @RequestMapping("/v1/demo/{projectName}") @PreAuthorize(PROJECT_MANAGER) +@Tag(name = "demo-data-controller", description = "Demo Data Controller") class DemoDataController { private final DemoDataService demoDataService; @@ -47,7 +49,7 @@ class DemoDataController { } @PostMapping("/generate") - @ApiOperation(value = "generate") + @Operation(summary = "generate") public DemoDataRs generate(@PathVariable String projectName, @Validated @RequestBody DemoDataRq demoDataRq, @AuthenticationPrincipal ReportPortalUser user) { return demoDataService.generate(demoDataRq, projectExtractor.extractProjectDetailsAdmin(user, projectName), user); diff --git a/src/main/java/com/epam/ta/reportportal/demodata/service/ContentUtils.java b/src/main/java/com/epam/ta/reportportal/demodata/service/ContentUtils.java index ddf95cfb71..7f37bf1785 100644 --- a/src/main/java/com/epam/ta/reportportal/demodata/service/ContentUtils.java +++ b/src/main/java/com/epam/ta/reportportal/demodata/service/ContentUtils.java @@ -25,8 +25,8 @@ import com.epam.ta.reportportal.entity.enums.TestItemIssueGroup; import com.epam.ta.reportportal.entity.enums.TestItemTypeEnum; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributesRQ; -import com.epam.ta.reportportal.ws.model.issue.Issue; +import com.epam.ta.reportportal.ws.reporting.Issue; +import com.epam.ta.reportportal.ws.reporting.ItemAttributesRQ; import com.google.common.base.CaseFormat; import com.google.common.base.Preconditions; import com.google.common.collect.Range; diff --git a/src/main/java/com/epam/ta/reportportal/demodata/service/DefaultDemoDataFacade.java b/src/main/java/com/epam/ta/reportportal/demodata/service/DefaultDemoDataFacade.java index cc147439b8..84261990ca 100644 --- a/src/main/java/com/epam/ta/reportportal/demodata/service/DefaultDemoDataFacade.java +++ b/src/main/java/com/epam/ta/reportportal/demodata/service/DefaultDemoDataFacade.java @@ -30,7 +30,7 @@ import com.epam.ta.reportportal.entity.log.Log; import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; diff --git a/src/main/java/com/epam/ta/reportportal/demodata/service/DemoDashboardsService.java b/src/main/java/com/epam/ta/reportportal/demodata/service/DemoDashboardsService.java index ac1ad9a2ae..05107b27d5 100644 --- a/src/main/java/com/epam/ta/reportportal/demodata/service/DemoDashboardsService.java +++ b/src/main/java/com/epam/ta/reportportal/demodata/service/DemoDashboardsService.java @@ -16,12 +16,21 @@ package com.epam.ta.reportportal.demodata.service; +import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_NAME; +import static com.epam.ta.reportportal.commons.querygen.constant.ItemAttributeConstant.CRITERIA_COMPOSITE_ATTRIBUTE; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.PROJECT_NOT_FOUND; +import static java.util.stream.Collectors.toList; + import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Condition; import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.querygen.FilterCondition; import com.epam.ta.reportportal.commons.querygen.ProjectFilter; -import com.epam.ta.reportportal.dao.*; +import com.epam.ta.reportportal.dao.DashboardRepository; +import com.epam.ta.reportportal.dao.DashboardWidgetRepository; +import com.epam.ta.reportportal.dao.ProjectRepository; +import com.epam.ta.reportportal.dao.UserFilterRepository; +import com.epam.ta.reportportal.dao.WidgetRepository; import com.epam.ta.reportportal.entity.dashboard.Dashboard; import com.epam.ta.reportportal.entity.dashboard.DashboardWidget; import com.epam.ta.reportportal.entity.dashboard.DashboardWidgetId; @@ -32,12 +41,16 @@ import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.entity.widget.WidgetType; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.widget.WidgetRQ; import com.epam.ta.reportportal.ws.converter.builders.WidgetBuilder; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.widget.WidgetRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Sets; +import java.io.IOException; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; @@ -46,169 +59,173 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.io.IOException; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Optional; - -import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_NAME; -import static com.epam.ta.reportportal.commons.querygen.constant.ItemAttributeConstant.CRITERIA_COMPOSITE_ATTRIBUTE; -import static com.epam.ta.reportportal.ws.model.ErrorType.PROJECT_NOT_FOUND; -import static java.util.stream.Collectors.toList; - @Service class DemoDashboardsService { - private static final String DASHBOARD_NAME = "DEMO DASHBOARD"; - private static final String FILTER_NAME = "DEMO_FILTER"; - private static final String START_TIME_SORTING = "startTime"; - private static final boolean SHARED = true; - - private final UserFilterRepository userFilterRepository; - - private final DashboardRepository dashboardRepository; - - private final DashboardWidgetRepository dashboardWidgetRepository; - - private final WidgetRepository widgetRepository; - - private final ProjectRepository projectRepository; - - private final ObjectMapper objectMapper; - - private Resource resource; - - @Autowired - public DemoDashboardsService(UserFilterRepository userFilterRepository, DashboardRepository dashboardRepository, - DashboardWidgetRepository dashboardWidgetRepository, WidgetRepository widgetRepository, ProjectRepository projectRepository, - ObjectMapper objectMapper) { - this.userFilterRepository = userFilterRepository; - this.dashboardRepository = dashboardRepository; - this.dashboardWidgetRepository = dashboardWidgetRepository; - this.widgetRepository = widgetRepository; - this.projectRepository = projectRepository; - this.objectMapper = objectMapper; - } - - @Value("classpath:demo/demo_widgets.json") - public void setResource(Resource resource) { - this.resource = resource; - } - - @Transactional - public Optional generate(ReportPortalUser user, Long projectId) { - Project project = projectRepository.findById(projectId).orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, projectId)); - - if (dashboardRepository.existsByNameAndOwnerAndProjectId(DASHBOARD_NAME, user.getUsername(), projectId)) { - return Optional.empty(); - } - - UserFilter filter = createDemoFilter(user, project); - List widgets = createWidgets(user, projectId, filter); - return Optional.of(createDemoDashboard(widgets, user, project, DASHBOARD_NAME)); - } - - private List createWidgets(ReportPortalUser user, Long projectId, UserFilter filter) { - try { - TypeReference> type = new TypeReference<>() { - }; - - List widgets = objectMapper.readValue(resource.getURL(), type).stream().map(it -> { - final WidgetBuilder widgetBuilder = new WidgetBuilder().addWidgetRq(it).addProject(projectId).addOwner(user.getUsername()); - final WidgetType widgetType = WidgetType.findByName(it.getWidgetType()) - .orElseThrow(() -> new ReportPortalException(ErrorType.UNABLE_TO_CREATE_WIDGET, - "Widget type '" + it.getWidgetType() + "' does not exists" - )); - if (!WidgetType.FLAKY_TEST_CASES.equals(widgetType) || !WidgetType.TOP_TEST_CASES.equals(widgetType)) { - widgetBuilder.addFilters(Sets.newHashSet(filter)); - } - return widgetBuilder.get(); - }).collect(toList()); - widgetRepository.saveAll(widgets); - return widgets; - } catch (IOException e) { - throw new ReportPortalException("Unable to load demo_widgets.json. " + e.getMessage(), e); - } - } - - private UserFilter createDemoFilter(ReportPortalUser user, Project project) { - List existedFilterList = userFilterRepository.findByFilter(ProjectFilter.of(Filter.builder() - .withTarget(UserFilter.class) - .withCondition(FilterCondition.builder() - .withCondition(Condition.EQUALS) - .withSearchCriteria(CRITERIA_NAME) - .withValue(FILTER_NAME) - .build()) - .build(), project.getId()), Pageable.unpaged()).getContent(); - - if (!existedFilterList.isEmpty()) { - return existedFilterList.get(0); - } - - UserFilter userFilter = new UserFilter(); - userFilter.setName(FILTER_NAME); - userFilter.setTargetClass(ObjectType.Launch); - userFilter.setProject(project); - userFilter.setFilterCondition(Sets.newHashSet(FilterCondition.builder() - .withSearchCriteria(CRITERIA_COMPOSITE_ATTRIBUTE) - .withCondition(Condition.HAS) - .withValue("demo") - .build())); - - FilterSort filterSort = new FilterSort(); - filterSort.setDirection(Sort.Direction.DESC); - filterSort.setField(START_TIME_SORTING); - userFilter.setFilterSorts(Sets.newHashSet(filterSort)); - - userFilter.setOwner(user.getUsername()); - - userFilterRepository.save(userFilter); - - return userFilter; - } - - private Dashboard createDemoDashboard(List widgets, ReportPortalUser user, Project project, String name) { - Dashboard dashboard = new Dashboard(); - dashboard.setName(name); - dashboard.setProject(project); - dashboard.setCreationDate(LocalDateTime.now()); - dashboard.setOwner(user.getUsername()); - - dashboardRepository.save(dashboard); - - dashboard.addWidget(createDashboardWidget(user.getUsername(), dashboard, widgets.get(0), 0, 0, 6, 5)); - dashboard.addWidget(createDashboardWidget(user.getUsername(), dashboard, widgets.get(1), 6, 0, 6, 5)); - dashboard.addWidget(createDashboardWidget(user.getUsername(), dashboard, widgets.get(2), 0, 5, 7, 5)); - dashboard.addWidget(createDashboardWidget(user.getUsername(), dashboard, widgets.get(3), 7, 5, 5, 5)); - dashboard.addWidget(createDashboardWidget(user.getUsername(), dashboard, widgets.get(4), 0, 10, 5, 5)); - dashboard.addWidget(createDashboardWidget(user.getUsername(), dashboard, widgets.get(5), 5, 10, 7, 5)); - dashboard.addWidget(createDashboardWidget(user.getUsername(), dashboard, widgets.get(6), 0, 15, 6, 5)); - dashboard.addWidget(createDashboardWidget(user.getUsername(), dashboard, widgets.get(7), 6, 15, 6, 5)); - dashboard.addWidget(createDashboardWidget(user.getUsername(), dashboard, widgets.get(8), 0, 20, 12, 4)); - dashboard.addWidget(createDashboardWidget(user.getUsername(), dashboard, widgets.get(9), 0, 24, 7, 5)); - dashboard.addWidget(createDashboardWidget(user.getUsername(), dashboard, widgets.get(10), 7, 24, 5, 5)); - dashboard.addWidget(createDashboardWidget(user.getUsername(), dashboard, widgets.get(11), 0, 29, 12, 4)); - - return dashboard; - } - - private DashboardWidget createDashboardWidget(String owner, Dashboard dashboard, Widget widget, int posX, int posY, int width, - int height) { - DashboardWidget dashboardWidget = new DashboardWidget(); - dashboardWidget.setId(new DashboardWidgetId(dashboard.getId(), widget.getId())); - - dashboardWidget.setDashboard(dashboard); - dashboardWidget.setWidget(widget); - dashboardWidget.setWidgetName(widget.getName()); - dashboardWidget.setWidgetType(widget.getWidgetType()); - dashboardWidget.setCreatedOn(true); - dashboardWidget.setWidgetOwner(owner); - dashboardWidget.setHeight(height); - dashboardWidget.setWidth(width); - dashboardWidget.setPositionX(posX); - dashboardWidget.setPositionY(posY); - - dashboardWidgetRepository.save(dashboardWidget); - return dashboardWidget; - } + private static final String DASHBOARD_NAME = "DEMO DASHBOARD"; + private static final String FILTER_NAME = "DEMO_FILTER"; + private static final String START_TIME_SORTING = "startTime"; + private static final boolean SHARED = true; + + private final UserFilterRepository userFilterRepository; + + private final DashboardRepository dashboardRepository; + + private final DashboardWidgetRepository dashboardWidgetRepository; + + private final WidgetRepository widgetRepository; + + private final ProjectRepository projectRepository; + + private final ObjectMapper objectMapper; + + private Resource resource; + + @Autowired + public DemoDashboardsService(UserFilterRepository userFilterRepository, + DashboardRepository dashboardRepository, DashboardWidgetRepository dashboardWidgetRepository, + WidgetRepository widgetRepository, ProjectRepository projectRepository, + ObjectMapper objectMapper) { + this.userFilterRepository = userFilterRepository; + this.dashboardRepository = dashboardRepository; + this.dashboardWidgetRepository = dashboardWidgetRepository; + this.widgetRepository = widgetRepository; + this.projectRepository = projectRepository; + this.objectMapper = objectMapper; + } + + @Value("classpath:demo/demo_widgets.json") + public void setResource(Resource resource) { + this.resource = resource; + } + + @Transactional + public Optional generate(ReportPortalUser user, Long projectId) { + Project project = projectRepository.findById(projectId) + .orElseThrow(() -> new ReportPortalException(PROJECT_NOT_FOUND, projectId)); + + if (dashboardRepository.existsByNameAndOwnerAndProjectId( + DASHBOARD_NAME, user.getUsername(), projectId)) { + return Optional.empty(); + } + + UserFilter filter = createDemoFilter(user, project); + List widgets = createWidgets(user, projectId, filter); + return Optional.of(createDemoDashboard(widgets, user, project, DASHBOARD_NAME)); + } + + private List createWidgets(ReportPortalUser user, Long projectId, UserFilter filter) { + try { + TypeReference> type = new TypeReference<>() { + }; + + List widgets = objectMapper.readValue(resource.getURL(), type).stream().map(it -> { + final WidgetBuilder widgetBuilder = + new WidgetBuilder().addWidgetRq(it).addProject(projectId).addOwner(user.getUsername()); + final WidgetType widgetType = WidgetType.findByName(it.getWidgetType()).orElseThrow( + () -> new ReportPortalException(ErrorType.UNABLE_TO_CREATE_WIDGET, + "Widget type '" + it.getWidgetType() + "' does not exists" + )); + if (!WidgetType.FLAKY_TEST_CASES.equals(widgetType) || !WidgetType.TOP_TEST_CASES.equals( + widgetType)) { + widgetBuilder.addFilters(Sets.newHashSet(filter)); + } + return widgetBuilder.get(); + }).collect(toList()); + widgetRepository.saveAll(widgets); + return widgets; + } catch (IOException e) { + throw new ReportPortalException("Unable to load demo_widgets.json. " + e.getMessage(), e); + } + } + + private UserFilter createDemoFilter(ReportPortalUser user, Project project) { + List existedFilterList = userFilterRepository.findByFilter(ProjectFilter.of( + Filter.builder().withTarget(UserFilter.class).withCondition( + FilterCondition.builder().withCondition(Condition.EQUALS) + .withSearchCriteria(CRITERIA_NAME).withValue(FILTER_NAME).build()).build(), + project.getId() + ), Pageable.unpaged()).getContent(); + + if (!existedFilterList.isEmpty()) { + return existedFilterList.get(0); + } + + UserFilter userFilter = new UserFilter(); + userFilter.setName(FILTER_NAME); + userFilter.setTargetClass(ObjectType.Launch); + userFilter.setProject(project); + userFilter.setFilterCondition(Sets.newHashSet( + FilterCondition.builder().withSearchCriteria(CRITERIA_COMPOSITE_ATTRIBUTE) + .withCondition(Condition.HAS).withValue("demo").build())); + + FilterSort filterSort = new FilterSort(); + filterSort.setDirection(Sort.Direction.DESC); + filterSort.setField(START_TIME_SORTING); + userFilter.setFilterSorts(Sets.newHashSet(filterSort)); + + userFilter.setOwner(user.getUsername()); + + userFilterRepository.save(userFilter); + + return userFilter; + } + + private Dashboard createDemoDashboard(List widgets, ReportPortalUser user, + Project project, String name) { + Dashboard dashboard = new Dashboard(); + dashboard.setName(name); + dashboard.setProject(project); + dashboard.setCreationDate(LocalDateTime.now()); + dashboard.setOwner(user.getUsername()); + + dashboardRepository.save(dashboard); + + dashboard.addWidget( + createDashboardWidget(user.getUsername(), dashboard, widgets.get(0), 0, 0, 6, 5)); + dashboard.addWidget( + createDashboardWidget(user.getUsername(), dashboard, widgets.get(1), 6, 0, 6, 5)); + dashboard.addWidget( + createDashboardWidget(user.getUsername(), dashboard, widgets.get(2), 0, 5, 7, 5)); + dashboard.addWidget( + createDashboardWidget(user.getUsername(), dashboard, widgets.get(3), 7, 5, 5, 5)); + dashboard.addWidget( + createDashboardWidget(user.getUsername(), dashboard, widgets.get(4), 0, 10, 5, 5)); + dashboard.addWidget( + createDashboardWidget(user.getUsername(), dashboard, widgets.get(5), 5, 10, 7, 5)); + dashboard.addWidget( + createDashboardWidget(user.getUsername(), dashboard, widgets.get(6), 0, 15, 6, 5)); + dashboard.addWidget( + createDashboardWidget(user.getUsername(), dashboard, widgets.get(7), 6, 15, 6, 5)); + dashboard.addWidget( + createDashboardWidget(user.getUsername(), dashboard, widgets.get(8), 0, 20, 12, 4)); + dashboard.addWidget( + createDashboardWidget(user.getUsername(), dashboard, widgets.get(9), 0, 24, 7, 5)); + dashboard.addWidget( + createDashboardWidget(user.getUsername(), dashboard, widgets.get(10), 7, 24, 5, 5)); + dashboard.addWidget( + createDashboardWidget(user.getUsername(), dashboard, widgets.get(11), 0, 29, 12, 4)); + + return dashboard; + } + + private DashboardWidget createDashboardWidget(String owner, Dashboard dashboard, Widget widget, + int posX, int posY, int width, int height) { + DashboardWidget dashboardWidget = new DashboardWidget(); + dashboardWidget.setId(new DashboardWidgetId(dashboard.getId(), widget.getId())); + + dashboardWidget.setDashboard(dashboard); + dashboardWidget.setWidget(widget); + dashboardWidget.setWidgetName(widget.getName()); + dashboardWidget.setWidgetType(widget.getWidgetType()); + dashboardWidget.setCreatedOn(true); + dashboardWidget.setWidgetOwner(owner); + dashboardWidget.setHeight(height); + dashboardWidget.setWidth(width); + dashboardWidget.setPositionX(posX); + dashboardWidget.setPositionY(posY); + + dashboardWidgetRepository.save(dashboardWidget); + return dashboardWidget; + } } \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/demodata/service/DemoDataLaunchService.java b/src/main/java/com/epam/ta/reportportal/demodata/service/DemoDataLaunchService.java index 9f6fdf2ebb..d2864bba36 100644 --- a/src/main/java/com/epam/ta/reportportal/demodata/service/DemoDataLaunchService.java +++ b/src/main/java/com/epam/ta/reportportal/demodata/service/DemoDataLaunchService.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.demodata.service; import static com.epam.ta.reportportal.entity.enums.StatusEnum.PASSED; -import static com.epam.ta.reportportal.ws.model.ErrorType.LAUNCH_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.LAUNCH_NOT_FOUND; import com.epam.reportportal.extension.event.LaunchFinishedPluginEvent; import com.epam.ta.reportportal.commons.ReportPortalUser; @@ -28,9 +28,9 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.converter.builders.LaunchBuilder; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributesRQ; -import com.epam.ta.reportportal.ws.model.launch.Mode; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.ItemAttributesRQ; +import com.epam.ta.reportportal.ws.reporting.Mode; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; import com.google.common.collect.Sets; import java.time.LocalDateTime; import java.time.ZoneId; diff --git a/src/main/java/com/epam/ta/reportportal/demodata/service/DemoDataTestItemService.java b/src/main/java/com/epam/ta/reportportal/demodata/service/DemoDataTestItemService.java index 8d41ab3fde..76669c81ab 100644 --- a/src/main/java/com/epam/ta/reportportal/demodata/service/DemoDataTestItemService.java +++ b/src/main/java/com/epam/ta/reportportal/demodata/service/DemoDataTestItemService.java @@ -29,8 +29,8 @@ import com.epam.ta.reportportal.entity.enums.StatusEnum; import com.epam.ta.reportportal.entity.enums.TestItemIssueGroup; import com.epam.ta.reportportal.entity.enums.TestItemTypeEnum; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/demodata/service/DemoLogsService.java b/src/main/java/com/epam/ta/reportportal/demodata/service/DemoLogsService.java index ce21a02fb7..6a5c5f23fc 100644 --- a/src/main/java/com/epam/ta/reportportal/demodata/service/DemoLogsService.java +++ b/src/main/java/com/epam/ta/reportportal/demodata/service/DemoLogsService.java @@ -16,6 +16,18 @@ package com.epam.ta.reportportal.demodata.service; +import static com.epam.ta.reportportal.entity.enums.LogLevel.DEBUG; +import static com.epam.ta.reportportal.entity.enums.LogLevel.ERROR; +import static com.epam.ta.reportportal.entity.enums.LogLevel.FATAL; +import static com.epam.ta.reportportal.entity.enums.LogLevel.INFO; +import static com.epam.ta.reportportal.entity.enums.LogLevel.TRACE; +import static com.epam.ta.reportportal.entity.enums.LogLevel.WARN; +import static com.epam.ta.reportportal.entity.enums.StatusEnum.FAILED; +import static com.epam.ta.reportportal.util.MultipartFileUtils.getMultipartFile; +import static com.epam.ta.reportportal.ws.converter.converters.LogConverter.LOG_FULL_TO_LOG; +import static java.util.stream.Collectors.toList; +import static org.apache.commons.collections4.CollectionUtils.isNotEmpty; + import com.epam.ta.reportportal.binary.AttachmentBinaryDataService; import com.epam.ta.reportportal.core.log.LogService; import com.epam.ta.reportportal.dao.LaunchRepository; @@ -29,26 +41,18 @@ import com.epam.ta.reportportal.entity.log.Log; import com.epam.ta.reportportal.entity.log.LogFull; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import java.util.HashMap; -import java.util.Map; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.io.IOException; import java.time.LocalDateTime; import java.time.ZoneOffset; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.SplittableRandom; import java.util.UUID; import java.util.stream.IntStream; - -import static com.epam.ta.reportportal.entity.enums.LogLevel.*; -import static com.epam.ta.reportportal.entity.enums.StatusEnum.FAILED; -import static com.epam.ta.reportportal.util.MultipartFileUtils.getMultipartFile; -import static com.epam.ta.reportportal.ws.converter.converters.LogConverter.LOG_FULL_TO_LOG; -import static java.util.stream.Collectors.toList; -import static org.apache.commons.collections4.CollectionUtils.isNotEmpty; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; @Service public class DemoLogsService { diff --git a/src/main/java/com/epam/ta/reportportal/job/FlushingDataJob.java b/src/main/java/com/epam/ta/reportportal/job/FlushingDataJob.java index 7ab883321b..a70f813db2 100644 --- a/src/main/java/com/epam/ta/reportportal/job/FlushingDataJob.java +++ b/src/main/java/com/epam/ta/reportportal/job/FlushingDataJob.java @@ -29,10 +29,10 @@ import com.epam.ta.reportportal.entity.project.ProjectIssueType; import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; +import com.epam.ta.reportportal.model.user.CreateUserRQFull; import com.epam.ta.reportportal.util.FeatureFlagHandler; import com.epam.ta.reportportal.util.PersonalProjectService; import com.epam.ta.reportportal.ws.converter.builders.UserBuilder; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQFull; import java.util.Set; import java.util.stream.Collectors; import org.jclouds.blobstore.BlobStore; @@ -47,7 +47,6 @@ import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; - /** * @author Pavel Bortnik */ @@ -107,12 +106,10 @@ public class FlushingDataJob implements Job { public void execute(JobExecutionContext context) { LOGGER.info("Flushing demo instance data is starting..."); truncateTables(); - projectRepository.findAllProjectNames() - .stream() - .filter(it -> !it.equalsIgnoreCase(SUPERADMIN_PERSONAL)) - .collect(Collectors.toList()) + projectRepository.findAllProjectNames().stream() + .filter(it -> !it.equalsIgnoreCase(SUPERADMIN_PERSONAL)).collect(Collectors.toList()) .forEach(name -> projectRepository.findByName(name).ifPresent(this::deleteProject)); - if (featureFlagHandler.isEnabled(FeatureFlag.SINGLE_BUCKET)){ + if (featureFlagHandler.isEnabled(FeatureFlag.SINGLE_BUCKET)) { try { blobStore.deleteContainer(defaultBucketName); } catch (Exception e) { @@ -130,8 +127,7 @@ public void execute(JobExecutionContext context) { * Get exclusive lock. Kill all running transactions. Truncate tables */ private void truncateTables() { - jdbcTemplate.execute("BEGIN; " - + "TRUNCATE TABLE launch RESTART IDENTITY CASCADE;" + jdbcTemplate.execute("BEGIN; " + "TRUNCATE TABLE launch RESTART IDENTITY CASCADE;" + "TRUNCATE TABLE activity RESTART IDENTITY CASCADE;" + "TRUNCATE TABLE owned_entity RESTART IDENTITY CASCADE;" + "TRUNCATE TABLE ticket RESTART IDENTITY CASCADE;" @@ -150,10 +146,8 @@ private void createDefaultUser() { request.setLogin("default"); request.setPassword("1q2w3e"); request.setEmail("defaultemail@domain.com"); - User user = new UserBuilder().addCreateUserFullRQ(request) - .addUserRole(UserRole.USER) - .addPassword(passwordEncoder.encode(request.getPassword())) - .get(); + User user = new UserBuilder().addCreateUserFullRQ(request).addUserRole(UserRole.USER) + .addPassword(passwordEncoder.encode(request.getPassword())).get(); projectRepository.save(personalProjectService.generatePersonalProject(user)); userRepository.save(user); LOGGER.info("Default user has been successfully created."); @@ -167,15 +161,13 @@ private void deleteUser(User user) { } private void deleteProject(Project project) { - Set defaultIssueTypeIds = issueTypeRepository.getDefaultIssueTypes() - .stream() - .map(IssueType::getId) - .collect(Collectors.toSet()); - Set issueTypesToRemove = project.getProjectIssueTypes() - .stream() - .map(ProjectIssueType::getIssueType) - .filter(issueType -> !defaultIssueTypeIds.contains(issueType.getId())) - .collect(Collectors.toSet()); + Set defaultIssueTypeIds = + issueTypeRepository.getDefaultIssueTypes().stream().map(IssueType::getId) + .collect(Collectors.toSet()); + Set issueTypesToRemove = + project.getProjectIssueTypes().stream().map(ProjectIssueType::getIssueType) + .filter(issueType -> !defaultIssueTypeIds.contains(issueType.getId())) + .collect(Collectors.toSet()); projectRepository.delete(project); analyzerServiceClient.removeSuggest(project.getId()); issueTypeRepository.deleteAll(issueTypesToRemove); diff --git a/src/main/java/com/epam/ta/reportportal/job/LoadPluginsJob.java b/src/main/java/com/epam/ta/reportportal/job/LoadPluginsJob.java index 5ab29ced26..c5765c09b3 100644 --- a/src/main/java/com/epam/ta/reportportal/job/LoadPluginsJob.java +++ b/src/main/java/com/epam/ta/reportportal/job/LoadPluginsJob.java @@ -25,7 +25,7 @@ import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.filesystem.DataStore; import com.epam.ta.reportportal.job.service.PluginLoaderService; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.io.File; import java.io.IOException; import java.io.InputStream; diff --git a/src/main/java/com/epam/ta/reportportal/model/ActivityEventResource.java b/src/main/java/com/epam/ta/reportportal/model/ActivityEventResource.java new file mode 100644 index 0000000000..58755680f3 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/ActivityEventResource.java @@ -0,0 +1,99 @@ +/* + * Copyright 2023 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import java.util.Date; +import javax.validation.constraints.NotNull; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * JSON Representation of Report Portal's Activity domain object. + * + * @author Ryhor_Kukharenka + */ +@JsonInclude(Include.NON_NULL) +@Getter +@Setter +@Builder +@ToString +public class ActivityEventResource { + + @NotNull + @JsonProperty(value = "id", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private Long id; + + @NotNull + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssZ") + @JsonProperty(value = "created_at") + private Date createdAt; + + @NotNull + @JsonProperty(value = "event_name", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String eventName; + + @JsonProperty(value = "object_id") + @Schema(requiredMode = RequiredMode.REQUIRED) + private Long objectId; + + @NotNull + @JsonProperty(value = "object_name", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String objectName; + + @NotNull + @JsonProperty(value = "object_type", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String objectType; + + @JsonProperty(value = "project_id") + @Schema(requiredMode = RequiredMode.REQUIRED) + private Long projectId; + + @JsonProperty(value = "project_name") + @Schema(requiredMode = RequiredMode.REQUIRED) + private String projectName; + + @NotNull + @JsonProperty(value = "subject_name", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String subjectName; + + @NotNull + @JsonProperty(value = "subject_type", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String subjectType; + + @NotNull + @JsonProperty(value = "subject_id", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String subjectId; + + @JsonProperty(value = "details") + private Object details; + +} diff --git a/src/main/java/com/epam/ta/reportportal/model/ApiKeyRQ.java b/src/main/java/com/epam/ta/reportportal/model/ApiKeyRQ.java new file mode 100644 index 0000000000..f7ed6fa678 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/ApiKeyRQ.java @@ -0,0 +1,50 @@ +/* + * Copyright 2022 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.validation.constraints.NotNull; + +/** + * Api key representation for request + * + * @author Andrei Piankouski + */ +@JsonInclude(Include.NON_NULL) +public class ApiKeyRQ { + + @NotNull + @JsonProperty(value = "name", required = true) + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "ApiKeyRQ{" + + "name='" + name + '\'' + + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/ApiKeyRS.java b/src/main/java/com/epam/ta/reportportal/model/ApiKeyRS.java new file mode 100644 index 0000000000..284b4167cb --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/ApiKeyRS.java @@ -0,0 +1,112 @@ +/* + * Copyright 2023 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Date; +import javax.validation.constraints.NotNull; + +/** + * Api key representation for response + * + * @author Andrei Piankouski + */ +@JsonInclude(Include.NON_NULL) +public class ApiKeyRS { + + @NotNull + @JsonProperty(value = "id", required = true) + private Long id; + + @NotNull + @JsonProperty(value = "name", required = true) + private String name; + + @NotNull + @JsonProperty(value = "user_id", required = true) + private Long userId; + + @NotNull + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssZ") + @JsonProperty(value = "created_at") + private Date createdAt; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") + @JsonProperty(value = "last_used_at") + private Date lastUsedAt; + + @JsonProperty(value = "api_key") + private String apiKey; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public Date getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public Date getLastUsedAt() { + return lastUsedAt; + } + + public void setLastUsedAt(Date lastUsedAt) { + this.lastUsedAt = lastUsedAt; + } + + @Override + public String toString() { + return "ApiKeyRS{" + "id=" + id + ", name='" + name + '\'' + ", userId=" + userId + + ", createdAt=" + createdAt + ", lastUsedAt=" + lastUsedAt + ", apiKey='" + apiKey + '\'' + + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/ApiKeysRS.java b/src/main/java/com/epam/ta/reportportal/model/ApiKeysRS.java new file mode 100644 index 0000000000..ac9108aec8 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/ApiKeysRS.java @@ -0,0 +1,49 @@ +/* + * Copyright 2023 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.validation.constraints.NotNull; + +/** + * Container for ApiKeysRS + * + * @author Andrei Piankouski + */ +@JsonInclude(Include.NON_NULL) +public class ApiKeysRS { + + @NotNull + @JsonProperty(value = "items", required = true) + private List apiKeys; + + public List getApiKeys() { + return apiKeys; + } + + public void setApiKeys(List apiKeys) { + this.apiKeys = apiKeys; + } + + @Override + public String toString() { + return "ApiKeysRS{" + "apiKeys=" + apiKeys + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/BaseEntityRQ.java b/src/main/java/com/epam/ta/reportportal/model/BaseEntityRQ.java new file mode 100644 index 0000000000..a66b671f73 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/BaseEntityRQ.java @@ -0,0 +1,46 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_ENTITY_DESCRIPTION; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.validation.constraints.Size; + +/** + * Base entity for manipulating sharable resources + * + * @author Aliaksei_Makayed + */ +@JsonInclude(Include.NON_NULL) +public class BaseEntityRQ { + + @Size(max = MAX_ENTITY_DESCRIPTION) + @JsonProperty(value = "description") + private String description; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/BulkRQ.java b/src/main/java/com/epam/ta/reportportal/model/BulkRQ.java new file mode 100644 index 0000000000..a22f6c9fdc --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/BulkRQ.java @@ -0,0 +1,48 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +/** + * @param Type of Key + * @param Type of Entity + * @author Dzmitry_Kavalets + */ +public class BulkRQ { + + @Valid + @NotNull + @JsonProperty(value = "entities", required = true) + private Map entities; + + public Map getEntities() { + return entities; + } + + public void setEntities(Map entities) { + this.entities = entities; + } + + @Override + public String toString() { + return "BulkRQ{" + "entities=" + entities + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/CollectionsRQ.java b/src/main/java/com/epam/ta/reportportal/model/CollectionsRQ.java new file mode 100644 index 0000000000..718d526f3e --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/CollectionsRQ.java @@ -0,0 +1,50 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +/** + * @deprecated use {@link BulkRQ} instead + */ +@Deprecated +public class CollectionsRQ { + + @Valid + @NotNull + @JsonProperty(value = "elements", required = true) + private List elements; + + public List getElements() { + return elements; + } + + public void setElements(List elements) { + this.elements = elements; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("CollectionsRQ{"); + sb.append("elements=").append(elements); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/DeleteBulkRQ.java b/src/main/java/com/epam/ta/reportportal/model/DeleteBulkRQ.java new file mode 100644 index 0000000000..a64eed9377 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/DeleteBulkRQ.java @@ -0,0 +1,51 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.validation.constraints.NotEmpty; + +/** + * @author Ivan Budayeu + */ +public class DeleteBulkRQ { + + @NotEmpty + @JsonProperty(value = "ids") + private List ids; + + public DeleteBulkRQ() { + } + + public DeleteBulkRQ(@NotEmpty List ids) { + this.ids = ids; + } + + public List getIds() { + return ids; + } + + public void setIds(List ids) { + this.ids = ids; + } + + @Override + public String toString() { + return "DeleteBulkRQ{" + "ids=" + ids + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/DeleteBulkRS.java b/src/main/java/com/epam/ta/reportportal/model/DeleteBulkRS.java new file mode 100644 index 0000000000..7e6ec5bfb0 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/DeleteBulkRS.java @@ -0,0 +1,74 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.epam.ta.reportportal.ws.reporting.ErrorRS; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * @author Ihar Kahadouski + */ +public class DeleteBulkRS { + + @JsonProperty("successfullyDeleted") + private List deleted; + + @JsonProperty("notFound") + private List notFound; + + @JsonProperty("errors") + private List errors; + + public DeleteBulkRS() { + } + + public DeleteBulkRS(List deleted, List notFound, List errors) { + this.deleted = deleted; + this.notFound = notFound; + this.errors = errors; + } + + public List getDeleted() { + return deleted; + } + + public void setDeleted(List deleted) { + this.deleted = deleted; + } + + public List getNotFound() { + return notFound; + } + + public void setNotFound(List notFound) { + this.notFound = notFound; + } + + public List getErrors() { + return errors; + } + + public void setErrors(List errors) { + this.errors = errors; + } + + @Override + public String toString() { + return "DeleteBulkRS{" + "deleted=" + deleted + ", notFound=" + notFound + ", errors=" + errors + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/EntryCreatedRS.java b/src/main/java/com/epam/ta/reportportal/model/EntryCreatedRS.java new file mode 100644 index 0000000000..77bda905e8 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/EntryCreatedRS.java @@ -0,0 +1,59 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Response when some entry has been created and we need to return ID + * + * @author Andrei Varabyeu + * + */ +@JsonInclude(Include.NON_NULL) +public class EntryCreatedRS { + + @JsonProperty("id") + private Long id; + + public EntryCreatedRS() { + + } + + public EntryCreatedRS(Long id) { + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("EntryCreatedRS{"); + sb.append("id='").append(id).append('\''); + sb.append('}'); + return sb.toString(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/LaunchImportCompletionRS.java b/src/main/java/com/epam/ta/reportportal/model/LaunchImportCompletionRS.java new file mode 100644 index 0000000000..762bbd2573 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/LaunchImportCompletionRS.java @@ -0,0 +1,42 @@ +/* + * Copyright 2023 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +/** + * Operation completion response for launch import. + * + * @author Siarhei Hrabko + */ +@Getter +@Setter +@ToString +@AllArgsConstructor +@NoArgsConstructor +public class LaunchImportCompletionRS extends OperationCompletionRS { + + @JsonProperty(value = "data") + private LaunchImportData data; + +} diff --git a/src/main/java/com/epam/ta/reportportal/model/LaunchImportData.java b/src/main/java/com/epam/ta/reportportal/model/LaunchImportData.java new file mode 100644 index 0000000000..dff3b92a01 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/LaunchImportData.java @@ -0,0 +1,47 @@ +/* + * Copyright 2023 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +/** + * Operation completion response extension for launch import. + * + * @author Siarhei Hrabko + */ +@Getter +@Setter +@ToString +@AllArgsConstructor +@NoArgsConstructor +public class LaunchImportData { + + @JsonProperty("id") + private String id; + + @JsonProperty("name") + private String name; + + @JsonProperty("number") + private Long number; + +} diff --git a/src/main/java/com/epam/ta/reportportal/model/ModelViews.java b/src/main/java/com/epam/ta/reportportal/model/ModelViews.java new file mode 100644 index 0000000000..f7c9468c25 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/ModelViews.java @@ -0,0 +1,35 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +/** + * Container of view classes + * + * @author Andrei Varabyeu + * + */ +public class ModelViews { + + public static class DefaultView { + } + + public static class FullUserView extends DefaultView { + } + + public static class FullProjectInfoView extends DefaultView { + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/NestedStepResource.java b/src/main/java/com/epam/ta/reportportal/model/NestedStepResource.java new file mode 100644 index 0000000000..a23bba970e --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/NestedStepResource.java @@ -0,0 +1,143 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.io.Serializable; +import java.util.Date; + +/** + * @author Ivan Budayeu + */ +@JsonInclude(Include.NON_NULL) +public class NestedStepResource implements Serializable { + + @JsonProperty(value = "id") + private Long id; + + @JsonProperty(value = "name") + private String name; + + @JsonProperty(value = "uuid") + private String uuid; + + @JsonProperty(value = "type") + private String type; + + @JsonProperty(value = "startTime") + private Date startTime; + + @JsonProperty(value = "endTime") + private Date endTime; + + @JsonProperty(value = "status") + private String status; + + @JsonProperty(value = "duration") + private Double duration; + + @JsonProperty(value = "hasContent") + private Boolean hasContent; + + @JsonProperty(value = "attachmentsCount") + private Integer attachmentsCount; + + public NestedStepResource() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public Double getDuration() { + return duration; + } + + public void setDuration(Double duration) { + this.duration = duration; + } + + public Boolean getHasContent() { + return hasContent; + } + + public void setHasContent(Boolean hasContent) { + this.hasContent = hasContent; + } + + public Integer getAttachmentsCount() { + return attachmentsCount; + } + + public void setAttachmentsCount(Integer attachmentsCount) { + this.attachmentsCount = attachmentsCount; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/OwnedEntityResource.java b/src/main/java/com/epam/ta/reportportal/model/OwnedEntityResource.java new file mode 100644 index 0000000000..2f0d3b2fb9 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/OwnedEntityResource.java @@ -0,0 +1,86 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Shared entity can used for sending information to client about shared resource. + * Contains only information about name and owner of entity. + * + * @author Aliaksei_Makayed + * + */ +@JsonInclude(Include.NON_NULL) +public class OwnedEntityResource { + + @JsonProperty(value = "id") + private String id; + + @JsonProperty(value = "name") + private String name; + + @JsonProperty(value = "owner") + private String owner; + + @JsonProperty(value = "description") + private String description; + + 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 getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("OwnedEntity{"); + sb.append("name='").append(name).append('\''); + sb.append(", owner='").append(owner).append('\''); + sb.append(", description='").append(description).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/Page.java b/src/main/java/com/epam/ta/reportportal/model/Page.java new file mode 100644 index 0000000000..24f49479cb --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/Page.java @@ -0,0 +1,139 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + + +import java.util.Collection; +import java.util.Iterator; + +/** + * Paged response representation + * Re-implementation of Spring's HATEAOS Page implementation to get rid of Spring's deps in model package + * + * @author Andrei Varabyeu + */ +public class Page implements Iterable { + + private final Collection content; + private final PageMetadata page; + + /** + * Visible for deserializer + */ + Page() { + this(null, null); + } + + public Page(Collection content, PageMetadata page) { + this.content = content; + this.page = page; + } + + public Page(Collection content, long size, long number, long totalElements, long totalPages) { + this.content = content; + this.page = new PageMetadata(size, number, totalElements, totalPages); + } + + public Page(Collection content, long size, long number, long totalElements) { + this.content = content; + this.page = new PageMetadata(size, number, totalElements); + } + + public Collection getContent() { + return content; + } + + public PageMetadata getPage() { + return page; + } + + @Override + public Iterator iterator() { + return content.iterator(); + } + + public static class PageMetadata { + long number; + long size; + long totalElements; + long totalPages; + + /** + * Visible for deserializer + */ + PageMetadata(){ + } + + public PageMetadata(long size, long number, long totalElements, long totalPages) { + checkArgument(size > -1, "Size must not be negative!"); + checkArgument(number > -1, "Number must not be negative!"); + checkArgument(totalElements > -1, "Total elements must not be negative!"); + checkArgument(totalPages > -1, "Total pages must not be negative!"); + + this.number = number; + this.size = size; + this.totalElements = totalElements; + this.totalPages = totalPages; + + } + + public PageMetadata(long size, long number, long totalElements) { + this(size, number, totalElements, size == 0 ? 0 : (long) Math.ceil((double) totalElements / (double) size)); + } + + public long getNumber() { + return number; + } + + public long getSize() { + return size; + } + + public long getTotalElements() { + return totalElements; + } + + public long getTotalPages() { + return totalPages; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("PageMetadata{"); + sb.append("number=").append(number); + sb.append(", size=").append(size); + sb.append(", totalElements=").append(totalElements); + sb.append(", totalPages=").append(totalPages); + sb.append('}'); + return sb.toString(); + } + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("Page{"); + sb.append("content=").append(content); + sb.append(", page=").append(page); + sb.append('}'); + return sb.toString(); + } + + private static void checkArgument(boolean expression, String errorMessage) { + if (!expression) { + throw new IllegalArgumentException(errorMessage); + } + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/PagedResponse.java b/src/main/java/com/epam/ta/reportportal/model/PagedResponse.java new file mode 100644 index 0000000000..a97497dfd0 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/PagedResponse.java @@ -0,0 +1,118 @@ +/* + * Copyright 2023 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.validation.constraints.NotNull; + +/** + * Paged representation. + * + * @param Type of items + */ +@JsonInclude(Include.NON_NULL) +public class PagedResponse { + + @NotNull + @JsonProperty(value = "offset") + private Long offset; + + @NotNull + @JsonProperty(value = "limit") + private Integer limit; + + @NotNull + @JsonProperty(value = "total_count") + private Long totalCount; + + @NotNull + @JsonProperty(value = "sort") + private String sort; + + @NotNull + @JsonProperty(value = "order") + private String order; + + @NotNull + @JsonProperty(value = "items") + private List items; + + public PagedResponse() { + } + + public PagedResponse(Long offset, Integer limit, Long totalCount, String sort, String order, + List items) { + this.offset = offset; + this.limit = limit; + this.totalCount = totalCount; + this.sort = sort; + this.order = order; + this.items = items; + } + + public Long getOffset() { + return offset; + } + + public void setOffset(Long offset) { + this.offset = offset; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + public Long getTotalCount() { + return totalCount; + } + + public void setTotalCount(Long totalCount) { + this.totalCount = totalCount; + } + + public String getSort() { + return sort; + } + + public void setSort(String sort) { + this.sort = sort; + } + + public String getOrder() { + return order; + } + + public void setOrder(String order) { + this.order = order; + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } + +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/Position.java b/src/main/java/com/epam/ta/reportportal/model/Position.java new file mode 100644 index 0000000000..9eaca2ff26 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/Position.java @@ -0,0 +1,81 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Pavel Bortnik + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Position { + + @JsonProperty(value = "positionX") + private int x; + + @JsonProperty(value = "positionY") + private int y; + + public Position() { + } + + public Position(int x, int y) { + this.x = x; + this.y = y; + } + + public int getX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getY() { + return y; + } + + public void setY(int y) { + this.y = y; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + Position position = (Position) o; + + if (x != position.x) { + return false; + } + return y == position.y; + } + + @Override + public int hashCode() { + int result = x; + result = 31 * result + y; + return result; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/SearchCriteria.java b/src/main/java/com/epam/ta/reportportal/model/SearchCriteria.java new file mode 100644 index 0000000000..f0be5091ea --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/SearchCriteria.java @@ -0,0 +1,98 @@ +/* + * Copyright 2023 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import java.util.Objects; +import javax.validation.constraints.NotNull; + +/** + * Search Criteria used for a compound query and subsequent conversion to a filter. + * + * @author Ryhor_Kukharenka + */ +@JsonInclude(Include.NON_NULL) +public class SearchCriteria { + + @NotNull + @JsonProperty(value = "filter_key", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String filterKey; + + @JsonProperty(value = "operation") + @Schema(allowableValues = "EQ, NE, CNT, NON_CNT, BTW, IN") + private String operation; + + @NotNull + @JsonProperty(value = "value", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String value; + + public SearchCriteria() { + } + + public SearchCriteria(String filterKey, String operation, String value) { + this.filterKey = filterKey; + this.operation = operation; + this.value = value; + } + + public String getFilterKey() { + return filterKey; + } + + public void setFilterKey(String filterKey) { + this.filterKey = filterKey; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SearchCriteria that = (SearchCriteria) o; + return Objects.equals(filterKey, that.filterKey); + } + + @Override + public int hashCode() { + return Objects.hash(filterKey); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/SearchCriteriaRQ.java b/src/main/java/com/epam/ta/reportportal/model/SearchCriteriaRQ.java new file mode 100644 index 0000000000..58e0cde7ec --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/SearchCriteriaRQ.java @@ -0,0 +1,52 @@ +/* + * Copyright 2023 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Set; +import javax.validation.constraints.NotNull; + +/** + * Keep all search criteria for request. + * + * @author Ryhor_Kukharenka + */ +@JsonInclude(Include.NON_NULL) +public class SearchCriteriaRQ { + + @NotNull + @JsonProperty(value = "search_criterias") + private Set criteriaList; + + public SearchCriteriaRQ() { + } + + public SearchCriteriaRQ(Set criteriaList) { + this.criteriaList = criteriaList; + } + + public Set getCriteriaList() { + return criteriaList; + } + + public void setCriteriaList(Set criteriaList) { + this.criteriaList = criteriaList; + } + +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/Size.java b/src/main/java/com/epam/ta/reportportal/model/Size.java new file mode 100644 index 0000000000..a58c43b76d --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/Size.java @@ -0,0 +1,81 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Pavel Bortnik + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Size { + + @JsonProperty(value = "width") + private int width; + + @JsonProperty(value = "height") + private int height; + + public Size() { + } + + public Size(int width, int height) { + this.width = width; + this.height = height; + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = width; + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = height; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + Size size = (Size) o; + + if (width != size.width) { + return false; + } + return height == size.height; + } + + @Override + public int hashCode() { + int result = width; + result = 31 * result + height; + return result; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/SystemInfoRS.java b/src/main/java/com/epam/ta/reportportal/model/SystemInfoRS.java new file mode 100644 index 0000000000..98dcb7af04 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/SystemInfoRS.java @@ -0,0 +1,62 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * System information response + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class SystemInfoRS { + + @JsonProperty("os") + private String osVersion; + + @JsonProperty("cpuUsage") + private float cpuUsage; + + @JsonProperty("memUsage") + private float memUsage; + + public void setOsVersion(String value) { + this.osVersion = value; + } + + public String getOsVersion() { + return osVersion; + } + + public void setCpuUsage(float value) { + this.cpuUsage = value; + } + + public float getCpuUsage() { + return cpuUsage; + } + + public void setMemUsage(float value) { + this.memUsage = value; + } + + public float getMemUsage() { + return memUsage; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/TestItemHistoryElement.java b/src/main/java/com/epam/ta/reportportal/model/TestItemHistoryElement.java new file mode 100644 index 0000000000..a40ffdb4d3 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/TestItemHistoryElement.java @@ -0,0 +1,58 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.epam.ta.reportportal.ws.reporting.TestItemResource; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +@JsonInclude(Include.NON_NULL) +public class TestItemHistoryElement { + + @JsonProperty(value = "groupingField") + private String groupingField; + + @JsonProperty(value = "resources") + private List resources; + + public TestItemHistoryElement() { + } + + public String getGroupingField() { + return groupingField; + } + + public void setGroupingField(String groupingField) { + this.groupingField = groupingField; + } + + public List getResources() { + return resources; + } + + public void setResources(List resources) { + this.resources = resources; + } + + @Override + public String toString() { + return "TestItemHistoryElement{" + "groupingField=" + groupingField + ", resources=" + resources + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/TokenCreatedRS.java b/src/main/java/com/epam/ta/reportportal/model/TokenCreatedRS.java new file mode 100644 index 0000000000..03f12da368 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/TokenCreatedRS.java @@ -0,0 +1,55 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Basic token creation response + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class TokenCreatedRS { + @JsonProperty("accessToken") + private String token; + + public TokenCreatedRS() { + } + + public TokenCreatedRS(String token) { + this.token = token; + } + + public void setId(String token) { + this.token = token; + } + + public String getToken() { + return token; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("TokenCreatedRS{"); + sb.append("access_token='").append(token).append('\''); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/WarningAwareRS.java b/src/main/java/com/epam/ta/reportportal/model/WarningAwareRS.java new file mode 100644 index 0000000000..6a2669cba9 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/WarningAwareRS.java @@ -0,0 +1,40 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +/** + * @author Andrei Varabyeu + */ +public class WarningAwareRS { + + private String warning; + + public String getWarning() { + return warning; + } + + public void setWarning(String warning) { + this.warning = warning; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("WarningAwareRS{"); + sb.append("warning='").append(warning).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/YesNoRS.java b/src/main/java/com/epam/ta/reportportal/model/YesNoRS.java new file mode 100644 index 0000000000..fee32044c8 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/YesNoRS.java @@ -0,0 +1,70 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonInclude(Include.NON_NULL) +public class YesNoRS { + + @JsonProperty("is") + private boolean is; + + public YesNoRS() { + } + + public YesNoRS(boolean param) { + this.is = param; + } + + public void setIs(boolean value) { + this.is = value; + } + + public boolean getIs() { + return is; + } + + @Override + public String toString() { + return "YesNoRS [is=" + is + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (is ? 1231 : 1237); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + YesNoRS other = (YesNoRS) obj; + if (is != other.is) + return false; + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/activity/DashboardActivityResource.java b/src/main/java/com/epam/ta/reportportal/model/activity/DashboardActivityResource.java new file mode 100644 index 0000000000..cb7622110c --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/activity/DashboardActivityResource.java @@ -0,0 +1,80 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.activity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Ihar Kahadouski + */ +public class DashboardActivityResource { + + @JsonProperty(value = "id", required = true) + private Long id; + + @JsonProperty(value = "name", required = true) + private String name; + + @JsonProperty(value = "projectId", required = true) + private Long projectId; + + @JsonProperty(value = "description") + private String description; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("DashboardActivityResource{"); + sb.append("id=").append(id); + sb.append(", name='").append(name).append('\''); + sb.append(", projectId=").append(projectId); + sb.append(", description='").append(description).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/activity/IntegrationActivityResource.java b/src/main/java/com/epam/ta/reportportal/model/activity/IntegrationActivityResource.java new file mode 100644 index 0000000000..6393ba1a9b --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/activity/IntegrationActivityResource.java @@ -0,0 +1,92 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.activity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Ihar Kahadouski + */ +public class IntegrationActivityResource { + + @JsonProperty(value = "id", required = true) + private Long id; + + @JsonProperty(value = "projectId", required = true) + private Long projectId; + + @JsonProperty(value = "name") + private String name; + + @JsonProperty(value = "projectName", required = true) + private String projectName; + + @JsonProperty(value = "typeName", required = true) + private String typeName; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public String getTypeName() { + return typeName; + } + + public void setTypeName(String typeName) { + this.typeName = typeName; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("IntegrationActivityResource{"); + sb.append("id=").append(id); + sb.append(", projectId=").append(projectId); + sb.append(", name='").append(name).append('\''); + sb.append(", projectName='").append(projectName).append('\''); + sb.append(", typeName='").append(typeName).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/activity/IssueTypeActivityResource.java b/src/main/java/com/epam/ta/reportportal/model/activity/IssueTypeActivityResource.java new file mode 100644 index 0000000000..395d8f0028 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/activity/IssueTypeActivityResource.java @@ -0,0 +1,56 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.activity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Ihar Kahadouski + */ +public class IssueTypeActivityResource { + + @JsonProperty(value = "id", required = true) + private Long id; + + @JsonProperty(value = "longName", required = true) + private String longName; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLongName() { + return longName; + } + + public void setLongName(String longName) { + this.longName = longName; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("IssueTypeActivityResource{"); + sb.append("id=").append(id); + sb.append(", longName='").append(longName).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/activity/LaunchActivityResource.java b/src/main/java/com/epam/ta/reportportal/model/activity/LaunchActivityResource.java new file mode 100644 index 0000000000..4a18163619 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/activity/LaunchActivityResource.java @@ -0,0 +1,68 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.activity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Ihar Kahadouski + */ +public class LaunchActivityResource { + + @JsonProperty(value = "id", required = true) + private Long id; + + @JsonProperty(value = "projectId", required = true) + private Long projectId; + + @JsonProperty(value = "name", required = true) + private String name; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("LaunchActivityResource{"); + sb.append("id=").append(id); + sb.append(", projectId=").append(projectId); + sb.append(", name='").append(name).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/activity/PatternTemplateActivityResource.java b/src/main/java/com/epam/ta/reportportal/model/activity/PatternTemplateActivityResource.java new file mode 100644 index 0000000000..31fff45e94 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/activity/PatternTemplateActivityResource.java @@ -0,0 +1,74 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.activity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Ivan Budayeu + */ +public class PatternTemplateActivityResource { + + @JsonProperty(value = "id", required = true) + private Long id; + + @JsonProperty(value = "projectId", required = true) + private Long projectId; + + @JsonProperty(value = "name", required = true) + private String name; + + @JsonProperty(value = "enabled", required = true) + private boolean enabled; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + @Override + public String toString() { + return "PatternTemplateActivityResource{" + "id=" + id + ", projectId=" + projectId + ", name='" + name + '\'' + ", enabled=" + enabled + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/activity/PluginActivityResource.java b/src/main/java/com/epam/ta/reportportal/model/activity/PluginActivityResource.java new file mode 100644 index 0000000000..8f38083d02 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/activity/PluginActivityResource.java @@ -0,0 +1,54 @@ +package com.epam.ta.reportportal.model.activity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class PluginActivityResource { + @JsonProperty(value = "id", required = true) + private Long id; + @JsonProperty(value = "name") + private String name; + + @JsonProperty(value = "enabled") + private boolean enabled; + + @JsonProperty(value = "version") + private String version; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + @Override + public String toString() { + return "PluginActivityResource{" + "id=" + id + ", name='" + name + '\'' + ", enabled=" + + enabled + ", version='" + version + '\'' + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/activity/ProjectAttributesActivityResource.java b/src/main/java/com/epam/ta/reportportal/model/activity/ProjectAttributesActivityResource.java new file mode 100644 index 0000000000..4cf01baef6 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/activity/ProjectAttributesActivityResource.java @@ -0,0 +1,72 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.activity; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.Map; + +/** + * @author Ihar Kahadouski + */ +public class ProjectAttributesActivityResource { + + @JsonProperty(value = "projectId", required = true) + private Long projectId; + + @JsonProperty(value = "projectName", required = true) + private String projectName; + + @JsonProperty(value = "config") + @JsonDeserialize(as = HashMap.class) + private Map config; + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public Map getConfig() { + return config; + } + + public void setConfig(Map config) { + this.config = config; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("ProjectAttributesActivityResource{"); + sb.append("projectId=").append(projectId); + sb.append(", projectName='").append(projectName).append('\''); + sb.append(", config=").append(config); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/activity/TestItemActivityResource.java b/src/main/java/com/epam/ta/reportportal/model/activity/TestItemActivityResource.java new file mode 100644 index 0000000000..61cbbd09ab --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/activity/TestItemActivityResource.java @@ -0,0 +1,140 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.activity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Ihar Kahadouski + */ +public class TestItemActivityResource { + + @JsonProperty(value = "id", required = true) + private Long id; + + @JsonProperty(value = "projectId", required = true) + private Long projectId; + + @JsonProperty(value = "name", required = true) + private String name; + + @JsonProperty(value = "issueDescription") + private String issueDescription; + + @JsonProperty(value = "issueTypeLongName") + private String issueTypeLongName; + + @JsonProperty(value = "ignoreAnalyzer") + private boolean ignoreAnalyzer; + + @JsonProperty(value = "autoAnalyzed") + private boolean autoAnalyzed; + + @JsonProperty(value = "tickets") + private String tickets; + + @JsonProperty(value = "status") + private String status; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getIssueDescription() { + return issueDescription; + } + + public void setIssueDescription(String issueDescription) { + this.issueDescription = issueDescription; + } + + public String getIssueTypeLongName() { + return issueTypeLongName; + } + + public void setIssueTypeLongName(String issueTypeLongName) { + this.issueTypeLongName = issueTypeLongName; + } + + public boolean isIgnoreAnalyzer() { + return ignoreAnalyzer; + } + + public void setIgnoreAnalyzer(boolean ignoreAnalyzer) { + this.ignoreAnalyzer = ignoreAnalyzer; + } + + public boolean isAutoAnalyzed() { + return autoAnalyzed; + } + + public void setAutoAnalyzed(boolean autoAnalyzed) { + this.autoAnalyzed = autoAnalyzed; + } + + public String getTickets() { + return tickets; + } + + public void setTickets(String tickets) { + this.tickets = tickets; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("TestItemActivityResource{"); + sb.append("id=").append(id); + sb.append(", projectId=").append(projectId); + sb.append(", name='").append(name).append('\''); + sb.append(", issueDescription='").append(issueDescription).append('\''); + sb.append(", issueTypeLongName='").append(issueTypeLongName).append('\''); + sb.append(", ignoreAnalyzer=").append(ignoreAnalyzer); + sb.append(", autoAnalyzed=").append(autoAnalyzed); + sb.append(", tickets='").append(tickets).append('\''); + sb.append(", status='").append(status).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/activity/UserActivityResource.java b/src/main/java/com/epam/ta/reportportal/model/activity/UserActivityResource.java new file mode 100644 index 0000000000..5f88457605 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/activity/UserActivityResource.java @@ -0,0 +1,77 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.activity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Ihar Kahadouski + */ +public class UserActivityResource { + + @JsonProperty(value = "id", required = true) + private Long id; + + @JsonProperty(value = "defaultProjectId", required = true) + private Long defaultProjectId; + + @JsonProperty(value = "fullName", required = true) + private String fullName; + + public UserActivityResource() { + } + + public UserActivityResource(Long id, Long defaultProjectId, String fullName) { + this.id = id; + this.defaultProjectId = defaultProjectId; + this.fullName = fullName; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getDefaultProjectId() { + return defaultProjectId; + } + + public void setDefaultProjectId(Long defaultProjectId) { + this.defaultProjectId = defaultProjectId; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("UserActivityResource{"); + sb.append("id=").append(id); + sb.append(", defaultProjectId=").append(defaultProjectId); + sb.append(", fullName='").append(fullName).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/activity/UserFilterActivityResource.java b/src/main/java/com/epam/ta/reportportal/model/activity/UserFilterActivityResource.java new file mode 100644 index 0000000000..7f90abcad9 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/activity/UserFilterActivityResource.java @@ -0,0 +1,80 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.activity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Ihar Kahadouski + */ +public class UserFilterActivityResource { + + @JsonProperty(value = "id", required = true) + private Long id; + + @JsonProperty(value = "projectId", required = true) + private Long projectId; + + @JsonProperty(value = "name", required = true) + private String name; + + @JsonProperty(value = "description") + private String description; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + 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; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("UserFilterActivityResource{"); + sb.append("id=").append(id); + sb.append(", projectId=").append(projectId); + sb.append(", name='").append(name).append('\''); + sb.append(", description='").append(description).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/activity/WidgetActivityResource.java b/src/main/java/com/epam/ta/reportportal/model/activity/WidgetActivityResource.java new file mode 100644 index 0000000000..bfb00d7aef --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/activity/WidgetActivityResource.java @@ -0,0 +1,123 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.activity; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +/** + * @author Ihar Kahadouski + */ +public class WidgetActivityResource { + + @JsonProperty(value = "id", required = true) + private Long id; + + @JsonProperty(value = "projectId", required = true) + private Long projectId; + + @JsonProperty(value = "name", required = true) + private String name; + + @JsonProperty(value = "description") + private String description; + + @JsonProperty(value = "itemsCount") + private int itemsCount; + + @JsonProperty(value = "contentFields") + @JsonDeserialize(as = LinkedHashSet.class) + private Set contentFields; + + @JsonProperty(value = "widgetOptions") + @JsonDeserialize(as = LinkedHashMap.class) + private Map widgetOptions; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + 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 int getItemsCount() { + return itemsCount; + } + + public void setItemsCount(int itemsCount) { + this.itemsCount = itemsCount; + } + + public Set getContentFields() { + return contentFields; + } + + public void setContentFields(Set contentFields) { + this.contentFields = contentFields; + } + + public Map getWidgetOptions() { + return widgetOptions; + } + + public void setWidgetOptions(Map widgetOptions) { + this.widgetOptions = widgetOptions; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("WidgetActivityResource{"); + sb.append("id=").append(id); + sb.append(", projectId=").append(projectId); + sb.append(", name='").append(name).append('\''); + sb.append(", description='").append(description).append('\''); + sb.append(", itemsCount=").append(itemsCount); + sb.append(", contentFields=").append(contentFields); + sb.append(", widgetOptions=").append(widgetOptions); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/analyzer/AnalyzedItemRs.java b/src/main/java/com/epam/ta/reportportal/model/analyzer/AnalyzedItemRs.java new file mode 100644 index 0000000000..4228a840ce --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/analyzer/AnalyzedItemRs.java @@ -0,0 +1,81 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.analyzer; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; + +/** + * @author Pavel Bortnik + */ +public class AnalyzedItemRs { + + @JsonProperty("testItem") + private Long itemId; + + @JsonProperty("relevantItem") + private Long relevantItemId; + + @JsonProperty("issueType") + private String locator; + + public Long getItemId() { + return itemId; + } + + public void setItemId(Long itemId) { + this.itemId = itemId; + } + + public Long getRelevantItemId() { + return relevantItemId; + } + + public void setRelevantItemId(Long relevantItemId) { + this.relevantItemId = relevantItemId; + } + + public String getLocator() { + return locator; + } + + public void setLocator(String locator) { + this.locator = locator; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AnalyzedItemRs that = (AnalyzedItemRs) o; + return Objects.equals(itemId, that.itemId); + } + + @Override + public int hashCode() { + return Objects.hash(itemId); + } + + @Override + public String toString() { + return "AnalyzedItemRs{" + "itemId=" + itemId + ", relevantItemId=" + relevantItemId + ", issueTypeLocator=" + locator + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/analyzer/CleanIndexRq.java b/src/main/java/com/epam/ta/reportportal/model/analyzer/CleanIndexRq.java new file mode 100644 index 0000000000..3825bc8284 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/analyzer/CleanIndexRq.java @@ -0,0 +1,56 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.analyzer; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * @author Ihar Kahadouski + */ +public class CleanIndexRq { + + @JsonProperty("project") + private Long projectId; + + @JsonProperty("ids") + private List logIds; + + public CleanIndexRq() { + } + + public CleanIndexRq(Long projectId, List logIds) { + this.projectId = projectId; + this.logIds = logIds; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public List getLogIds() { + return logIds; + } + + public void setLogIds(List logIds) { + this.logIds = logIds; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/analyzer/IndexRs.java b/src/main/java/com/epam/ta/reportportal/model/analyzer/IndexRs.java new file mode 100644 index 0000000000..91f01e399c --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/analyzer/IndexRs.java @@ -0,0 +1,64 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.analyzer; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * Represents indexing operation response. + * + * @author Ivan Sharamet + */ +public class IndexRs { + + @JsonProperty("took") + private int took; + + @JsonProperty("errors") + private boolean errors; + + @JsonProperty("items") + private List items; + + public IndexRs() { + } + + public int getTook() { + return took; + } + + public void setTook(int took) { + this.took = took; + } + + public boolean isErrors() { + return errors; + } + + public void setErrors(boolean errors) { + this.errors = errors; + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/analyzer/IndexRsIndex.java b/src/main/java/com/epam/ta/reportportal/model/analyzer/IndexRsIndex.java new file mode 100644 index 0000000000..185b0858a6 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/analyzer/IndexRsIndex.java @@ -0,0 +1,114 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.analyzer; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Represents detailed index information in indexing operation response. + * + * @author Ivan Sharamet + */ +public class IndexRsIndex { + + public static final int STATUS_UPDATED = 200; + public static final int STATUS_CREATED = 201; + + @JsonProperty("_index") + private String index; + + @JsonProperty("_type") + private String type; + + @JsonProperty("_id") + private String id; + + @JsonProperty("_version") + private int version; + + @JsonProperty("result") + private String result; + + @JsonProperty("created") + private boolean created; + + @JsonProperty("status") + private int status; + + public IndexRsIndex() { + } + + public String getIndex() { + return index; + } + + public void setIndex(String index) { + this.index = index; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getVersion() { + return version; + } + + public void setVersion(int version) { + this.version = version; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + public boolean isCreated() { + return created; + } + + public void setCreated(boolean created) { + this.created = created; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + public boolean failed() { + return status != STATUS_CREATED && status != STATUS_UPDATED; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/analyzer/IndexRsItem.java b/src/main/java/com/epam/ta/reportportal/model/analyzer/IndexRsItem.java new file mode 100644 index 0000000000..ece1c27aa6 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/analyzer/IndexRsItem.java @@ -0,0 +1,42 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.analyzer; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Represents single item in indexing operation response. + * + * @author Ivan Sharamet + */ +public class IndexRsItem { + + @JsonProperty("index") + private IndexRsIndex index; + + public IndexRsItem() { + } + + public IndexRsIndex getIndex() { + return index; + } + + public void setIndex(IndexRsIndex index) { + this.index = index; + } + +} diff --git a/src/main/java/com/epam/ta/reportportal/model/analyzer/RelevantItemInfo.java b/src/main/java/com/epam/ta/reportportal/model/analyzer/RelevantItemInfo.java new file mode 100644 index 0000000000..11c16ae5e5 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/analyzer/RelevantItemInfo.java @@ -0,0 +1,65 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.analyzer; + +import java.io.Serializable; + +/** + * @author Ihar Kahadouski + */ +public class RelevantItemInfo implements Serializable { + + private String itemId; + + private String path; + + private String launchId; + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getLaunchId() { + return launchId; + } + + public void setLaunchId(String launchId) { + this.launchId = launchId; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("RelevantItemInfo{"); + sb.append("itemId='").append(itemId).append('\''); + sb.append(", path='").append(path).append('\''); + sb.append(", launchId='").append(launchId).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/analyzer/SearchRq.java b/src/main/java/com/epam/ta/reportportal/model/analyzer/SearchRq.java new file mode 100644 index 0000000000..01970d8b3c --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/analyzer/SearchRq.java @@ -0,0 +1,106 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.analyzer; + +import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; +import java.util.List; + +/** + * @author Ihar Kahadouski + */ +public class SearchRq { + + private Long launchId; + + private String launchName; + + private Long itemId; + + private Long projectId; + + private List filteredLaunchIds; + + private List logMessages; + + private Integer logLines; + + private AnalyzerConfig analyzerConfig; + + public Long getLaunchId() { + return launchId; + } + + public void setLaunchId(Long launchId) { + this.launchId = launchId; + } + + public String getLaunchName() { + return launchName; + } + + public void setLaunchName(String launchName) { + this.launchName = launchName; + } + + public Long getItemId() { + return itemId; + } + + public void setItemId(Long itemId) { + this.itemId = itemId; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public Integer getLogLines() { + return logLines; + } + + public void setLogLines(Integer logLines) { + this.logLines = logLines; + } + + public List getFilteredLaunchIds() { + return filteredLaunchIds; + } + + public void setFilteredLaunchIds(List filteredLaunchIds) { + this.filteredLaunchIds = filteredLaunchIds; + } + + public List getLogMessages() { + return logMessages; + } + + public void setLogMessages(List logMessages) { + this.logMessages = logMessages; + } + + public AnalyzerConfig getAnalyzerConfig() { + return analyzerConfig; + } + + public void setAnalyzerConfig(AnalyzerConfig analyzerConfig) { + this.analyzerConfig = analyzerConfig; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/analyzer/SearchRs.java b/src/main/java/com/epam/ta/reportportal/model/analyzer/SearchRs.java new file mode 100644 index 0000000000..f9ce27413d --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/analyzer/SearchRs.java @@ -0,0 +1,65 @@ +/* + * Copyright 2020 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.analyzer; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; + +/** + * @author Ivan Budayeu + */ +public class SearchRs { + + @JsonProperty(value = "logId") + private Long logId; + + @JsonProperty(value = "testItemId") + private Long testItemId; + + public Long getLogId() { + return logId; + } + + public void setLogId(Long logId) { + this.logId = logId; + } + + public Long getTestItemId() { + return testItemId; + } + + public void setTestItemId(Long testItemId) { + this.testItemId = testItemId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SearchRs searchRs = (SearchRs) o; + return Objects.equals(logId, searchRs.logId) && Objects.equals(testItemId, searchRs.testItemId); + } + + @Override + public int hashCode() { + return Objects.hash(logId, testItemId); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/dashboard/AddWidgetRq.java b/src/main/java/com/epam/ta/reportportal/model/dashboard/AddWidgetRq.java new file mode 100644 index 0000000000..8e563ae71b --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/dashboard/AddWidgetRq.java @@ -0,0 +1,42 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.dashboard; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +/** + * @author Pavel Bortnik + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AddWidgetRq { + + @Valid + @NotNull + @JsonProperty(value = "addWidget") + private DashboardResource.WidgetObjectModel addWidget; + + public DashboardResource.WidgetObjectModel getAddWidget() { + return addWidget; + } + + public void setAddWidget(DashboardResource.WidgetObjectModel addWidget) { + this.addWidget = addWidget; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/dashboard/CreateDashboardRQ.java b/src/main/java/com/epam/ta/reportportal/model/dashboard/CreateDashboardRQ.java new file mode 100644 index 0000000000..0981c51257 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/dashboard/CreateDashboardRQ.java @@ -0,0 +1,57 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.dashboard; + +import com.epam.ta.reportportal.model.BaseEntityRQ; +import com.epam.ta.reportportal.ws.annotations.NotBlankWithSize; +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; + +/** + * Domain object for creating dashboards. + * + * @author Aliaksei_Makayed + */ +@JsonInclude(Include.NON_NULL) +@Schema +public class CreateDashboardRQ extends BaseEntityRQ { + + @NotBlankWithSize(min = ValidationConstraints.MIN_NAME_LENGTH, max = ValidationConstraints.MAX_DASHBOARD_NAME_LENGTH) + @JsonProperty(value = "name", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("CreateDashboardRQ{"); + sb.append("name='").append(name).append('\''); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/dashboard/DashboardResource.java b/src/main/java/com/epam/ta/reportportal/model/dashboard/DashboardResource.java new file mode 100644 index 0000000000..d5c6615ea0 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/dashboard/DashboardResource.java @@ -0,0 +1,183 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.dashboard; + +import com.epam.ta.reportportal.model.Position; +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.epam.ta.reportportal.ws.reporting.OwnedResource; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +/** + * Domain model DashBoard resource object. JSON Representation of Report Portal + * domain object. + * + * @author Aliaksei_Makayed + */ +@JsonInclude(Include.NON_NULL) +public class DashboardResource extends OwnedResource { + + @NotNull + @JsonProperty(value = "id", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private Long dashboardId; + + @NotBlank + @Size(min = ValidationConstraints.MIN_NAME_LENGTH, max = ValidationConstraints.MAX_DASHBOARD_NAME_LENGTH) + @JsonProperty(value = "name", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String name; + + @JsonProperty(value = "widgets") + private List widgets; + + public Long getDashboardId() { + return dashboardId; + } + + public void setDashboardId(Long dashboardId) { + this.dashboardId = dashboardId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getWidgets() { + return widgets; + } + + public void setWidgets(List widgets) { + this.widgets = widgets; + } + + @JsonInclude(Include.NON_NULL) + public static class WidgetObjectModel { + + @JsonProperty(value = "widgetName") + private String name; + + @NotNull + @JsonProperty(value = "widgetId") + private Long widgetId; + + @JsonProperty(value = "widgetType") + private String widgetType; + + @JsonProperty(value = "widgetSize") + private com.epam.ta.reportportal.model.Size widgetSize = new com.epam.ta.reportportal.model.Size(); + + @JsonProperty(value = "widgetPosition") + private Position widgetPosition = new Position(); + + @JsonProperty(value = "widgetOptions") + private Map widgetOptions; + + public WidgetObjectModel() { + } + + public WidgetObjectModel(String name, Long widgetId, com.epam.ta.reportportal.model.Size widgetSize, Position widgetPosition) { + this.name = name; + this.widgetId = widgetId; + this.widgetSize = widgetSize; + this.widgetPosition = widgetPosition; + } + + public Long getWidgetId() { + return widgetId; + } + + public void setWidgetId(Long widgetId) { + this.widgetId = widgetId; + } + + public String getWidgetType() { + return widgetType; + } + + public void setWidgetType(String widgetType) { + this.widgetType = widgetType; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public com.epam.ta.reportportal.model.Size getWidgetSize() { + return widgetSize; + } + + public void setWidgetSize(com.epam.ta.reportportal.model.Size widgetSize) { + this.widgetSize = widgetSize; + } + + public Position getWidgetPosition() { + return widgetPosition; + } + + public void setWidgetPosition(Position widgetPosition) { + this.widgetPosition = widgetPosition; + } + + public Map getWidgetOptions() { + return widgetOptions; + } + + public void setWidgetOptions(Map widgetOptions) { + this.widgetOptions = widgetOptions; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("WidgetObjectModel{"); + sb.append("name='").append(name).append('\''); + sb.append(", widgetId=").append(widgetId); + sb.append(", widgetType='").append(widgetType).append('\''); + sb.append(", widgetSize=").append(widgetSize); + sb.append(", widgetPosition=").append(widgetPosition); + sb.append(", widgetOptions=").append(widgetOptions); + sb.append('}'); + return sb.toString(); + } + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("DashboardResource{"); + sb.append("dashboardId='").append(dashboardId).append('\''); + sb.append(", name='").append(name).append('\''); + sb.append(", widgets=").append(widgets); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/dashboard/UpdateDashboardRQ.java b/src/main/java/com/epam/ta/reportportal/model/dashboard/UpdateDashboardRQ.java new file mode 100644 index 0000000000..16b206cf95 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/dashboard/UpdateDashboardRQ.java @@ -0,0 +1,67 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.dashboard; + +import com.epam.ta.reportportal.model.BaseEntityRQ; +import com.epam.ta.reportportal.ws.annotations.NotBlankWithSize; +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import java.util.List; +import javax.validation.Valid; + +/** + * Domain object for updating widget positions. + * + * @author Pavel Bortnik + */ +@JsonInclude(Include.NON_NULL) +public class UpdateDashboardRQ extends BaseEntityRQ { + + @NotBlankWithSize(min = ValidationConstraints.MIN_NAME_LENGTH, max = ValidationConstraints.MAX_DASHBOARD_NAME_LENGTH) + @JsonProperty(value = "name", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String name; + + @Valid + @JsonProperty(value = "updateWidgets") + private List widgets; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public void setWidgets(List value) { + this.widgets = value; + } + + public List getWidgets() { + return widgets; + } + + @Override + public String toString() { + return "UpdateDashboardRQ{" + "name='" + name + '\'' + ", widgets=" + widgets + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/externalsystem/BtsConnectionTestRQ.java b/src/main/java/com/epam/ta/reportportal/model/externalsystem/BtsConnectionTestRQ.java new file mode 100644 index 0000000000..8432bb86cd --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/externalsystem/BtsConnectionTestRQ.java @@ -0,0 +1,52 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.externalsystem; + +import com.fasterxml.jackson.annotation.JsonInclude; +import javax.validation.constraints.NotBlank; + +/** + * @author Ivan Budayeu + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BtsConnectionTestRQ { + + @NotBlank + private String url; + + @NotBlank + private String btsProject; + + public BtsConnectionTestRQ() { + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getBtsProject() { + return btsProject; + } + + public void setBtsProject(String btsProject) { + this.btsProject = btsProject; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/externalsystem/UpdateBugTrackingSystemRQ.java b/src/main/java/com/epam/ta/reportportal/model/externalsystem/UpdateBugTrackingSystemRQ.java new file mode 100644 index 0000000000..a4e50707c2 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/externalsystem/UpdateBugTrackingSystemRQ.java @@ -0,0 +1,43 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.externalsystem; + +import com.epam.ta.reportportal.ws.model.externalsystem.PostFormField; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * Request model for external system update + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class UpdateBugTrackingSystemRQ { + + @JsonProperty(value = "fields") + private List fields; + + public void setFields(List form) { + this.fields = form; + } + + public List getFields() { + return fields; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/filter/BulkUpdateFilterRQ.java b/src/main/java/com/epam/ta/reportportal/model/filter/BulkUpdateFilterRQ.java new file mode 100644 index 0000000000..8e7df6bf70 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/filter/BulkUpdateFilterRQ.java @@ -0,0 +1,47 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.filter; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.validation.constraints.NotBlank; + +/** + * @deprecated use {@link UpdateUserFilterRQ} in conjunction with + * {@link com.epam.ta.reportportal.model.BulkRQ} + */ +@Deprecated +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BulkUpdateFilterRQ extends UpdateUserFilterRQ { + + @NotBlank + @JsonProperty(value = "id") + private String id; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String toString() { + return "BulkUpdateFilterRQ{" + "id='" + id + '\'' + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/filter/Order.java b/src/main/java/com/epam/ta/reportportal/model/filter/Order.java new file mode 100644 index 0000000000..e18ca361d8 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/filter/Order.java @@ -0,0 +1,80 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.filter; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import javax.validation.constraints.NotNull; + +/** + * @author Pavel Bortnik + */ +public class Order { + + @NotNull + @JsonProperty(value = "sortingColumn", required = true) + private String sortingColumnName; + + @NotNull + @JsonProperty(value = "isAsc", required = true) + private boolean isAsc; + + public String getSortingColumnName() { + return sortingColumnName; + } + + public void setSortingColumnName(String sortingColumnName) { + this.sortingColumnName = sortingColumnName; + } + + public boolean getIsAsc() { + return isAsc; + } + + public void setIsAsc(boolean isAsc) { + this.isAsc = isAsc; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + Order order = (Order) o; + + if (isAsc != order.isAsc) { + return false; + } + return sortingColumnName != null ? sortingColumnName.equals(order.sortingColumnName) : order.sortingColumnName == null; + } + + @Override + public int hashCode() { + int result = sortingColumnName != null ? sortingColumnName.hashCode() : 0; + result = 31 * result + (isAsc ? 1 : 0); + return result; + } + + @Override + public String toString() { + return "Order{" + "sortingColumnName='" + sortingColumnName + '\'' + ", isAsc=" + isAsc + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/filter/UpdateUserFilterRQ.java b/src/main/java/com/epam/ta/reportportal/model/filter/UpdateUserFilterRQ.java new file mode 100644 index 0000000000..ae422a7f70 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/filter/UpdateUserFilterRQ.java @@ -0,0 +1,113 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.filter; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_NUMBER_OF_FILTER_ENTITIES; +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_USER_FILTER_NAME_LENGTH; +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_COLLECTION_SIZE; +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_NAME_LENGTH; + +import com.epam.ta.reportportal.model.BaseEntityRQ; +import com.epam.ta.reportportal.ws.annotations.In; +import com.epam.ta.reportportal.ws.annotations.NotBlankWithSize; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import javax.validation.Valid; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +/** + * Domain object for filter actions + * + * @author Aliaksei_Makayed + */ +@JsonInclude(Include.NON_NULL) +public class UpdateUserFilterRQ extends BaseEntityRQ { + + @NotBlankWithSize(min = MIN_NAME_LENGTH, max = MAX_USER_FILTER_NAME_LENGTH) + @JsonProperty(value = "name", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String name; + + @NotBlank + @JsonProperty(value = "type", required = true) + @In(allowedValues = { "launch", "testItem", "log" }) + @Schema(required = true, allowableValues = "launch, testitem, log") + private String objectType; + + @Valid + @NotNull + @Size(min = MIN_COLLECTION_SIZE, max = MAX_NUMBER_OF_FILTER_ENTITIES) + @JsonProperty(value = "conditions", required = true) + @JsonDeserialize(as = LinkedHashSet.class) + @Schema(requiredMode = RequiredMode.REQUIRED) + private Set conditions; + + @Valid + @NotNull + @Size(min = MIN_COLLECTION_SIZE) + @JsonProperty(value = "orders", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private List orders; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @NotNull + public Set getConditions() { + return conditions; + } + + public void setConditions(@NotNull Set conditions) { + this.conditions = conditions; + } + + public String getObjectType() { + return objectType; + } + + public void setObjectType(String objectType) { + this.objectType = objectType; + } + + public List getOrders() { + return orders; + } + + public void setOrders(List orders) { + this.orders = orders; + } + + @Override + public String toString() { + return "UpdateUserFilterRQ{" + "name='" + name + '\'' + ", objectType='" + objectType + '\'' + + ", conditions=" + conditions + ", orders=" + orders + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/filter/UserFilterCondition.java b/src/main/java/com/epam/ta/reportportal/model/filter/UserFilterCondition.java new file mode 100644 index 0000000000..187915929d --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/filter/UserFilterCondition.java @@ -0,0 +1,134 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.filter; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +import javax.validation.constraints.NotBlank; + +/** + * Filter entity domain model object. + * + * @author Aliaksei_Makayed + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class UserFilterCondition { + + @NotBlank + @JsonProperty(value = "filteringField", required = true) + private String filteringField; + + @NotBlank + @JsonProperty(value = "condition", required = true) + private String condition; + + @NotBlank + @JsonProperty(value = "value", required = true) + private String value; + + public UserFilterCondition() { + } + + public UserFilterCondition(String field, String condition, String value) { + this.filteringField = field; + this.condition = condition; + this.value = value; + } + + public String getCondition() { + return condition; + } + + public void setCondition(String condition) { + this.condition = condition; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getFilteringField() { + return filteringField; + } + + public void setFilteringField(String filteringField) { + this.filteringField = filteringField; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((condition == null) ? 0 : condition.hashCode()); + result = prime * result + ((filteringField == null) ? 0 : filteringField.hashCode()); + result = prime * result + ((value == null) ? 0 : value.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + UserFilterCondition other = (UserFilterCondition) obj; + if (condition == null) { + if (other.condition != null) { + return false; + } + } else if (!condition.equals(other.condition)) { + return false; + } + if (filteringField == null) { + if (other.filteringField != null) { + return false; + } + } else if (!filteringField.equals(other.filteringField)) { + return false; + } + if (value == null) { + if (other.value != null) { + return false; + } + } else if (!value.equals(other.value)) { + return false; + } + return true; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("UserFilterEntity{"); + sb.append("filteringField='").append(filteringField).append('\''); + sb.append(", condition='").append(condition).append('\''); + sb.append(", value='").append(value).append('\''); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/filter/UserFilterResource.java b/src/main/java/com/epam/ta/reportportal/model/filter/UserFilterResource.java new file mode 100644 index 0000000000..4bd169e53c --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/filter/UserFilterResource.java @@ -0,0 +1,126 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.filter; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_USER_FILTER_NAME_LENGTH; +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_COLLECTION_SIZE; +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_NAME_LENGTH; + +import com.epam.ta.reportportal.ws.annotations.In; +import com.epam.ta.reportportal.ws.reporting.OwnedResource; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Set; +import javax.validation.Valid; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +/** + * JSON Representation of Report Portal's UserFilter domain object + * + * @author Aliaksei_Makayed + */ + +@JsonInclude(Include.NON_NULL) +public class UserFilterResource extends OwnedResource { + + @NotNull + @JsonProperty(value = "id", required = true) + private Long filterId; + + @NotBlank + @Size(min = MIN_NAME_LENGTH, max = MAX_USER_FILTER_NAME_LENGTH) + @JsonProperty(value = "name", required = true) + private String name; + + @Valid + @NotNull + @Size(min = MIN_COLLECTION_SIZE) + @JsonProperty(value = "conditions", required = true) + private Set conditions; + + @Size(min = MIN_COLLECTION_SIZE) + @JsonProperty(value = "orders", required = true) + private List orders; + + @In(allowedValues = { "launch", "testItem", "log" }) + @NotNull + @JsonProperty(value = "type", required = true) + private String objectType; + + @NotNull + @JsonProperty(value = "owner", required = true) + private String owner; + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Set getConditions() { + return conditions; + } + + public void setConditions(Set conditions) { + this.conditions = conditions; + } + + public List getOrders() { + return orders; + } + + public void setOrders(List orders) { + this.orders = orders; + } + + public Long getFilterId() { + return filterId; + } + + public void setFilterId(Long filterId) { + this.filterId = filterId; + } + + public String getObjectType() { + return objectType; + } + + public void setObjectType(String objectType) { + this.objectType = objectType; + } + + @Override + public String toString() { + return "UserFilterResource{" + "filterId='" + filterId + '\'' + ", name='" + name + '\'' + + ", conditions=" + conditions + ", orders=" + orders + ", objectType='" + objectType + '\'' + + ", owner='" + owner + '\'' + "} " + super.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/integration/AuthFlowEnum.java b/src/main/java/com/epam/ta/reportportal/model/integration/AuthFlowEnum.java new file mode 100644 index 0000000000..157235ecee --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/integration/AuthFlowEnum.java @@ -0,0 +1,28 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.integration; + +/** + * @author Pavel Bortnik + */ +public enum AuthFlowEnum { + OAUTH, + BASIC, + TOKEN, + FORM, + LDAP +} diff --git a/src/main/java/com/epam/ta/reportportal/model/integration/CreateIntegrationRQ.java b/src/main/java/com/epam/ta/reportportal/model/integration/CreateIntegrationRQ.java new file mode 100644 index 0000000000..5ca4cc7c05 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/integration/CreateIntegrationRQ.java @@ -0,0 +1 @@ +package com.epam.ta.reportportal.model.integration; \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/integration/IntegrationRQ.java b/src/main/java/com/epam/ta/reportportal/model/integration/IntegrationRQ.java new file mode 100644 index 0000000000..4455341b85 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/integration/IntegrationRQ.java @@ -0,0 +1,61 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.integration; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; + +/** + * @author Pavel Bortnik + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class IntegrationRQ { + + @JsonProperty("name") + private String name; + + @JsonProperty("integrationParameters") + private Map integrationParams; + + @JsonProperty("enabled") + private Boolean enabled; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Map getIntegrationParams() { + return integrationParams; + } + + public void setIntegrationParams(Map integrationParams) { + this.integrationParams = integrationParams; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/integration/IntegrationResource.java b/src/main/java/com/epam/ta/reportportal/model/integration/IntegrationResource.java new file mode 100644 index 0000000000..79840b6611 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/integration/IntegrationResource.java @@ -0,0 +1,118 @@ +/* + * Copyright 2021 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.integration; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.io.Serializable; +import java.util.Date; +import java.util.Map; + +/** + * @author Pavel Bortnik + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class IntegrationResource implements Serializable { + + @JsonProperty("id") + private Long id; + + @JsonProperty("projectId") + private Long projectId; + + @JsonProperty("name") + private String name; + + @JsonProperty("integrationType") + private IntegrationTypeResource integrationType; + + @JsonProperty("integrationParameters") + private Map integrationParams; + + @JsonProperty("enabled") + private Boolean enabled; + + @JsonProperty("creator") + private String creator; + + @JsonProperty("creationDate") + private Date creationDate; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public IntegrationTypeResource getIntegrationType() { + return integrationType; + } + + public void setIntegrationType(IntegrationTypeResource integrationType) { + this.integrationType = integrationType; + } + + public Map getIntegrationParams() { + return integrationParams; + } + + public void setIntegrationParams(Map integrationParams) { + this.integrationParams = integrationParams; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public String getCreator() { + return creator; + } + + public void setCreator(String creator) { + this.creator = creator; + } + + public Date getCreationDate() { + return creationDate; + } + + public void setCreationDate(Date creationDate) { + this.creationDate = creationDate; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/integration/IntegrationTypeResource.java b/src/main/java/com/epam/ta/reportportal/model/integration/IntegrationTypeResource.java new file mode 100644 index 0000000000..dbecced8de --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/integration/IntegrationTypeResource.java @@ -0,0 +1,108 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.integration; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.io.Serializable; +import java.util.Date; +import java.util.Map; + +/** + * @author Pavel Bortnik + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class IntegrationTypeResource implements Serializable { + + @JsonProperty("type") + private Long id; + + @JsonProperty("name") + private String name; + + @JsonProperty("enabled") + private boolean enabled; + + @JsonProperty("authFlow") + private AuthFlowEnum authFlow; + + @JsonProperty("creationDate") + private Date creationDate; + + @JsonProperty("groupType") + private String groupType; + + @JsonProperty("details") + private Map details; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @JsonProperty("enabled") + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public AuthFlowEnum getAuthFlow() { + return authFlow; + } + + public void setAuthFlow(AuthFlowEnum authFlow) { + this.authFlow = authFlow; + } + + public Date getCreationDate() { + return creationDate; + } + + public void setCreationDate(Date creationDate) { + this.creationDate = creationDate; + } + + public String getGroupType() { + return groupType; + } + + public void setGroupType(String groupType) { + this.groupType = groupType; + } + + public Map getDetails() { + return details; + } + + public void setDetails(Map details) { + this.details = details; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/integration/UpdatePluginStateRQ.java b/src/main/java/com/epam/ta/reportportal/model/integration/UpdatePluginStateRQ.java new file mode 100644 index 0000000000..3b81382bba --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/integration/UpdatePluginStateRQ.java @@ -0,0 +1,61 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.integration; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.io.Serializable; +import javax.validation.constraints.NotNull; + +/** + * @author Ivan Budayeu + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UpdatePluginStateRQ implements Serializable { + + @NotNull + private Boolean isEnabled; + + public UpdatePluginStateRQ() { + } + + public Boolean getEnabled() { + return isEnabled; + } + + public void setEnabled(Boolean enabled) { + isEnabled = enabled; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + UpdatePluginStateRQ that = (UpdatePluginStateRQ) o; + + return isEnabled != null ? isEnabled.equals(that.isEnabled) : that.isEnabled == null; + } + + @Override + public int hashCode() { + return isEnabled != null ? isEnabled.hashCode() : 0; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/issue/DefineIssueRQ.java b/src/main/java/com/epam/ta/reportportal/model/issue/DefineIssueRQ.java new file mode 100644 index 0000000000..6fa0266ffd --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/issue/DefineIssueRQ.java @@ -0,0 +1,56 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.issue; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +/** + * Request for test items issue types definition (defect block) + * + * @author Dzianis Shlychkou + */ +@JsonInclude(Include.NON_NULL) +public class DefineIssueRQ { + + @NotNull + @Valid + @Size(max = 300) + @JsonProperty(value = "issues", required = true) + private List issues; + + public List getIssues() { + return issues; + } + + public void setIssues(List issues) { + this.issues = issues; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("DefineIssueRQ{"); + sb.append("issues=").append(issues); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/issue/IssueDefinition.java b/src/main/java/com/epam/ta/reportportal/model/issue/IssueDefinition.java new file mode 100644 index 0000000000..cad1f46d81 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/issue/IssueDefinition.java @@ -0,0 +1,67 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.issue; + +import com.epam.ta.reportportal.ws.reporting.Issue; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +/** + * Test item issue with provided it + * + * @author Dzianis Shlychkou + * + */ +@JsonInclude(Include.NON_NULL) +public class IssueDefinition { + + @NotNull + @JsonProperty(value = "testItemId", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private Long id; + + @NotNull + @Valid + @JsonProperty(value = "issue", required = true) + private Issue issue; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Issue getIssue() { + return issue; + } + + public void setIssue(Issue issue) { + this.issue = issue; + } + + @Override + public String toString() { + return "IssueDefinition{" + "id=" + id + ", issue=" + issue + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/item/ExternalIssueRQ.java b/src/main/java/com/epam/ta/reportportal/model/item/ExternalIssueRQ.java new file mode 100644 index 0000000000..6672a2ca49 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/item/ExternalIssueRQ.java @@ -0,0 +1,43 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.item; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.Size; + +/** + * @author Ihar Kahadouski + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public abstract class ExternalIssueRQ { + + @NotEmpty + @Size(max = 300) + @JsonProperty(value = "testItemIds") + private List testItemIds; + + public List getTestItemIds() { + return testItemIds; + } + + public void setTestItemIds(List testItemIds) { + this.testItemIds = testItemIds; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/item/LinkExternalIssueRQ.java b/src/main/java/com/epam/ta/reportportal/model/item/LinkExternalIssueRQ.java new file mode 100644 index 0000000000..3663be9c81 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/item/LinkExternalIssueRQ.java @@ -0,0 +1,56 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.item; + +import com.epam.ta.reportportal.ws.reporting.Issue; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import java.util.List; +import javax.validation.Valid; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.Size; + +/** + * Request model for add link to external system issue + * + * @author Dzmitry_Kavalets + * @author Andrei_Ramanchuk + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class LinkExternalIssueRQ extends ExternalIssueRQ { + + @NotEmpty + @Valid + @Size(max = 300) + @JsonProperty(value = "issues") + @Schema(implementation = Issue.ExternalSystemIssue.class) + private List issues; + + public void setIssues(List values) { + this.issues = values; + } + + public List getIssues() { + return issues; + } + + @Override + public String toString() { + return "LinkExternalIssueRQ{" + "issues=" + issues + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/item/UnlinkExternalIssueRQ.java b/src/main/java/com/epam/ta/reportportal/model/item/UnlinkExternalIssueRQ.java new file mode 100644 index 0000000000..e954a5f22c --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/item/UnlinkExternalIssueRQ.java @@ -0,0 +1,55 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.item; + +import com.epam.ta.reportportal.ws.annotations.NotBlankStringCollection; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.validation.Valid; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.Size; + +/** + * @author Pavel Bortnik + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UnlinkExternalIssueRQ extends ExternalIssueRQ { + + @Valid + @NotEmpty + @NotBlankStringCollection + @Size(max = 300) + @JsonProperty(value = "ticketIds") + private List ticketIds; + + public List getTicketIds() { + return ticketIds; + } + + public void setTicketIds(List ticketIds) { + this.ticketIds = ticketIds; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("UnlinkExternalIssueRQ{"); + sb.append("ticketIds=").append(ticketIds); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/item/UpdateTestItemRQ.java b/src/main/java/com/epam/ta/reportportal/model/item/UpdateTestItemRQ.java new file mode 100644 index 0000000000..d623d206f5 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/item/UpdateTestItemRQ.java @@ -0,0 +1,68 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.item; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_PARAMETERS_LENGTH; + +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Set; +import javax.validation.Valid; +import javax.validation.constraints.Size; + +/** + * @author Dzmitry_Kavalets + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UpdateTestItemRQ { + + @Size(max = MAX_PARAMETERS_LENGTH) + @Valid + @JsonProperty(value = "attributes") + private Set attributes; + + @JsonProperty(value = "description") + private String description; + + @JsonProperty(value = "status") + private String status; + + public Set getAttributes() { + return attributes; + } + + public void setAttributes(Set attributes) { + this.attributes = attributes; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/launch/AnalyzeLaunchRQ.java b/src/main/java/com/epam/ta/reportportal/model/launch/AnalyzeLaunchRQ.java new file mode 100644 index 0000000000..cc8ad497af --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/launch/AnalyzeLaunchRQ.java @@ -0,0 +1,86 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.launch; + +import com.epam.ta.reportportal.ws.annotations.In; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import java.util.List; +import javax.validation.constraints.NotNull; + +/** + * @author Pavel Bortnik + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AnalyzeLaunchRQ { + + @NotNull + @JsonProperty(value = "launchId", required = true) + @Schema + private Long launchId; + + @NotNull + @JsonProperty(value = "analyzerMode", required = true) + @In(allowedValues = { "all", "launch_name", "current_launch", "previous_launch", "current_and_the_same_name" }) + @Schema(allowableValues = "ALL, LAUNCH_NAME, CURRENT_LAUNCH, PREVIOUS_LAUNCH, CURRENT_AND_THE_SAME_NAME") + private String analyzerHistoryMode; + + @NotNull + @JsonProperty(value = "analyzerTypeName", required = true) + @In(allowedValues = { "autoAnalyzer", "patternAnalyzer" }) + @Schema(allowableValues = "autoAnalyzer, patternAnalyzer") + private String analyzerTypeName; + + @NotNull + @JsonProperty(value = "analyzeItemsMode", required = true) + @In(allowedValues = { "to_investigate", "auto_analyzed", "manually_analyzed" }) + @Schema(allowableValues = "TO_INVESTIGATE, AUTO_ANALYZED, MANUALLY_ANALYZED") + private List analyzeItemsModes; + + public Long getLaunchId() { + return launchId; + } + + public void setLaunchId(Long launchId) { + this.launchId = launchId; + } + + public String getAnalyzerHistoryMode() { + return analyzerHistoryMode; + } + + public String getAnalyzerTypeName() { + return analyzerTypeName; + } + + public void setAnalyzerTypeName(String analyzerTypeName) { + this.analyzerTypeName = analyzerTypeName; + } + + public void setAnalyzerHistoryMode(String analyzerHistoryMode) { + this.analyzerHistoryMode = analyzerHistoryMode; + } + + public List getAnalyzeItemsModes() { + return analyzeItemsModes; + } + + public void setAnalyzeItemsModes(List analyzeItemsModes) { + this.analyzeItemsModes = analyzeItemsModes; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/launch/FinishLaunchRS.java b/src/main/java/com/epam/ta/reportportal/model/launch/FinishLaunchRS.java new file mode 100644 index 0000000000..85bae068fc --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/launch/FinishLaunchRS.java @@ -0,0 +1,69 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.launch; + +import com.epam.ta.reportportal.ws.reporting.EntryCreatedAsyncRS; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Response model of launch start resource + * + * @author Andrei Varabyeu + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class FinishLaunchRS extends EntryCreatedAsyncRS { + + @JsonProperty("number") + private Long number; + + @JsonProperty("link") + private String link; + + public FinishLaunchRS() { + } + + public FinishLaunchRS(String id, Long number, String link) { + super(id); + this.number = number; + this.link = link; + } + + public Long getNumber() { + return number; + } + + public void setNumber(Long number) { + this.number = number; + } + + public String getLink() { + return link; + } + + public void setLink(String link) { + this.link = link; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("FinishLaunchRS{"); + sb.append("number=").append(number); + sb.append(", link='").append(link).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/launch/LaunchImportRQ.java b/src/main/java/com/epam/ta/reportportal/model/launch/LaunchImportRQ.java new file mode 100644 index 0000000000..4513626ffc --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/launch/LaunchImportRQ.java @@ -0,0 +1,102 @@ +/* + * Copyright 2023 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.launch; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_NAME_LENGTH; +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_PARAMETERS_LENGTH; +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_LAUNCH_NAME_LENGTH; + +import com.epam.ta.reportportal.ws.reporting.ItemAttributesRQ; +import com.epam.ta.reportportal.ws.reporting.Mode; +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import java.util.Date; +import java.util.Set; +import javax.validation.Valid; +import javax.validation.constraints.Size; +import lombok.Data; + +/** + * @author Pavel Bortnik + */ +@Data +public class LaunchImportRQ { + + @JsonProperty(value = "name") + @Schema + @Size(min = MIN_LAUNCH_NAME_LENGTH, max = MAX_NAME_LENGTH) + protected String name; + + @JsonProperty(value = "description") + private String description; + + @Size(max = MAX_PARAMETERS_LENGTH) + @Valid + @JsonProperty("attributes") + @JsonAlias({ "attributes", "tags" }) + private Set attributes; + + @JsonProperty + @JsonAlias({ "startTime", "start_time" }) + @Schema + private Date startTime; + + @JsonProperty("mode") + private Mode mode; + + 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 Set getAttributes() { + return attributes; + } + + public void setAttributes( + Set attributes) { + this.attributes = attributes; + } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Mode getMode() { + return mode; + } + + public void setMode(Mode mode) { + this.mode = mode; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/launch/UpdateLaunchRQ.java b/src/main/java/com/epam/ta/reportportal/model/launch/UpdateLaunchRQ.java new file mode 100644 index 0000000000..666c4c6ec2 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/launch/UpdateLaunchRQ.java @@ -0,0 +1,82 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.launch; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_PARAMETERS_LENGTH; + +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.Mode; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import java.util.Set; +import javax.validation.Valid; +import javax.validation.constraints.Size; + +/** + * Domain object for updating launch object. + * + * @author Aliaksei_Makayed + */ +@JsonInclude(Include.NON_NULL) +public class UpdateLaunchRQ { + + @JsonProperty("mode") + @Schema(allowableValues = "DEFAULT, DEBUG") + private Mode mode; + + @JsonProperty("description") + private String description; + + @Size(max = MAX_PARAMETERS_LENGTH) + @Valid + @JsonProperty("attributes") + private Set attributes; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Set getAttributes() { + return attributes; + } + + public void setAttributes(Set attributes) { + this.attributes = attributes; + } + + public Mode getMode() { + return mode; + } + + public void setMode(Mode mode) { + this.mode = mode; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("UpdateLaunchRQ{"); + sb.append("mode=").append(mode); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/launch/cluster/CreateClustersRQ.java b/src/main/java/com/epam/ta/reportportal/model/launch/cluster/CreateClustersRQ.java new file mode 100644 index 0000000000..3e9a5db893 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/launch/cluster/CreateClustersRQ.java @@ -0,0 +1,54 @@ +/* + * Copyright 2021 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.launch.cluster; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.validation.constraints.NotNull; + +/** + * @author Ivan Budayeu + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class CreateClustersRQ { + + @NotNull + @JsonProperty(value = "launchId", required = true) + private Long launchId; + + @JsonProperty(value = "removeNumbers") + private boolean removeNumbers; + + public CreateClustersRQ() { + } + + public Long getLaunchId() { + return launchId; + } + + public void setLaunchId(Long launchId) { + this.launchId = launchId; + } + + public boolean isRemoveNumbers() { + return removeNumbers; + } + + public void setRemoveNumbers(boolean removeNumbers) { + this.removeNumbers = removeNumbers; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/log/GetLogsUnderRq.java b/src/main/java/com/epam/ta/reportportal/model/log/GetLogsUnderRq.java new file mode 100644 index 0000000000..8f99ebdcb9 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/log/GetLogsUnderRq.java @@ -0,0 +1,37 @@ +package com.epam.ta.reportportal.model.log; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import java.util.List; +import javax.validation.constraints.NotNull; + +public class GetLogsUnderRq { + + @NotNull + @JsonProperty(value = "itemIds") + private List itemIds; + + @NotNull + @JsonProperty(value = "logLevel") + @Schema(allowableValues = "error, warn, info, debug, trace, fatal, unknown") + private String logLevel; + + public GetLogsUnderRq() { + } + + public List getItemIds() { + return itemIds; + } + + public void setItemIds(List itemIds) { + this.itemIds = itemIds; + } + + public String getLogLevel() { + return logLevel; + } + + public void setLogLevel(String logLevel) { + this.logLevel = logLevel; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/log/LogResource.java b/src/main/java/com/epam/ta/reportportal/model/log/LogResource.java new file mode 100644 index 0000000000..b5b4655d58 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/log/LogResource.java @@ -0,0 +1,215 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.log; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import java.util.Date; +import javax.validation.constraints.NotNull; + +/** + * JSON Representation of Report Portal's Log domain object + * + * @author Andrei Varabyeu + */ +@JsonInclude(Include.NON_NULL) +public class LogResource { + + @JsonInclude(Include.NON_NULL) + public static class BinaryContent { + + @NotNull + @JsonProperty(value = "id", required = true) + private String binaryDataId; + + @JsonProperty(value = "thumbnailId", required = true) + private String thumbnailId; + + @JsonProperty(value = "contentType", required = true) + private String contentType; + + /** + * @return the binaryDataId + */ + public String getBinaryDataId() { + return binaryDataId; + } + + /** + * @param binaryDataId the binaryDataId to set + */ + public void setBinaryDataId(String binaryDataId) { + this.binaryDataId = binaryDataId; + } + + /** + * @return the thumbnailId + */ + public String getThumbnailId() { + return thumbnailId; + } + + /** + * @param thumbnailId the thumbnailId to set + */ + public void setThumbnailId(String thumbnailId) { + this.thumbnailId = thumbnailId; + } + + /** + * @return the contentType + */ + public String getContentType() { + return contentType; + } + + /** + * @param contentType the contentType to set + */ + public void setContentType(String contentType) { + this.contentType = contentType; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("BinaryContent{"); + sb.append("binaryDataId='").append(binaryDataId).append('\''); + sb.append(", thumbnailId='").append(thumbnailId).append('\''); + sb.append(", contentType='").append(contentType).append('\''); + sb.append('}'); + return sb.toString(); + } + } + + @JsonProperty(value = "id", required = true) + private Long id; + + @JsonProperty(value = "uuid", required = true) + private String uuid; + + @JsonProperty(value = "time") + private Date logTime; + + @JsonProperty(value = "message") + private String message; + + @JsonProperty(value = "binaryContent") + private BinaryContent binaryContent; + + @JsonProperty(value = "thumbnail") + private String thumbnail; + + @JsonProperty(value = "level") + @Schema(allowableValues = "error, warn, info, debug, trace, fatal, unknown") + private String level; + + @JsonProperty(value = "itemId") + private Long itemId; + + @JsonProperty(value = "launchId") + private Long launchId; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Date getLogTime() { + return logTime; + } + + public String getUuid() { + return uuid; + } + + public Long getLaunchId() { + return launchId; + } + + public void setLaunchId(Long launchId) { + this.launchId = launchId; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public void setLogTime(Date logTime) { + this.logTime = logTime; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public Long getItemId() { + return itemId; + } + + public void setItemId(Long itemId) { + this.itemId = itemId; + } + + public String getThumbnail() { + return thumbnail; + } + + public void setThumbnail(String thumbnail) { + this.thumbnail = thumbnail; + } + + public void setBinaryContent(BinaryContent binaryContent) { + this.binaryContent = binaryContent; + } + + public BinaryContent getBinaryContent() { + return binaryContent; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("LogResource{"); + sb.append("id=").append(id); + sb.append(", uuid='").append(uuid).append('\''); + sb.append(", logTime=").append(logTime); + sb.append(", message='").append(message).append('\''); + sb.append(", binaryContent=").append(binaryContent); + sb.append(", thumbnail='").append(thumbnail).append('\''); + sb.append(", level='").append(level).append('\''); + sb.append(", itemId=").append(itemId); + sb.append(", launchId=").append(launchId); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/log/SearchLogRq.java b/src/main/java/com/epam/ta/reportportal/model/log/SearchLogRq.java new file mode 100644 index 0000000000..abce24c779 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/log/SearchLogRq.java @@ -0,0 +1,63 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.log; + +import com.epam.ta.reportportal.ws.annotations.In; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import javax.validation.constraints.NotNull; + +/** + * @author Ihar Kahadouski + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class SearchLogRq { + + @NotNull + @JsonProperty(value = "searchMode", required = true) + @In(allowedValues = { "launchName", "currentLaunch", "filer" }) + @Schema(allowableValues = "currentLaunch, launchName, filter") + private String searchMode; + + private Long filterId; + + public String getSearchMode() { + return searchMode; + } + + public void setSearchMode(String searchMode) { + this.searchMode = searchMode; + } + + public Long getFilterId() { + return filterId; + } + + public void setFilterId(Long filterId) { + this.filterId = filterId; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("SearchLogRq{"); + sb.append("searchMode='").append(searchMode).append('\''); + sb.append(", filterId=").append(filterId); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/log/SearchLogRs.java b/src/main/java/com/epam/ta/reportportal/model/log/SearchLogRs.java new file mode 100644 index 0000000000..cc2d25969e --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/log/SearchLogRs.java @@ -0,0 +1,188 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.log; + +import com.epam.ta.reportportal.ws.reporting.Issue; +import com.epam.ta.reportportal.ws.reporting.PathNameResource; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Set; + +/** + * @author Ihar Kahadouski + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class SearchLogRs { + + @JsonProperty(value = "launchId") + private Long launchId; + + @JsonProperty(value = "itemId") + private Long itemId; + + @JsonProperty(value = "itemName") + private String itemName; + + @JsonProperty(value = "path") + private String path; + + @JsonProperty(value = "pathNames") + private PathNameResource pathNames; + + @JsonProperty(value = "duration") + private double duration; + + @JsonProperty(value = "status") + private String status; + + @JsonProperty(value = "issue") + private Issue issue; + + @JsonProperty(value = "patternTemplates") + private Set patternTemplates; + + @JsonProperty(value = "logs") + private List logs; + + public static class LogEntry { + private String message; + private String level; + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("LogEntry{"); + sb.append("message='").append(message).append('\''); + sb.append(", level='").append(level).append('\''); + sb.append('}'); + return sb.toString(); + } + } + + public Long getLaunchId() { + return launchId; + } + + public void setLaunchId(Long launchId) { + this.launchId = launchId; + } + + public PathNameResource getPathNames() { + return pathNames; + } + + public void setPathNames(PathNameResource pathNames) { + this.pathNames = pathNames; + } + + public Set getPatternTemplates() { + return patternTemplates; + } + + public void setPatternTemplates(Set patternTemplates) { + this.patternTemplates = patternTemplates; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public Long getItemId() { + return itemId; + } + + public void setItemId(Long itemId) { + this.itemId = itemId; + } + + public String getItemName() { + return itemName; + } + + public void setItemName(String itemName) { + this.itemName = itemName; + } + + public double getDuration() { + return duration; + } + + public void setDuration(double duration) { + this.duration = duration; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public Issue getIssue() { + return issue; + } + + public void setIssue(Issue issue) { + this.issue = issue; + } + + public List getLogs() { + return logs; + } + + public void setLogs(List logs) { + this.logs = logs; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("SearchLogRs{"); + sb.append(", launchId=").append(launchId); + sb.append(", itemId=").append(itemId); + sb.append(", itemName='").append(itemName).append('\''); + sb.append(", path='").append(path).append('\''); + sb.append(", pathNames=").append(pathNames); + sb.append(", duration=").append(duration); + sb.append(", status='").append(status).append('\''); + sb.append(", issue=").append(issue); + sb.append(", patternTemplates=").append(patternTemplates); + sb.append(", logs=").append(logs); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/notification/EmailNotificationRQ.java b/src/main/java/com/epam/ta/reportportal/model/notification/EmailNotificationRQ.java new file mode 100644 index 0000000000..3c7944ff84 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/notification/EmailNotificationRQ.java @@ -0,0 +1,72 @@ +/* + * Copyright 2023 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.notification; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import javax.validation.constraints.NotNull; + +/** + * @author Andrei Piankouski + */ +public class EmailNotificationRQ { + + @NotNull + @JsonProperty(value = "recipient") + private String recipient; + + @NotNull + @JsonProperty(value = "template") + private String template; + + @JsonProperty(value = "params") + private Map params; + + + public String getRecipient() { + return recipient; + } + + public void setRecipient(String recipient) { + this.recipient = recipient; + } + + public String getTemplate() { + return template; + } + + public void setTemplate(String template) { + this.template = template; + } + + public Map getParams() { + return params; + } + + public void setParams(Map params) { + this.params = params; + } + + @Override + public String toString() { + return "EmailNotificationRQ{" + + "recipient='" + recipient + '\'' + + ", template='" + template + '\'' + + ", params=" + params + + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/preference/PreferenceResource.java b/src/main/java/com/epam/ta/reportportal/model/preference/PreferenceResource.java new file mode 100644 index 0000000000..c180882046 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/preference/PreferenceResource.java @@ -0,0 +1,70 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.preference; + +import com.epam.ta.reportportal.model.filter.UserFilterResource; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/** + * JSON representation of report portal domain object + * + * @author Dzmitry_Kavalets + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class PreferenceResource { + + @JsonProperty(value = "userId") + private Long userId; + + @JsonProperty(value = "projectId", required = true) + private Long projectId; + + @JsonProperty(value = "filters") + private List filters; + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public List getFilters() { + return filters; + } + + public void setFilters(List filters) { + this.filters = filters; + } + + @Override + public String toString() { + return "PreferenceResource{" + "userId=" + userId + ", projectId=" + projectId + ", filters=" + filters + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/AssignUsersRQ.java b/src/main/java/com/epam/ta/reportportal/model/project/AssignUsersRQ.java new file mode 100644 index 0000000000..7bcad4688e --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/AssignUsersRQ.java @@ -0,0 +1,52 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import javax.validation.constraints.NotNull; + +/** + * Assign users from project request model + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class AssignUsersRQ { + + @NotNull + @JsonProperty(value = "userNames", required = true) + private Map userNames; + + public void setUserNames(Map value) { + this.userNames = value; + } + + public Map getUserNames() { + return userNames; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("AssignUsersRQ{"); + sb.append("userNames=").append(userNames.keySet()); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/project/CreateProjectRQ.java b/src/main/java/com/epam/ta/reportportal/model/project/CreateProjectRQ.java new file mode 100644 index 0000000000..de4719104c --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/CreateProjectRQ.java @@ -0,0 +1,78 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.PROJECT_NAME_REGEXP; + +import com.epam.ta.reportportal.ws.annotations.In; +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +/** + * Create project request initial model + * + * @author Hanna_Sukhadolava + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class CreateProjectRQ { + + @NotBlank + @Pattern(regexp = PROJECT_NAME_REGEXP) + @Size(min = ValidationConstraints.MIN_NAME_LENGTH, max = ValidationConstraints.MAX_NAME_LENGTH) + @JsonProperty(value = "projectName", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED, example = "string") + private String projectName; + + @NotBlank + @JsonProperty(value = "entryType", required = true) + @In(allowedValues = "internal") + @Schema(required = true, allowableValues = "INTERNAL") + private String entryType; + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public String getEntryType() { + return entryType; + } + + public void setEntryType(String value) { + this.entryType = value; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("CreateProjectRQ{"); + sb.append("projectName='").append(projectName).append('\''); + sb.append(", entryType='").append(entryType).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/DeleteProjectRQ.java b/src/main/java/com/epam/ta/reportportal/model/project/DeleteProjectRQ.java new file mode 100644 index 0000000000..a11bd91491 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/DeleteProjectRQ.java @@ -0,0 +1,74 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.PROJECT_NAME_REGEXP; + +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +/** + * @author Ivan Budayeu + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class DeleteProjectRQ { + + @NotBlank + @JsonProperty(value = "projectName", required = true) + @Pattern(regexp = PROJECT_NAME_REGEXP) + @Size(min = ValidationConstraints.MIN_NAME_LENGTH, max = ValidationConstraints.MAX_NAME_LENGTH) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String projectName; + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + DeleteProjectRQ that = (DeleteProjectRQ) o; + + return projectName.equals(that.projectName); + } + + @Override + public int hashCode() { + return projectName.hashCode(); + } + + @Override + public String toString() { + return "DeleteProjectRQ{" + "projectName='" + projectName + '\'' + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/LaunchesPerUser.java b/src/main/java/com/epam/ta/reportportal/model/project/LaunchesPerUser.java new file mode 100644 index 0000000000..429cab8efb --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/LaunchesPerUser.java @@ -0,0 +1,61 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Basic representation of launches information per user for specified project
+ * Current view is:
+ * String:user_id : {String:fullname, Integer:launchesCount}
+ * + * @author Andrei_Ramanchuk + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class LaunchesPerUser { + + @JsonProperty(value = "fullName") + private String fullUsername; + + @JsonProperty(value = "count") + private Integer launchCount; + + public LaunchesPerUser() { + } + + public LaunchesPerUser(String fullname, Integer count) { + this.fullUsername = fullname; + this.launchCount = count; + } + + public void setFullUsername(String value) { + this.fullUsername = value; + } + + public String getFullUsername() { + return fullUsername; + } + + public void setLaunchCount(Integer value) { + this.launchCount = value; + } + + public Integer getLaunchCount() { + return launchCount; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/project/ProjectConfiguration.java b/src/main/java/com/epam/ta/reportportal/model/project/ProjectConfiguration.java new file mode 100644 index 0000000000..12c848c569 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/ProjectConfiguration.java @@ -0,0 +1,79 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project; + +import com.epam.ta.reportportal.model.project.config.IssueSubTypeResource; +import com.epam.ta.reportportal.model.project.config.pattern.PatternTemplateResource; +import com.epam.ta.reportportal.model.project.email.ProjectNotificationConfigDTO; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Map; + +/** + * Project configuration model + * + * @author Pavel Bortnik + */ +@JsonInclude(Include.NON_NULL) +public class ProjectConfiguration { + + @JsonProperty(value = "attributes", required = true) + private Map projectAttributes; + + @JsonProperty(value = "subTypes") + private Map> subTypes; + + @JsonProperty(value = "notificationsConfiguration") + private ProjectNotificationConfigDTO projectConfig; + + @JsonProperty(value = "patterns") + private List patterns; + + public Map getProjectAttributes() { + return projectAttributes; + } + + public void setProjectAttributes(Map projectAttributes) { + this.projectAttributes = projectAttributes; + } + + public Map> getSubTypes() { + return subTypes; + } + + public void setSubTypes(Map> subTypes) { + this.subTypes = subTypes; + } + + public ProjectNotificationConfigDTO getProjectConfig() { + return projectConfig; + } + + public void setProjectConfig(ProjectNotificationConfigDTO projectConfig) { + this.projectConfig = projectConfig; + } + + public List getPatterns() { + return patterns; + } + + public void setPatterns(List patterns) { + this.patterns = patterns; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/ProjectInfoResource.java b/src/main/java/com/epam/ta/reportportal/model/project/ProjectInfoResource.java new file mode 100644 index 0000000000..1e6e3c3a84 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/ProjectInfoResource.java @@ -0,0 +1,171 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project; + +import com.epam.ta.reportportal.model.ModelViews; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonView; +import java.util.Date; +import java.util.List; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +/** + * Project info resource representation for responses
+ * {@link ModelViews.DefaultView} used as + * default fields output
+ * {@link ModelViews.FullProjectInfoView} used + * as extended fields output
+ * + * @author Dzmitry_Kavalets + * @author Andrei_Ramanchuk + */ +public class ProjectInfoResource { + + @NotNull + @JsonProperty(value = "id") + private Long projectId; + + @NotBlank + @JsonProperty(value = "projectName") + private String projectName; + + @NotNull + @JsonProperty(value = "usersQuantity") + private Integer usersQuantity; + + @NotNull + @JsonProperty(value = "launchesQuantity") + private Integer launchesQuantity; + + @JsonProperty(value = "launchesPerUser") + @JsonView(ModelViews.FullProjectInfoView.class) + private List launchesPerUser; + + @JsonProperty(value = "uniqueTickets") + @JsonView(ModelViews.FullProjectInfoView.class) + private Integer uniqueTickets; + + @JsonProperty(value = "launchesPerWeek") + @JsonView(ModelViews.FullProjectInfoView.class) + private String launchesPerWeek; + + @NotNull + @JsonProperty(value = "lastRun") + private Date lastRun; + + @NotNull + @JsonProperty(value = "creationDate") + private Date creationDate; + + @JsonProperty(value = "entryType") + private String entryType; + + @JsonProperty(value = "organization") + private String organization; + + public ProjectInfoResource() { + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public Integer getUsersQuantity() { + return usersQuantity; + } + + public void setUsersQuantity(Integer usersQuantity) { + this.usersQuantity = usersQuantity; + } + + public Integer getLaunchesQuantity() { + return launchesQuantity; + } + + public void setLaunchesQuantity(Integer launchesQuantity) { + this.launchesQuantity = launchesQuantity; + } + + public void setLaunchesPerUser(List value) { + this.launchesPerUser = value; + } + + public List getLaunchesPerUser() { + return launchesPerUser; + } + + public void setUniqueTickets(Integer value) { + this.uniqueTickets = value; + } + + public Integer getUniqueTickets() { + return uniqueTickets; + } + + public void setLaunchesPerWeek(String value) { + this.launchesPerWeek = value; + } + + public String getLaunchesPerWeek() { + return launchesPerWeek; + } + + public Date getLastRun() { + return lastRun; + } + + public void setLastRun(Date lastRun) { + this.lastRun = lastRun; + } + + public Date getCreationDate() { + return creationDate; + } + + public void setCreationDate(Date creationDate) { + this.creationDate = creationDate; + } + + public String getEntryType() { + return entryType; + } + + public void setEntryType(String entryType) { + this.entryType = entryType; + } + + public String getOrganization() { + return organization; + } + + public void setOrganization(String organization) { + this.organization = organization; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/ProjectResource.java b/src/main/java/com/epam/ta/reportportal/model/project/ProjectResource.java new file mode 100644 index 0000000000..0702c6a410 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/ProjectResource.java @@ -0,0 +1,165 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project; + +import com.epam.ta.reportportal.model.integration.IntegrationResource; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Date; +import java.util.List; +import javax.validation.constraints.NotNull; + +/** + * Project resource representation for responses + * + * @author Pavel Bortnik + */ +public class ProjectResource { + + @NotNull + @JsonProperty(value = "projectId", required = true) + private Long projectId; + + @NotNull + @JsonProperty(value = "projectName", required = true) + private String projectName; + + @JsonProperty(value = "entryType", required = true) + private String entryType; + + @NotNull + @JsonProperty(value = "configuration", required = true) + private ProjectConfiguration configuration; + + @JsonProperty(value = "users") + private List users; + + @JsonProperty(value = "integrations") + private List integrations; + + @JsonProperty(value = "organization") + private String organization; + + @JsonProperty(value = "allocatedStorage") + private Long allocatedStorage; + + @NotNull + @JsonProperty(value = "creationDate") + private Date creationDate; + + public Date getCreationDate() { + return creationDate; + } + + public void setCreationDate(Date creationDate) { + this.creationDate = creationDate; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public String getEntryType() { + return entryType; + } + + public void setEntryType(String entryType) { + this.entryType = entryType; + } + + public void setConfiguration( + ProjectConfiguration configuration) { + this.configuration = configuration; + } + + public ProjectConfiguration getConfiguration() { + return configuration; + } + + public List getIntegrations() { + return integrations; + } + + public void setIntegrations(List integrations) { + this.integrations = integrations; + } + + public List getUsers() { + return users; + } + + public void setUsers(List users) { + this.users = users; + } + + public String getOrganization() { + return organization; + } + + public void setOrganization(String organization) { + this.organization = organization; + } + + public Long getAllocatedStorage() { + return allocatedStorage; + } + + public void setAllocatedStorage(Long allocatedStorage) { + this.allocatedStorage = allocatedStorage; + } + + public static class ProjectUser { + + @JsonProperty(value = "login") + private String login; + + @JsonProperty(value = "projectRole") + private String projectRole; + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public void setProjectRole(String value) { + this.projectRole = value; + } + + public String getProjectRole() { + return projectRole; + } + + @Override + public String toString() { + return "ProjectUser{" + "projectRole='" + projectRole + '\'' + '}'; + } + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/UnassignUsersRQ.java b/src/main/java/com/epam/ta/reportportal/model/project/UnassignUsersRQ.java new file mode 100644 index 0000000000..c15bc1c33f --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/UnassignUsersRQ.java @@ -0,0 +1,55 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import java.util.List; +import javax.validation.constraints.NotEmpty; + +/** + * Un-assign users request template + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class UnassignUsersRQ { + + @NotEmpty + @JsonProperty(value = "userNames", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private List usernames; + + public void setUsernames(List value) { + this.usernames = value; + } + + public List getUsernames() { + return usernames; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("UnassignUsersRQ{"); + sb.append("usernames=").append(usernames); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/project/UniqueErrorConfig.java b/src/main/java/com/epam/ta/reportportal/model/project/UniqueErrorConfig.java new file mode 100644 index 0000000000..4398381a1e --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/UniqueErrorConfig.java @@ -0,0 +1,36 @@ +package com.epam.ta.reportportal.model.project; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Ivan Budayeu + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UniqueErrorConfig { + + @JsonProperty(value = "isAutoAnalyzerEnabled") + private boolean enabled; + + @JsonProperty(value = "isAutoAnalyzerEnabled") + private boolean removeNumbers; + + public UniqueErrorConfig() { + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public boolean isRemoveNumbers() { + return removeNumbers; + } + + public void setRemoveNumbers(boolean removeNumbers) { + this.removeNumbers = removeNumbers; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/UpdateProjectRQ.java b/src/main/java/com/epam/ta/reportportal/model/project/UpdateProjectRQ.java new file mode 100644 index 0000000000..2bc9dc8974 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/UpdateProjectRQ.java @@ -0,0 +1,71 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project; + +import com.epam.ta.reportportal.model.project.config.ProjectConfigurationUpdate; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import javax.validation.Valid; + +/** + * Update project request model + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class UpdateProjectRQ { + + @JsonProperty(value = "users") + private Map userRoles; + + @Valid + @JsonProperty(value = "configuration") + private ProjectConfigurationUpdate configuration; + + /** + * @return the userRoles + */ + public Map getUserRoles() { + return userRoles; + } + + /** + * @param userRoles the userRoles to set + */ + public void setUserRoles(Map userRoles) { + this.userRoles = userRoles; + } + + public ProjectConfigurationUpdate getConfiguration() { + return configuration; + } + + public void setConfiguration(ProjectConfigurationUpdate configuration) { + this.configuration = configuration; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("UpdateProjectRQ{"); + sb.append(", userRoles=").append(userRoles); + sb.append(", configuration=").append(configuration); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/project/config/CreateIssueSubTypeRQ.java b/src/main/java/com/epam/ta/reportportal/model/project/config/CreateIssueSubTypeRQ.java new file mode 100644 index 0000000000..92432061c0 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/config/CreateIssueSubTypeRQ.java @@ -0,0 +1,93 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project.config; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.HEX_COLOR_REGEXP; + +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +/** + * Request model for new issue sub type for specified project.
+ * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class CreateIssueSubTypeRQ { + + @NotBlank + @JsonProperty(value = "typeRef", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String typeRef; + + @NotBlank + @Size(min = ValidationConstraints.MIN_SUBTYPE_LONG_NAME, max = ValidationConstraints.MAX_SUBTYPE_LONG_NAME) + @JsonProperty(value = "longName", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String longName; + + @NotBlank + @Size(min = ValidationConstraints.MIN_SUBTYPE_SHORT_NAME, max = ValidationConstraints.MAX_SUBTYPE_SHORT_NAME) + @JsonProperty(value = "shortName", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED, example = "string") + private String shortName; + + @NotBlank + @Pattern(regexp = HEX_COLOR_REGEXP) + @JsonProperty(value = "color", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED, example = "string") + private String color; + + public void setTypeRef(String typeRef) { + this.typeRef = typeRef; + } + + public String getTypeRef() { + return typeRef; + } + + public void setLongName(String longName) { + this.longName = longName; + } + + public String getLongName() { + return longName; + } + + public void setShortName(String shortName) { + this.shortName = shortName; + } + + public String getShortName() { + return shortName; + } + + public void setColor(String color) { + this.color = color; + } + + public String getColor() { + return color; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/config/IssueSubTypeCreatedRS.java b/src/main/java/com/epam/ta/reportportal/model/project/config/IssueSubTypeCreatedRS.java new file mode 100644 index 0000000000..933c293b03 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/config/IssueSubTypeCreatedRS.java @@ -0,0 +1,47 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project.config; + +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Ivan Budayeu + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class IssueSubTypeCreatedRS extends EntryCreatedRS { + + @JsonProperty(value = "locator") + private String locator; + + public IssueSubTypeCreatedRS() { + } + + public IssueSubTypeCreatedRS(Long id, String locator) { + super(id); + this.locator = locator; + } + + public String getLocator() { + return locator; + } + + public void setLocator(String locator) { + this.locator = locator; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/config/IssueSubTypeResource.java b/src/main/java/com/epam/ta/reportportal/model/project/config/IssueSubTypeResource.java new file mode 100644 index 0000000000..b407b33506 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/config/IssueSubTypeResource.java @@ -0,0 +1,109 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project.config; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Issue sub-type resource representation + * + * @author Andrei_Ramanchuk + * + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class IssueSubTypeResource { + + @JsonProperty(value = "id") + private Long id; + + @JsonProperty(value = "locator") + private String locator; + + @JsonProperty(value = "typeRef") + private String typeRef; + + @JsonProperty(value = "longName") + private String longName; + + @JsonProperty(value = "shortName") + private String shortName; + + @JsonProperty(value = "color") + private String color; + + public IssueSubTypeResource() { + + } + + public IssueSubTypeResource(Long id, String locator, String typeRef, String longName, String shortName, String color) { + this.id = id; + this.locator = locator; + this.typeRef = typeRef; + this.longName = longName; + this.shortName = shortName; + this.color = color; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLocator() { + return locator; + } + + public void setLocator(String locator) { + this.locator = locator; + } + + public String getTypeRef() { + return typeRef; + } + + public void setTypeRef(String typeRef) { + this.typeRef = typeRef; + } + + public String getLongName() { + return longName; + } + + public void setLongName(String longName) { + this.longName = longName; + } + + public String getShortName() { + return shortName; + } + + public void setShortName(String shortName) { + this.shortName = shortName; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/config/ProjectConfigurationUpdate.java b/src/main/java/com/epam/ta/reportportal/model/project/config/ProjectConfigurationUpdate.java new file mode 100644 index 0000000000..db0b625e42 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/config/ProjectConfigurationUpdate.java @@ -0,0 +1,47 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project.config; + +import com.epam.ta.reportportal.ws.annotations.NotNullMapValue; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import javax.validation.constraints.NotNull; + +/** + * Project configuration model + * + * @author Ivan Budayeu + */ +@JsonInclude(Include.NON_NULL) +public class ProjectConfigurationUpdate { + + @NotNull + @NotNullMapValue + @JsonProperty(value = "attributes", required = true) + private Map projectAttributes; + + public Map getProjectAttributes() { + return projectAttributes; + } + + public void setProjectAttributes(Map projectAttributes) { + this.projectAttributes = projectAttributes; + } + +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/config/ProjectSettingsResource.java b/src/main/java/com/epam/ta/reportportal/model/project/config/ProjectSettingsResource.java new file mode 100644 index 0000000000..25af8cc81b --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/config/ProjectSettingsResource.java @@ -0,0 +1,53 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project.config; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Map; + +/** + * Project settings resource output + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ProjectSettingsResource { + + @JsonProperty(value = "project", required = true) + private Long projectId; + + @JsonProperty(value = "subTypes", required = true) + private Map> subTypes; + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public void setSubTypes(Map> types) { + this.subTypes = types; + } + + public Map> getSubTypes() { + return subTypes; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/config/UpdateIssueSubTypeRQ.java b/src/main/java/com/epam/ta/reportportal/model/project/config/UpdateIssueSubTypeRQ.java new file mode 100644 index 0000000000..7e5b0f01f2 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/config/UpdateIssueSubTypeRQ.java @@ -0,0 +1,68 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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. + */ +/* + * This file is part of Report Portal. + * + * Report Portal is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Report Portal is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Report Portal. If not, see . + */ + +package com.epam.ta.reportportal.model.project.config; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import java.util.List; +import javax.validation.Valid; +import javax.validation.constraints.NotEmpty; + +/** + * Request model for existing issue sub type update for specified project.
+ * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class UpdateIssueSubTypeRQ { + + @Valid + @NotEmpty + @JsonProperty(value = "ids", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private List ids; + + public UpdateIssueSubTypeRQ() { + } + + public void setIds(List values) { + this.ids = values; + } + + public List getIds() { + return ids; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/config/UpdateOneIssueSubTypeRQ.java b/src/main/java/com/epam/ta/reportportal/model/project/config/UpdateOneIssueSubTypeRQ.java new file mode 100644 index 0000000000..443d7ccdef --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/config/UpdateOneIssueSubTypeRQ.java @@ -0,0 +1,108 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project.config; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.HEX_COLOR_REGEXP; + +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +/** + * One settings sub-type update request representation + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class UpdateOneIssueSubTypeRQ { + + @NotBlank + @JsonProperty(value = "locator", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String locator; + + @NotBlank + @JsonProperty(value = "typeRef", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String typeRef; + + @NotBlank + @JsonProperty(value = "longName") + @Size(min = ValidationConstraints.MIN_SUBTYPE_LONG_NAME, max = ValidationConstraints.MAX_SUBTYPE_LONG_NAME) + private String longName; + + @NotBlank + @JsonProperty(value = "shortName") + @Size(min = ValidationConstraints.MIN_SUBTYPE_SHORT_NAME, max = ValidationConstraints.MAX_SUBTYPE_SHORT_NAME) + @Schema(requiredMode = RequiredMode.REQUIRED, example = "string") + private String shortName; + + @NotBlank + @Pattern(regexp = HEX_COLOR_REGEXP) + @JsonProperty(value = "color") + @Size(min = ValidationConstraints.MIN_SUBTYPE_LONG_NAME, max = ValidationConstraints.MAX_SUBTYPE_LONG_NAME) + @Schema(requiredMode = RequiredMode.REQUIRED, example = "string") + private String color; + + public UpdateOneIssueSubTypeRQ() { + } + + public String getLocator() { + return locator; + } + + public void setLocator(String locator) { + this.locator = locator; + } + + public void setTypeRef(String typeRef) { + this.typeRef = typeRef; + } + + public String getTypeRef() { + return typeRef; + } + + public void setLongName(String longName) { + this.longName = longName; + } + + public String getLongName() { + return longName; + } + + public void setShortName(String shortName) { + this.shortName = shortName; + } + + public String getShortName() { + return shortName; + } + + public void setColor(String color) { + this.color = color; + } + + public String getColor() { + return color; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/project/config/pattern/CreatePatternTemplateRQ.java b/src/main/java/com/epam/ta/reportportal/model/project/config/pattern/CreatePatternTemplateRQ.java new file mode 100644 index 0000000000..8f2a4e2baf --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/config/pattern/CreatePatternTemplateRQ.java @@ -0,0 +1,90 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project.config.pattern; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_ANALYSIS_PATTERN_NAME_LENGTH; +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_ANALYSIS_PATTERN_NAME_LENGTH; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +/** + * @author Ivan Budayeu + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class CreatePatternTemplateRQ { + + @NotBlank + @Size(min = MIN_ANALYSIS_PATTERN_NAME_LENGTH, max = MAX_ANALYSIS_PATTERN_NAME_LENGTH) + @JsonProperty(value = "name") + private String name; + + @NotBlank + @JsonProperty(value = "value") + private String value; + + @NotBlank + @JsonProperty(value = "type") + private String type; + + @NotNull + @JsonProperty(value = "enabled") + private Boolean enabled; + + public CreatePatternTemplateRQ() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + @Override + public String toString() { + return "UpdatePatternTemplateRQ{" + "name='" + name + '\'' + ", value='" + value + '\'' + ", type='" + type + '\'' + ", enabled=" + enabled + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/config/pattern/PatternTemplateResource.java b/src/main/java/com/epam/ta/reportportal/model/project/config/pattern/PatternTemplateResource.java new file mode 100644 index 0000000000..7f06ea87c3 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/config/pattern/PatternTemplateResource.java @@ -0,0 +1,91 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project.config.pattern; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Ivan Budayeu + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class PatternTemplateResource { + + @JsonProperty(value = "id") + private Long id; + + @JsonProperty(value = "name") + private String name; + + @JsonProperty(value = "value") + private String value; + + @JsonProperty(value = "type") + private String type; + + @JsonProperty(value = "enabled") + private Boolean enabled; + + public PatternTemplateResource() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + @Override + public String toString() { + return "UpdatePatternTemplateRQ{" + "name='" + name + '\'' + ", value='" + value + '\'' + ", type='" + type + '\'' + ", enabled=" + + enabled + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/config/pattern/UpdatePatternTemplateRQ.java b/src/main/java/com/epam/ta/reportportal/model/project/config/pattern/UpdatePatternTemplateRQ.java new file mode 100644 index 0000000000..c5305fad78 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/config/pattern/UpdatePatternTemplateRQ.java @@ -0,0 +1,66 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project.config.pattern; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_ANALYSIS_PATTERN_NAME_LENGTH; +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_ANALYSIS_PATTERN_NAME_LENGTH; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +/** + * @author Ivan Budayeu + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UpdatePatternTemplateRQ { + + @NotBlank + @Size(min = MIN_ANALYSIS_PATTERN_NAME_LENGTH, max = MAX_ANALYSIS_PATTERN_NAME_LENGTH) + @JsonProperty(value = "name") + private String name; + + @NotNull + @JsonProperty(value = "enabled") + private Boolean enabled; + + public UpdatePatternTemplateRQ() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + @Override + public String toString() { + return "UpdatePatternTemplateRQ{" + "name='" + name + '\'' + ", enabled=" + enabled + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/project/email/ProjectNotificationConfigDTO.java b/src/main/java/com/epam/ta/reportportal/model/project/email/ProjectNotificationConfigDTO.java new file mode 100644 index 0000000000..c7dec9d606 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/email/ProjectNotificationConfigDTO.java @@ -0,0 +1,74 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project.email; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.io.Serializable; +import java.util.List; +import javax.validation.Valid; + +/** + * Project notifications configuration object + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class ProjectNotificationConfigDTO implements Serializable { + /** + * Generated SVUID + */ + private static final long serialVersionUID = -961365872944240700L; + + @JsonProperty(value = "enabled") + private boolean enabled; + + @Valid + @JsonProperty(value = "cases") + private List senderCases; + + public ProjectNotificationConfigDTO() { + } + + public ProjectNotificationConfigDTO(boolean enabled, List senderCases) { + this.enabled = enabled; + this.senderCases = senderCases; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public List getSenderCases() { + return senderCases; + } + + public void setSenderCases(List senderCases) { + this.senderCases = senderCases; + } + + @Override + public String toString() { + return "ProjectNotificationConfigDTO{" + "enabled=" + enabled + ", senderCases=" + senderCases + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/project/email/SenderCaseDTO.java b/src/main/java/com/epam/ta/reportportal/model/project/email/SenderCaseDTO.java new file mode 100644 index 0000000000..2b7d6bf4e6 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/project/email/SenderCaseDTO.java @@ -0,0 +1,185 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.project.email; + +import com.epam.ta.reportportal.ws.annotations.In; +import com.epam.ta.reportportal.ws.annotations.NotBlankStringCollection; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import java.io.Serializable; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import javax.validation.Valid; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotEmpty; + +/** + * Cases object for notifications sending declarations + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class SenderCaseDTO implements Serializable { + /** + * Generated SVUID + */ + private static final long serialVersionUID = -3546546654348861010L; + + @JsonProperty("id") + private Long id; + + @NotEmpty + @JsonProperty("ruleName") + private String ruleName; + + @NotEmpty + @NotBlankStringCollection + @JsonProperty(value = "recipients") + private List recipients; + + @NotBlank + @JsonProperty(value = "sendCase") + @In(allowedValues = { "always", "failed", "toInvestigate", "more10", "more20", "more50" }) + @Schema(allowableValues = { "always", "failed", "toInvestigate", "more10", "more20", "more50" }) + private String sendCase; + + @NotBlankStringCollection + @JsonProperty(value = "launchNames") + private List launchNames; + + @Valid + @JsonProperty(value = "attributes") + private Set attributes; + + @JsonProperty(value = "enabled") + private boolean enabled; + + @NotBlank + @JsonProperty(value = "attributesOperator") + @In(allowedValues = { "and", "or" }) + @Schema(allowableValues = "AND, OR") + private String attributesOperator; + + public SenderCaseDTO() { + } + + public SenderCaseDTO(Long id, String ruleName, List recs, String sendMode, + List laNames, Set attributes, boolean enabled) { + this.id = id; + this.ruleName = ruleName; + this.recipients = recs; + this.sendCase = sendMode; + this.launchNames = laNames; + this.attributes = attributes; + this.enabled = enabled; + } + + /* Getters and setters block */ + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getRuleName() { + return ruleName; + } + + public void setRuleName(String ruleName) { + this.ruleName = ruleName; + } + + public void setRecipients(List recipients) { + this.recipients = recipients; + } + + public List getRecipients() { + return recipients; + } + + public void setSendCase(String value) { + this.sendCase = value; + } + + public String getSendCase() { + return sendCase; + } + + public void setLaunchNames(List value) { + this.launchNames = value; + } + + public List getLaunchNames() { + return launchNames; + } + + public Set getAttributes() { + return attributes; + } + + public void setAttributes(Set attributes) { + this.attributes = attributes; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getAttributesOperator() { + return attributesOperator; + } + + public void setAttributesOperator(String attributesOperator) { + this.attributesOperator = attributesOperator; + } + + /* Auto generated methods */ + @Override + public String toString() { + return "SenderCaseDTO{" + "recipients=" + recipients + ", sendCase='" + sendCase + '\'' + + ", launchNames=" + launchNames + ", attributes=" + attributes + ", enabled=" + enabled + ", attributesOperator=" + attributesOperator + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SenderCaseDTO that = (SenderCaseDTO) o; + return Objects.equals(recipients, that.recipients) && Objects.equals(sendCase, that.sendCase) + && Objects.equals(launchNames, that.launchNames) && Objects.equals(attributes, that.attributes) + && Objects.equals(enabled, that.enabled) && Objects.equals(attributesOperator, that.attributesOperator); + } + + @Override + public int hashCode() { + return Objects.hash(recipients, sendCase, launchNames, attributes, enabled, attributesOperator); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/role/SaveRoleRQ.java b/src/main/java/com/epam/ta/reportportal/model/role/SaveRoleRQ.java new file mode 100644 index 0000000000..6d8b297771 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/role/SaveRoleRQ.java @@ -0,0 +1,65 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.role; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.validation.constraints.NotNull; + +/** + * + * @author Siarhei_Kharlanau + * + */ +@JsonInclude(Include.NON_NULL) +public class SaveRoleRQ { + + @NotNull + @JsonProperty(value = "roleName", required = true) + private String roleName; + + @NotNull + @JsonProperty(value = "permissions", required = true) + private String permissions; + + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + public String getPermissions() { + return permissions; + } + + public void setPermissions(String permissions) { + this.permissions = permissions; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("SaveRoleRQ{"); + sb.append("roleName='").append(roleName).append('\''); + sb.append(", permissions='").append(permissions).append('\''); + sb.append('}'); + return sb.toString(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/settings/AnalyticsResource.java b/src/main/java/com/epam/ta/reportportal/model/settings/AnalyticsResource.java new file mode 100644 index 0000000000..27877551b2 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/settings/AnalyticsResource.java @@ -0,0 +1,63 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.settings; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import java.io.Serializable; +import javax.validation.constraints.NotBlank; + +@JsonInclude(Include.NON_NULL) +public class AnalyticsResource implements Serializable { + + private Boolean enabled; + + @NotBlank + private String type; + + public AnalyticsResource() { + } + + public AnalyticsResource(Boolean enabled) { + this.enabled = enabled; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("AnalyticsResource{"); + sb.append(", enabled=").append(enabled); + sb.append(", type='").append(type).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/settings/ServerEmailResource.java b/src/main/java/com/epam/ta/reportportal/model/settings/ServerEmailResource.java new file mode 100644 index 0000000000..d3a557dce5 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/settings/ServerEmailResource.java @@ -0,0 +1,170 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.settings; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import java.io.Serializable; +import javax.validation.constraints.NotBlank; + +/** + * Configurable email setting for project object + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class ServerEmailResource implements Serializable { + + /** + * Generated sUID + */ + private static final long serialVersionUID = 2573744596368345366L; + + private boolean enabled = true; + + @NotBlank + private String host; + + private Integer port; + + private String protocol; + + private Boolean authEnabled; + + private Boolean starTlsEnabled; + + private Boolean sslEnabled; + + private String username; + + private String password; + + private String from; + + public ServerEmailResource() { + } + + public ServerEmailResource(Boolean enabled, String host, Integer port, String protocol, Boolean authEnabled, Boolean starTlsEnabled, + Boolean sslEnabled, String username, String password, String from) { + this.enabled = enabled; + this.host = host; + this.port = port; + this.protocol = protocol; + this.authEnabled = authEnabled; + this.starTlsEnabled = starTlsEnabled; + this.sslEnabled = sslEnabled; + this.username = username; + this.password = password; + this.from = from; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public Integer getPort() { + return port; + } + + public void setPort(Integer port) { + this.port = port; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public Boolean getAuthEnabled() { + return authEnabled; + } + + public void setAuthEnabled(Boolean authEnabled) { + this.authEnabled = authEnabled; + } + + public Boolean getStarTlsEnabled() { + return starTlsEnabled; + } + + public void setStarTlsEnabled(Boolean starTlsEnabled) { + this.starTlsEnabled = starTlsEnabled; + } + + public Boolean getSslEnabled() { + return sslEnabled; + } + + public void setSslEnabled(Boolean sslEnabled) { + this.sslEnabled = sslEnabled; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("ServerEmailResource{"); + sb.append("host='").append(host).append('\''); + sb.append(", port=").append(port); + sb.append(", protocol='").append(protocol).append('\''); + sb.append(", authEnabled=").append(authEnabled); + sb.append(", starTlsEnabled=").append(starTlsEnabled); + sb.append(", sslEnabled=").append(sslEnabled); + sb.append(", username='").append(username).append('\''); + sb.append(", password='").append(password).append('\''); + sb.append(", from='").append(from).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/settings/ServerSettingsResource.java b/src/main/java/com/epam/ta/reportportal/model/settings/ServerSettingsResource.java new file mode 100644 index 0000000000..51c24a23ec --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/settings/ServerSettingsResource.java @@ -0,0 +1,82 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.settings; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; + +/** + * Global server settings response of stored properties + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class ServerSettingsResource { + + private String profile; + + private boolean active; + + @JsonProperty(value = "serverEmailConfig") + private ServerEmailResource serverEmailResource; + + // private Map oauthConfigs; + + private Map analyticsResource; + + public void setProfile(String id) { + this.profile = id; + } + + public String getProfile() { + return profile; + } + + public void setActive(boolean is) { + this.active = is; + } + + public boolean getActive() { + return active; + } + + public void setServerEmailResource(ServerEmailResource config) { + this.serverEmailResource = config; + } + + public ServerEmailResource getServerEmailResource() { + return serverEmailResource; + } + + // public Map getOauthConfigs() { + // return oauthConfigs; + // } + + // public void setOauthConfigs(Map oauthConfigs) { + // this.oauthConfigs = oauthConfigs; + // } + + public Map getAnalyticsResource() { + return analyticsResource; + } + + public void setAnalyticsResource(Map analyticsResource) { + this.analyticsResource = analyticsResource; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/user/ChangePasswordRQ.java b/src/main/java/com/epam/ta/reportportal/model/user/ChangePasswordRQ.java new file mode 100644 index 0000000000..fe1e0f7c51 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/user/ChangePasswordRQ.java @@ -0,0 +1,88 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.user; + +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.fasterxml.jackson.annotation.JsonInclude; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +/** + * @author Dzmitry_Kavalets + */ + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ChangePasswordRQ { + + @NotBlank + @Size(min = ValidationConstraints.MIN_PASSWORD_LENGTH, max = ValidationConstraints.MAX_PASSWORD_LENGTH) + private String newPassword; + + @NotBlank + @Size(min = ValidationConstraints.MIN_PASSWORD_LENGTH, max = ValidationConstraints.MAX_PASSWORD_LENGTH) + private String oldPassword; + + public String getNewPassword() { + return newPassword; + } + + public void setNewPassword(String newPassword) { + this.newPassword = newPassword; + } + + public String getOldPassword() { + return oldPassword; + } + + public void setOldPassword(String oldPassword) { + this.oldPassword = oldPassword; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + ChangePasswordRQ that = (ChangePasswordRQ) o; + + if (newPassword != null ? !newPassword.equals(that.newPassword) : that.newPassword != null) { + return false; + } + return !(oldPassword != null ? !oldPassword.equals(that.oldPassword) : that.oldPassword != null); + + } + + @Override + public int hashCode() { + int result = newPassword != null ? newPassword.hashCode() : 0; + result = 31 * result + (oldPassword != null ? oldPassword.hashCode() : 0); + return result; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("ChangePasswordRQ{"); + sb.append("newPassword='").append(newPassword).append('\''); //NOSONAR + sb.append(", oldPassword='").append(oldPassword).append('\''); //NOSONAR + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/user/CreateUserBidRS.java b/src/main/java/com/epam/ta/reportportal/model/user/CreateUserBidRS.java new file mode 100644 index 0000000000..2a979cccae --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/user/CreateUserBidRS.java @@ -0,0 +1,58 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.user; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonInclude(Include.NON_NULL) +public class CreateUserBidRS { + + @JsonProperty(value = "message") + private String message; + + @JsonProperty(value = "bid") + private String bid; + + @JsonProperty(value = "backLink") + private String backLink; + + public void setMessage(String value) { + this.message = value; + } + + public String getMessage() { + return message; + } + + public void setBid(String uuid) { + this.bid = uuid; + } + + public String getBid() { + return bid; + } + + public void setBackLink(String link) { + this.backLink = link; + } + + public String getBackLink() { + return backLink; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/user/CreateUserRQ.java b/src/main/java/com/epam/ta/reportportal/model/user/CreateUserRQ.java new file mode 100644 index 0000000000..69bf6932a7 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/user/CreateUserRQ.java @@ -0,0 +1,84 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.user; + +import com.epam.ta.reportportal.ws.annotations.In; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import javax.validation.constraints.NotBlank; + +/** + * Request model for user creation (confirmation will be send on email) + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class CreateUserRQ { + + @NotBlank + @JsonProperty(value = "email", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String email; + + @NotBlank + @JsonProperty(value = "role", required = true) + @In(allowedValues = { "operator", "customer", "member", "project_manager" }) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String role; + + @NotBlank + @JsonProperty(value = "defaultProject", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String defaultProject; + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getDefaultProject() { + return defaultProject; + } + + public void setDefaultProject(String value) { + this.defaultProject = value; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("CreateUserRQ{"); + sb.append("email='").append(email).append('\''); + sb.append(", role='").append(role).append('\''); + sb.append(", defaultProject='").append(defaultProject).append('\''); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/user/CreateUserRQConfirm.java b/src/main/java/com/epam/ta/reportportal/model/user/CreateUserRQConfirm.java new file mode 100644 index 0000000000..bcbeb36ffe --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/user/CreateUserRQConfirm.java @@ -0,0 +1,104 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.user; + +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +/** + * Confirmation resource of user creation with user-data + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class CreateUserRQConfirm { + + @NotBlank + @Pattern(regexp = "[a-zA-Z0-9-_.]+") + @Size(min = ValidationConstraints.MIN_LOGIN_LENGTH, max = ValidationConstraints.MAX_LOGIN_LENGTH) + @JsonProperty(value = "login", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED, example = "string") + private String login; + + @NotBlank + @Size(min = ValidationConstraints.MIN_PASSWORD_LENGTH, max = ValidationConstraints.MAX_PASSWORD_LENGTH) + @JsonProperty(value = "password", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String password; + + @NotBlank + @Pattern(regexp = "[\\pL0-9-_ \\.]+") + @Size(min = ValidationConstraints.MIN_USER_NAME_LENGTH, max = ValidationConstraints.MAX_USER_NAME_LENGTH) + @JsonProperty(value = "fullName", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED, example = "string") + private String fullName; + + @NotBlank + @JsonProperty(value = "email", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String email; + + public void setLogin(String value) { + this.login = value; + } + + public String getLogin() { + return login; + } + + public void setPassword(String value) { + this.password = value; + } + + public String getPassword() { + return password; + } + + public void setFullName(String value) { + this.fullName = value; + } + + public String getFullName() { + return fullName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("CreateUserRQConfirm{"); + sb.append("login='").append(login).append('\''); + sb.append(", password='").append(password).append('\''); + sb.append(", fullName='").append(fullName).append('\''); + sb.append(", email='").append(email).append('\''); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/user/CreateUserRQFull.java b/src/main/java/com/epam/ta/reportportal/model/user/CreateUserRQFull.java new file mode 100644 index 0000000000..12cc34206e --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/user/CreateUserRQFull.java @@ -0,0 +1,142 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.user; + +import com.epam.ta.reportportal.ws.annotations.In; +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +/** + * Create User request for admin user creation functionality + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class CreateUserRQFull { + + @NotBlank + @Pattern(regexp = "[a-zA-Z0-9-_.]+") + @Size(min = ValidationConstraints.MIN_LOGIN_LENGTH, max = ValidationConstraints.MAX_LOGIN_LENGTH) + @JsonProperty(value = "login", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED, example = "string") + private String login; + + @NotBlank + @Size(min = ValidationConstraints.MIN_PASSWORD_LENGTH, max = ValidationConstraints.MAX_PASSWORD_LENGTH) + @JsonProperty(value = "password", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String password; + + @NotBlank + @Pattern(regexp = "[\\pL0-9-_ \\.]+") + @Size(min = ValidationConstraints.MIN_USER_NAME_LENGTH, max = ValidationConstraints.MAX_USER_NAME_LENGTH) + @JsonProperty(value = "fullName", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED, example = "string") + private String fullName; + + @NotBlank + @JsonProperty(value = "email", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String email; + + @NotNull + @JsonProperty(value = "accountRole", required = true) + @In(allowedValues = { "user", "administrator" }) + @Schema(required = true, allowableValues = "USER, ADMINISTRATOR") + private String accountRole; + + @NotNull + @JsonProperty(value = "projectRole", required = true) + @In(allowedValues = { "operator", "customer", "member", "project_manager" }) + @Schema(required = true, allowableValues = "CUSTOMER, MEMBER, PROJECT_MANAGER") + private String projectRole; + + @NotBlank + @JsonProperty(value = "defaultProject", required = true) + @Schema(requiredMode = RequiredMode.REQUIRED) + private String defaultProject; + + public void setLogin(String value) { + this.login = value; + } + + public String getLogin() { + return login; + } + + public void setPassword(String value) { + this.password = value; + } + + public String getPassword() { + return password; + } + + public void setFullName(String value) { + this.fullName = value; + } + + public String getFullName() { + return fullName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getAccountRole() { + return accountRole; + } + + public void setAccountRole(String role) { + this.accountRole = role; + } + + public String getProjectRole() { + return projectRole; + } + + public void setProjectRole(String role) { + this.projectRole = role; + } + + public String getDefaultProject() { + return defaultProject; + } + + public void setDefaultProject(String value) { + this.defaultProject = value; + } + + @Override + public String toString() { + return "CreateUserRQFull [login=" + login + ", password=" + password + ", fullName=" + fullName + ", email=" + email + + ", projectRole=" + projectRole + ", defaultProject=" + defaultProject + "]"; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/user/CreateUserRS.java b/src/main/java/com/epam/ta/reportportal/model/user/CreateUserRS.java new file mode 100644 index 0000000000..84f6a58c17 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/user/CreateUserRS.java @@ -0,0 +1,60 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.user; + +import com.epam.ta.reportportal.model.WarningAwareRS; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Aliaksandr_Kazantsau + */ +@JsonInclude(Include.NON_NULL) +public class CreateUserRS extends WarningAwareRS { + + @JsonProperty("id") + private Long id; + + @JsonProperty("login") + private String login; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("CreateUserRS{"); + sb.append("id=").append(id); + sb.append(", login='").append(login).append('\''); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/user/EditUserRQ.java b/src/main/java/com/epam/ta/reportportal/model/user/EditUserRQ.java new file mode 100644 index 0000000000..1614f51c3f --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/user/EditUserRQ.java @@ -0,0 +1,87 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.user; + +import com.epam.ta.reportportal.ws.annotations.In; +import com.epam.ta.reportportal.ws.annotations.NotBlankString; +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +/** + * Edit User request model + * + * @author Aliaksandr_Kazantsau + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class EditUserRQ { + + @NotBlankString + @JsonProperty(value = "email") + private String email; + + @In(allowedValues = { "user", "administrator" }) + @JsonProperty(value = "role") + private String role; + + @NotBlankString + @Size(min = ValidationConstraints.MIN_USER_NAME_LENGTH, max = ValidationConstraints.MAX_USER_NAME_LENGTH) + @Pattern(regexp = "(\\s*[\\pL0-9-_\\.]+\\s*)+") + @JsonProperty(value = "fullName") + @Schema(requiredMode = RequiredMode.REQUIRED, example = "string") + private String fullName; + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public void setFullName(String value) { + this.fullName = value; + } + + public String getFullName() { + return fullName; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("EditUserRQ{"); + sb.append("email='").append(email).append('\''); + sb.append(", role='").append(role).append('\''); + sb.append(", fullName='").append(fullName).append('\''); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/user/ResetPasswordRQ.java b/src/main/java/com/epam/ta/reportportal/model/user/ResetPasswordRQ.java new file mode 100644 index 0000000000..6e58be026f --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/user/ResetPasswordRQ.java @@ -0,0 +1,93 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.user; + +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +/** + * @author Dzmitry_Kavalets + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ResetPasswordRQ { + + @NotBlank + @Size(min = ValidationConstraints.MIN_PASSWORD_LENGTH, max = ValidationConstraints.MAX_PASSWORD_LENGTH) + @JsonProperty(value = "password") + @Schema(requiredMode = RequiredMode.REQUIRED) + private String password; + + @NotBlank + @JsonProperty(value = "uuid") + @Schema(requiredMode = RequiredMode.REQUIRED) + private String uuid; + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + ResetPasswordRQ that = (ResetPasswordRQ) o; + + if (password != null ? !password.equals(that.password) : that.password != null) { + return false; + } + return !(uuid != null ? !uuid.equals(that.uuid) : that.uuid != null); + + } + + @Override + public int hashCode() { + int result = password != null ? password.hashCode() : 0; + result = 31 * result + (uuid != null ? uuid.hashCode() : 0); + return result; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("RestorePasswordRQ{"); + sb.append("password='").append(password).append('\''); //NOSONAR + sb.append(", uuid='").append(uuid).append('\''); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/user/RestorePasswordRQ.java b/src/main/java/com/epam/ta/reportportal/model/user/RestorePasswordRQ.java new file mode 100644 index 0000000000..1b6dca8689 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/user/RestorePasswordRQ.java @@ -0,0 +1,71 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.user; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import javax.validation.constraints.NotBlank; + +/** + * @author Dzmitry_Kavalets + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class RestorePasswordRQ { + + @NotBlank + @JsonProperty(value = "email") + @Schema(requiredMode = RequiredMode.REQUIRED) + private String email; + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + RestorePasswordRQ that = (RestorePasswordRQ) o; + + return !(email != null ? !email.equals(that.email) : that.email != null); + + } + + @Override + public int hashCode() { + return email != null ? email.hashCode() : 0; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("ResetPasswordRQ{"); + sb.append("email='").append(email).append('\''); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/user/SearchUserResource.java b/src/main/java/com/epam/ta/reportportal/model/user/SearchUserResource.java new file mode 100644 index 0000000000..214e8c4f1a --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/user/SearchUserResource.java @@ -0,0 +1,56 @@ +package com.epam.ta.reportportal.model.user; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonInclude(Include.NON_NULL) +public class SearchUserResource { + + @JsonProperty(value = "id", required = true) + private Long id; + + @JsonProperty(value = "login", required = true) + private String login; + + @JsonProperty(value = "email", required = true) + private String email; + + @JsonProperty(value = "fullName") + private String fullName; + + public SearchUserResource() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/user/UserBidRS.java b/src/main/java/com/epam/ta/reportportal/model/user/UserBidRS.java new file mode 100644 index 0000000000..a8df530164 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/user/UserBidRS.java @@ -0,0 +1,63 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.user; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * User creation bid response + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class UserBidRS { + + @JsonProperty("uuid") + private String uuid; + + @JsonProperty("isActive") + private boolean isActive; + + @JsonProperty("email") + private String email; + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public void setIsActive(boolean value) { + this.isActive = value; + } + + public boolean getIsActive() { + return isActive; + } + + public void setEmail(String value) { + this.email = value; + } + + public String getEmail() { + return email; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/user/UserResource.java b/src/main/java/com/epam/ta/reportportal/model/user/UserResource.java new file mode 100644 index 0000000000..6867eaf2bb --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/user/UserResource.java @@ -0,0 +1,181 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.user; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import javax.validation.constraints.NotNull; + +/** + * User resource representation for responses + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class UserResource { + + @NotNull + @JsonProperty(value = "id", required = true) + private Long id; + + @NotNull + @JsonProperty(value = "userId", required = true) + private String userId; + + @JsonProperty(value = "email", required = true) + private String email; + + @JsonProperty(value = "photoId") + private String photoId; + + @JsonProperty(value = "fullName") + private String fullName; + + @JsonProperty(value = "accountType") + private String accountType; + + @JsonProperty(value = "userRole") + private String userRole; + + @JsonProperty(value = "photoLoaded") + private boolean isLoaded; + + @JsonProperty(value = "metadata") + private Object metadata; + + @JsonProperty(value = "assignedProjects") + private Map assignedProjects; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public void setUserId(String value) { + this.userId = value; + } + + public String getUserId() { + return userId; + } + + public void setEmail(String value) { + this.email = value; + } + + public String getEmail() { + return email; + } + + public void setPhotoId(String value) { + this.photoId = value; + } + + public String getPhotoId() { + return photoId; + } + + public void setFullName(String value) { + this.fullName = value; + } + + public String getFullName() { + return fullName; + } + + public void setAccountType(String value) { + this.accountType = value; + } + + public String getAccountType() { + return accountType; + } + + public String getUserRole() { + return userRole; + } + + public void setUserRole(String value) { + this.userRole = value; + } + + public Object getMetadata() { + return metadata; + } + + public void setMetadata(Object metadata) { + this.metadata = metadata; + } + + public void setIsLoaded(boolean value) { + this.isLoaded = value; + } + + public boolean getIsLoaded() { + return isLoaded; + } + + public Map getAssignedProjects() { + return assignedProjects; + } + + public void setAssignedProjects(Map assignedProjects) { + this.assignedProjects = assignedProjects; + } + + public static class AssignedProject { + + private String projectRole; + private String entryType; + + public String getEntryType() { + return entryType; + } + + public void setEntryType(String entryType) { + this.entryType = entryType; + } + + public void setProjectRole(String projectRole) { + this.projectRole = projectRole; + } + + public String getProjectRole() { + return projectRole; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("AssignedProject{"); + sb.append("projectRole='").append(projectRole).append('\''); + sb.append('}'); + return sb.toString(); + } + } + + @Override + public String toString() { + return "UserResource{" + "id=" + id + ", userId='" + userId + '\'' + ", email='" + email + '\'' + ", photoId='" + photoId + '\'' + + ", fullName='" + fullName + '\'' + ", accountType='" + accountType + '\'' + ", userRole='" + userRole + '\'' + + ", isLoaded=" + isLoaded + ", metadata=" + metadata + ", assignedProjects=" + assignedProjects + '}'; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/validation/NotBlankWithSizeValidator.java b/src/main/java/com/epam/ta/reportportal/model/validation/NotBlankWithSizeValidator.java new file mode 100644 index 0000000000..3a86215e7d --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/validation/NotBlankWithSizeValidator.java @@ -0,0 +1,71 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.validation; + +import com.epam.ta.reportportal.ws.annotations.NotBlankWithSize; +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import org.apache.commons.lang3.StringUtils; + +/** + * @author Tatyana Gladysheva + */ +public class NotBlankWithSizeValidator implements ConstraintValidator { + + private static final String NOT_NULL_PROPERTY = "{NotNull}"; + private static final String NOT_BLANK_PROPERTY = "{NotBlank}"; + private static final String SIZE_PROPERTY = "{Size}"; + private static final String SPACE = " "; + + private int min; + private int max; + + @Override + public void initialize(NotBlankWithSize notBlankWithSizeAnnotation) { + this.min = notBlankWithSizeAnnotation.min(); + this.max = notBlankWithSizeAnnotation.max(); + } + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + boolean result; + if (value == null) { + result = false; + + setValidationMessage(NOT_NULL_PROPERTY, context); + + } else if (StringUtils.isBlank(value)) { + result = false; + + String message = NOT_BLANK_PROPERTY + SPACE + SIZE_PROPERTY; + setValidationMessage(message, context); + + } else if (value.length() < min || value.length() > max) { + result = false; + + setValidationMessage(SIZE_PROPERTY, context); + + } else { + result = true; + } return result; + } + + private void setValidationMessage(String message, ConstraintValidatorContext context) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(message).addConstraintViolation(); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/widget/ChartObject.java b/src/main/java/com/epam/ta/reportportal/model/widget/ChartObject.java new file mode 100644 index 0000000000..1fbf6eec31 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/widget/ChartObject.java @@ -0,0 +1,102 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.widget; + +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Basic representation for chart object with info for UI + * + * @author Andrei_Ramanchuk + */ +@JsonInclude(Include.NON_NULL) +public class ChartObject { + + @JsonProperty(value = "values") + private Map values; + + @JsonProperty(value = "name") + private String name; + + @JsonProperty(value = "startTime") + private String startTime; + + @JsonProperty(value = "number") + private String number; + + @JsonProperty(value = "id") + private String id; + + public ChartObject() { + } + + public void setId(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void setValues(Map values) { + this.values = values; + } + + public Map getValues() { + return values; + } + + public void setName(String value) { + this.name = value; + } + + public String getName() { + return name; + } + + public void setStartTime(String value) { + this.startTime = value; + } + + public String getStartTime() { + return startTime; + } + + public void setNumber(String value) { + this.number = value; + } + + public String getNumber() { + return number; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("ChartObject{"); + sb.append("values='").append(values).append('\''); + sb.append(", name='").append(name).append('\''); + sb.append(", startTime='").append(startTime).append('\''); + sb.append(", number='").append(number).append('\''); + sb.append(", id='").append(id).append('\''); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/widget/ContentParameters.java b/src/main/java/com/epam/ta/reportportal/model/widget/ContentParameters.java new file mode 100644 index 0000000000..bf96f411db --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/widget/ContentParameters.java @@ -0,0 +1,74 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.widget; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import java.util.List; +import java.util.Map; + +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_WIDGET_LIMIT; +import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_WIDGET_LIMIT; + +/** + * Part of widget domain object. Describe chart parameters + * + * @author Aliaksei_Makayed + */ +@JsonInclude(Include.NON_NULL) +public class ContentParameters { + + // fields for main data(for example: graphs at the chart) + @JsonProperty(value = "contentFields", required = true) + private List contentFields; + + @NotNull + @JsonProperty(value = "itemsCount", required = true) + private int itemsCount; + + @JsonProperty(value = "widgetOptions") + private Map widgetOptions; + + public List getContentFields() { + return contentFields; + } + + public void setContentFields(List contentFields) { + this.contentFields = contentFields; + } + + public int getItemsCount() { + return itemsCount; + } + + public void setItemsCount(int itemsCount) { + this.itemsCount = itemsCount; + } + + public Map getWidgetOptions() { + return widgetOptions; + } + + public void setWidgetOptions(Map widgetOptions) { + this.widgetOptions = widgetOptions; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/widget/MaterializedWidgetType.java b/src/main/java/com/epam/ta/reportportal/model/widget/MaterializedWidgetType.java new file mode 100644 index 0000000000..2003fba463 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/widget/MaterializedWidgetType.java @@ -0,0 +1,24 @@ +package com.epam.ta.reportportal.model.widget; + +import javax.annotation.Nullable; +import java.util.Arrays; +import java.util.Optional; + +/** + * @author Pavel Bortnik + */ +public enum MaterializedWidgetType { + + COMPONENT_HEALTH_CHECK_TABLE("componentHealthCheckTable"), + CUMULATIVE_TREND_CHART("cumulative"); + + private final String type; + + MaterializedWidgetType(String type) { + this.type = type; + } + + public String getType() { + return this.type; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/widget/SortEntry.java b/src/main/java/com/epam/ta/reportportal/model/widget/SortEntry.java new file mode 100644 index 0000000000..9ddc1a0f98 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/widget/SortEntry.java @@ -0,0 +1,36 @@ +package com.epam.ta.reportportal.model.widget; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.Serializable; + +/** + * @author Ivan Budayeu + */ +public class SortEntry implements Serializable { + + @JsonProperty(value = "asc") + private boolean asc; + + @JsonProperty(value = "sortingColumn") + private String sortingColumn; + + public SortEntry() { + } + + public boolean isAsc() { + return asc; + } + + public void setAsc(boolean asc) { + this.asc = asc; + } + + public String getSortingColumn() { + return sortingColumn; + } + + public void setSortingColumn(String sortingColumn) { + this.sortingColumn = sortingColumn; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/widget/WidgetPreviewRQ.java b/src/main/java/com/epam/ta/reportportal/model/widget/WidgetPreviewRQ.java new file mode 100644 index 0000000000..c5a0a5b62a --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/widget/WidgetPreviewRQ.java @@ -0,0 +1,111 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.widget; + +import com.epam.ta.reportportal.ws.annotations.In; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import java.util.List; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +/** + * Model object for getting widget preview content + * + * @author Pavel Bortnik + */ + +@JsonInclude(Include.NON_NULL) +public class WidgetPreviewRQ { + + @NotNull + @JsonProperty(value = "widgetType", required = true) + @In(allowedValues = { "oldLineChart", "investigatedTrend", "launchStatistics", "statisticTrend", + "casesTrend", "notPassed", "overallStatistics", "uniqueBugTable", "bugTrend", + "activityStream", "launchesComparisonChart", "launchesDurationChart", "launchesTable", + "topTestCases", "flakyTestCases", "passingRateSummary", "passingRatePerLaunch", + "productStatus", "mostTimeConsuming", "cumulative" }) + @Schema(required = true, allowableValues = + "oldLineChart, investigatedTrend, launchStatistics, statisticTrend," + + " casesTrend, notPassed, overallStatistics, uniqueBugTable, bugTrend, activityStream, launchesComparisonChart," + + " launchesDurationChart, launchesTable, topTestCases, flakyTestCases, passingRateSummary, passingRatePerLaunch," + + " productStatus, mostTimeConsuming, cumulative") + private String widgetType; + + @Valid + @JsonProperty(value = "contentParameters") + private ContentParameters contentParameters; + + @JsonProperty(value = "filterIds") + private List filterIds; + + @NotNull + public String getWidgetType() { + return widgetType; + } + + public void setWidgetType(@NotNull String widgetType) { + this.widgetType = widgetType; + } + + public ContentParameters getContentParameters() { + return contentParameters; + } + + public void setContentParameters(ContentParameters contentParameters) { + this.contentParameters = contentParameters; + } + + public List getFilterIds() { + return filterIds; + } + + public void setFilterIds(List filterIds) { + this.filterIds = filterIds; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + WidgetPreviewRQ that = (WidgetPreviewRQ) o; + + if (!widgetType.equals(that.widgetType)) { + return false; + } + if (contentParameters != null ? !contentParameters.equals(that.contentParameters) : + that.contentParameters != null) { + return false; + } + return filterIds != null ? filterIds.equals(that.filterIds) : that.filterIds == null; + } + + @Override + public int hashCode() { + int result = widgetType.hashCode(); + result = 31 * result + (contentParameters != null ? contentParameters.hashCode() : 0); + result = 31 * result + (filterIds != null ? filterIds.hashCode() : 0); + return result; + } +} diff --git a/src/main/java/com/epam/ta/reportportal/model/widget/WidgetRQ.java b/src/main/java/com/epam/ta/reportportal/model/widget/WidgetRQ.java new file mode 100644 index 0000000000..b05059a328 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/widget/WidgetRQ.java @@ -0,0 +1,106 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.widget; + +import com.epam.ta.reportportal.model.BaseEntityRQ; +import com.epam.ta.reportportal.core.events.annotations.WidgetLimitRange; +import com.epam.ta.reportportal.ws.annotations.In; +import com.epam.ta.reportportal.ws.annotations.NotBlankWithSize; +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import java.util.List; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +/** + * Domain model object for creating and updating widget + * + * @author Aliaksei_Makayed + */ + +@WidgetLimitRange +@JsonInclude(Include.NON_NULL) +public class WidgetRQ extends BaseEntityRQ { + + @NotBlankWithSize(min = ValidationConstraints.MIN_NAME_LENGTH, max = ValidationConstraints.MAX_WIDGET_NAME_LENGTH) + @JsonProperty(value = "name", required = true) + private String name; + + @NotNull + @JsonProperty(value = "widgetType", required = true) + @In(allowedValues = { "oldLineChart", "investigatedTrend", "launchStatistics", "statisticTrend", + "casesTrend", "notPassed", "overallStatistics", "uniqueBugTable", "bugTrend", + "activityStream", "launchesComparisonChart", "launchesDurationChart", "launchesTable", + "topTestCases", "flakyTestCases", "passingRateSummary", "passingRatePerLaunch", + "productStatus", "mostTimeConsuming", "cumulative", "topPatternTemplates", + "componentHealthCheck", "componentHealthCheckTable" }) + @Schema(required = true, allowableValues = + "oldLineChart, investigatedTrend, launchStatistics, statisticTrend," + + " casesTrend, notPassed, overallStatistics, uniqueBugTable, bugTrend, activityStream, launchesComparisonChart," + + " launchesDurationChart, launchesTable, topTestCases, flakyTestCases, passingRateSummary, passingRatePerLaunch," + + " productStatus, mostTimeConsuming, cumulative, topPatternTemplates, componentHealthCheck, componentHealthCheckTable") + private String widgetType; + + @Valid + @JsonProperty(value = "contentParameters") + private ContentParameters contentParameters; + + @JsonProperty(value = "filterIds") + private List filterIds; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @NotNull + public String getWidgetType() { + return widgetType; + } + + public void setWidgetType(@NotNull String widgetType) { + this.widgetType = widgetType; + } + + public ContentParameters getContentParameters() { + return contentParameters; + } + + public void setContentParameters(ContentParameters contentParameters) { + this.contentParameters = contentParameters; + } + + public List getFilterIds() { + return filterIds; + } + + public void setFilterIds(List filterIds) { + this.filterIds = filterIds; + } + + @Override + public String toString() { + return "WidgetRQ{" + "name='" + name + '\'' + ", widgetType='" + widgetType + '\'' + + ", contentParameters=" + contentParameters + ", filterIds=" + filterIds + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/model/widget/WidgetResource.java b/src/main/java/com/epam/ta/reportportal/model/widget/WidgetResource.java new file mode 100644 index 0000000000..d48faed0f0 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/model/widget/WidgetResource.java @@ -0,0 +1,120 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.model.widget; + +import com.epam.ta.reportportal.model.filter.UserFilterResource; +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import com.epam.ta.reportportal.ws.reporting.OwnedResource; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import java.util.List; +import java.util.Map; +import javax.validation.Valid; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +/** + * @author Dzmitry_Kavalets + */ +public class WidgetResource extends OwnedResource { + + @NotNull + @JsonProperty(value = "id", required = true) + private Long widgetId; + + @NotBlank + @Size(min = ValidationConstraints.MIN_NAME_LENGTH, max = ValidationConstraints.MAX_WIDGET_NAME_LENGTH) + @JsonProperty(value = "name", required = true) + private String name; + + @NotNull + @JsonProperty(value = "widgetType", required = true) + @Schema(required = true, allowableValues = + "oldLineChart, investigatedTrend, launchStatistics, statisticTrend," + + " casesTrend, notPassed, overallStatistics, uniqueBugTable, bugTrend, activityStream, launchesComparisonChart," + + " launchesDurationChart, launchesTable, topTestCases, flakyTestCases, passingRateSummary, passingRatePerLaunch," + + " productStatus, mostTimeConsuming, cumulative") + private String widgetType; + + @NotNull + @Valid + @JsonProperty(value = "contentParameters", required = true) + private ContentParameters contentParameters; + + @JsonProperty(value = "appliedFilters") + private List appliedFilters; + + @JsonProperty(value = "content") + private Map content; + + public Long getWidgetId() { + return widgetId; + } + + public void setWidgetId(Long widgetId) { + this.widgetId = widgetId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getAppliedFilters() { + return appliedFilters; + } + + public void setAppliedFilters(List appliedFilters) { + this.appliedFilters = appliedFilters; + } + + @NotNull + public String getWidgetType() { + return widgetType; + } + + public void setWidgetType(@NotNull String widgetType) { + this.widgetType = widgetType; + } + + public ContentParameters getContentParameters() { + return contentParameters; + } + + public void setContentParameters(ContentParameters contentParameters) { + this.contentParameters = contentParameters; + } + + public Map getContent() { + return content; + } + + public void setContent(Map content) { + this.content = content; + } + + @Override + public String toString() { + return "WidgetResource{" + "widgetId=" + widgetId + ", name='" + name + '\'' + ", widgetType='" + + widgetType + '\'' + ", contentParameters=" + contentParameters + ", appliedFilters=" + + appliedFilters + ", content=" + content + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/plugin/Pf4jPluginManager.java b/src/main/java/com/epam/ta/reportportal/plugin/Pf4jPluginManager.java index 07b539354e..c071e220db 100644 --- a/src/main/java/com/epam/ta/reportportal/plugin/Pf4jPluginManager.java +++ b/src/main/java/com/epam/ta/reportportal/plugin/Pf4jPluginManager.java @@ -37,7 +37,7 @@ import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.filesystem.DataStore; import com.epam.ta.reportportal.ws.converter.builders.IntegrationTypeBuilder; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import java.io.IOException; diff --git a/src/main/java/com/epam/ta/reportportal/util/BinaryDataResponseWriter.java b/src/main/java/com/epam/ta/reportportal/util/BinaryDataResponseWriter.java index 463f002999..a12e4f173c 100644 --- a/src/main/java/com/epam/ta/reportportal/util/BinaryDataResponseWriter.java +++ b/src/main/java/com/epam/ta/reportportal/util/BinaryDataResponseWriter.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.entity.attachment.BinaryData; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.io.IOException; import java.io.InputStream; import javax.servlet.http.HttpServletResponse; diff --git a/src/main/java/com/epam/ta/reportportal/util/ControllerUtils.java b/src/main/java/com/epam/ta/reportportal/util/ControllerUtils.java index 3c0f441574..88466a6222 100644 --- a/src/main/java/com/epam/ta/reportportal/util/ControllerUtils.java +++ b/src/main/java/com/epam/ta/reportportal/util/ControllerUtils.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.util; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; import java.util.Iterator; import java.util.List; import java.util.Set; diff --git a/src/main/java/com/epam/ta/reportportal/util/ItemInfoUtils.java b/src/main/java/com/epam/ta/reportportal/util/ItemInfoUtils.java index 14890df9e4..7650e48a84 100644 --- a/src/main/java/com/epam/ta/reportportal/util/ItemInfoUtils.java +++ b/src/main/java/com/epam/ta/reportportal/util/ItemInfoUtils.java @@ -17,13 +17,13 @@ package com.epam.ta.reportportal.util; import static com.epam.ta.reportportal.util.Predicates.ITEM_ATTRIBUTE_EQUIVALENCE; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; import com.epam.ta.reportportal.entity.ItemAttribute; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.BulkInfoUpdateRQ; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.attribute.UpdateItemAttributeRQ; +import com.epam.ta.reportportal.ws.reporting.BulkInfoUpdateRQ; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.UpdateItemAttributeRQ; import java.util.Collection; import java.util.Objects; import java.util.Optional; @@ -33,8 +33,7 @@ /** * @author Ihar Kahadouski *

- * Util class. Contains methods for updating - * {@link com.epam.ta.reportportal.entity.launch.Launch}/{@link + * Util class. Contains methods for updating {@link com.epam.ta.reportportal.entity.launch.Launch}/{@link * com.epam.ta.reportportal.entity.item.TestItem} attributes and description. */ public class ItemInfoUtils { diff --git a/src/main/java/com/epam/ta/reportportal/util/Predicates.java b/src/main/java/com/epam/ta/reportportal/util/Predicates.java index 40e840f958..cf3ee19e26 100644 --- a/src/main/java/com/epam/ta/reportportal/util/Predicates.java +++ b/src/main/java/com/epam/ta/reportportal/util/Predicates.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.entity.enums.TestItemTypeEnum; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; import com.google.common.base.CharMatcher; import java.util.Objects; import java.util.Set; diff --git a/src/main/java/com/epam/ta/reportportal/util/ProjectExtractor.java b/src/main/java/com/epam/ta/reportportal/util/ProjectExtractor.java index 998001d160..89a9eb8832 100644 --- a/src/main/java/com/epam/ta/reportportal/util/ProjectExtractor.java +++ b/src/main/java/com/epam/ta/reportportal/util/ProjectExtractor.java @@ -22,7 +22,7 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.dao.ProjectUserRepository; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/epam/ta/reportportal/util/SchemaFactory.java b/src/main/java/com/epam/ta/reportportal/util/SchemaFactory.java new file mode 100644 index 0000000000..7447b17ff7 --- /dev/null +++ b/src/main/java/com/epam/ta/reportportal/util/SchemaFactory.java @@ -0,0 +1,51 @@ +/* + * Copyright 2024 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.util; + + +import io.swagger.v3.oas.models.media.*; +import java.sql.Timestamp; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; + + +/** + * @author Andrei Piankouski + */ +public class SchemaFactory { + + private static final Map, Supplier> schemas = new HashMap<>(); + + static { + schemas.put(String.class, StringSchema::new); + schemas.put(Integer.class, IntegerSchema::new); + schemas.put(Long.class, IntegerSchema::new); + schemas.put(Boolean.class, BooleanSchema::new); + schemas.put(Timestamp.class, DateSchema::new); + schemas.put(Date.class, DateSchema::new); + schemas.put(List.class, ArraySchema::new); + } + + public static Schema createSchemaForType(Class type) { + return Optional.ofNullable(schemas.get(type)) + .map(Supplier::get) + .orElse(new StringSchema()); + } +} diff --git a/src/main/java/com/epam/ta/reportportal/util/email/EmailRulesValidator.java b/src/main/java/com/epam/ta/reportportal/util/email/EmailRulesValidator.java index da4778c975..3aa397d571 100644 --- a/src/main/java/com/epam/ta/reportportal/util/email/EmailRulesValidator.java +++ b/src/main/java/com/epam/ta/reportportal/util/email/EmailRulesValidator.java @@ -22,8 +22,8 @@ import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; import static com.epam.ta.reportportal.entity.project.ProjectUtils.getOwner; import static com.epam.ta.reportportal.util.UserUtils.isEmailValid; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; -import static com.epam.ta.reportportal.ws.model.ErrorType.USER_NOT_FOUND; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.USER_NOT_FOUND; import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_LOGIN_LENGTH; import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_NAME_LENGTH; import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_LOGIN_LENGTH; @@ -31,8 +31,8 @@ import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectUtils; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; import org.apache.commons.lang3.StringUtils; /** diff --git a/src/main/java/com/epam/ta/reportportal/util/email/EmailService.java b/src/main/java/com/epam/ta/reportportal/util/email/EmailService.java index 60736fe8bd..57368d34b9 100644 --- a/src/main/java/com/epam/ta/reportportal/util/email/EmailService.java +++ b/src/main/java/com/epam/ta/reportportal/util/email/EmailService.java @@ -37,9 +37,9 @@ import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectIssueType; import com.epam.ta.reportportal.entity.statistics.Statistics; +import com.epam.ta.reportportal.model.user.CreateUserRQFull; import com.epam.ta.reportportal.util.UserUtils; import com.epam.ta.reportportal.util.email.constant.IssueRegexConstant; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQFull; import com.google.common.annotations.VisibleForTesting; import java.io.UnsupportedEncodingException; import java.util.Collections; @@ -75,7 +75,8 @@ public class EmailService extends JavaMailSenderImpl { private static final String FINISH_LAUNCH_EMAIL_SUBJECT = " ReportPortal Notification: [%s] launch '%s' #%s finished"; private static final String URL_FORMAT = "%s/launches/all"; - private static final String COMPOSITE_ATTRIBUTE_FILTER_FORMAT = "%s?launchesParams=filter.has.compositeAttribute=%s"; + private static final String COMPOSITE_ATTRIBUTE_FILTER_FORMAT = + "%s?launchesParams=filter.has.compositeAttribute=%s"; private static final String TEMPLATE_IMAGES_PREFIX = "templates/email/images/"; private TemplateEngine templateEngine; /* Default value for FROM project notifications field */ @@ -125,7 +126,8 @@ public void sendLaunchFinishNotification(final String[] recipients, final String final Project project, final Launch launch) { String subject = format(FINISH_LAUNCH_EMAIL_SUBJECT, project.getName().toUpperCase(), launch.getName(), - launch.getNumber()); + launch.getNumber() + ); MimeMessagePreparator preparator = mimeMessage -> { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "utf-8"); message.setSubject(subject); @@ -152,25 +154,21 @@ String mergeFinishLaunchText(String url, Launch launch, Set pr /* Tags with links */ if (!CollectionUtils.isEmpty(launch.getAttributes())) { - email.put("attributes", - launch.getAttributes() - .stream() - .filter(it -> !it.isSystem()) - .collect(toMap(attribute -> ofNullable(attribute.getKey()).map(it -> it.concat(":")) - .orElse("") - .concat(attribute.getValue()), - attribute -> buildAttributesLink(basicUrl, attribute))) - ); + email.put("attributes", launch.getAttributes().stream().filter(it -> !it.isSystem()).collect( + toMap(attribute -> ofNullable(attribute.getKey()).map(it -> it.concat(":")).orElse("") + .concat(attribute.getValue()), + attribute -> buildAttributesLink(basicUrl, attribute) + ))); } /* Launch execution statistics */ - Map statistics = launch.getStatistics() - .stream() - .filter(s -> ofNullable(s.getStatisticsField()).isPresent() && StringUtils.isNotEmpty( - s.getStatisticsField().getName())) - .collect(Collectors.toMap(s -> s.getStatisticsField().getName(), Statistics::getCounter, - (prev, curr) -> prev)); + Map statistics = launch.getStatistics().stream().filter( + s -> ofNullable(s.getStatisticsField()).isPresent() && StringUtils.isNotEmpty( + s.getStatisticsField().getName())).collect( + Collectors.toMap(s -> s.getStatisticsField().getName(), Statistics::getCounter, + (prev, curr) -> prev + )); email.put("total", ofNullable(statistics.get(EXECUTIONS_TOTAL)).orElse(0)); email.put("passed", ofNullable(statistics.get(EXECUTIONS_PASSED)).orElse(0)); @@ -180,26 +178,31 @@ String mergeFinishLaunchText(String url, Launch launch, Set pr /* Launch issue statistics global counters */ email.put("productBugTotal", ofNullable(statistics.get(DEFECTS_PRODUCT_BUG_TOTAL)).orElse(0)); email.put("automationBugTotal", - ofNullable(statistics.get(DEFECTS_AUTOMATION_BUG_TOTAL)).orElse(0)); + ofNullable(statistics.get(DEFECTS_AUTOMATION_BUG_TOTAL)).orElse(0) + ); email.put("systemIssueTotal", ofNullable(statistics.get(DEFECTS_SYSTEM_ISSUE_TOTAL)).orElse(0)); email.put("noDefectTotal", ofNullable(statistics.get(DEFECTS_NO_DEFECT_TOTAL)).orElse(0)); email.put("toInvestigateTotal", - ofNullable(statistics.get(DEFECTS_TO_INVESTIGATE_TOTAL)).orElse(0)); + ofNullable(statistics.get(DEFECTS_TO_INVESTIGATE_TOTAL)).orElse(0) + ); - Map locatorsMapping = projectIssueTypes.stream() - .collect( - toMap(it -> it.getIssueType().getLocator(), it -> it.getIssueType().getLongName())); + Map locatorsMapping = projectIssueTypes.stream().collect( + toMap(it -> it.getIssueType().getLocator(), it -> it.getIssueType().getLongName())); /* Launch issue statistics custom sub-types */ fillEmail(email, "pbInfo", statistics, locatorsMapping, - IssueRegexConstant.PRODUCT_BUG_ISSUE_REGEX); + IssueRegexConstant.PRODUCT_BUG_ISSUE_REGEX + ); fillEmail(email, "abInfo", statistics, locatorsMapping, - IssueRegexConstant.AUTOMATION_BUG_ISSUE_REGEX); + IssueRegexConstant.AUTOMATION_BUG_ISSUE_REGEX + ); fillEmail(email, "siInfo", statistics, locatorsMapping, IssueRegexConstant.SYSTEM_ISSUE_REGEX); fillEmail(email, "ndInfo", statistics, locatorsMapping, - IssueRegexConstant.NO_DEFECT_ISSUE_REGEX); + IssueRegexConstant.NO_DEFECT_ISSUE_REGEX + ); fillEmail(email, "tiInfo", statistics, locatorsMapping, - IssueRegexConstant.TO_INVESTIGATE_ISSUE_REGEX); + IssueRegexConstant.TO_INVESTIGATE_ISSUE_REGEX + ); return templateEngine.merge("finish-launch-template.ftl", email); } @@ -207,43 +210,33 @@ String mergeFinishLaunchText(String url, Launch launch, Set pr private String getUrl(String baseUrl) { return ofNullable(rpHost).map(rh -> { final UriComponents rpHostUri = UriComponentsBuilder.fromUriString(rh).build(); - return UriComponentsBuilder.fromUriString(baseUrl) - .scheme(rpHostUri.getScheme()) - .host(rpHostUri.getHost()) - .port(rpHostUri.getPort()) - .build() - .toUri() - .toASCIIString(); + return UriComponentsBuilder.fromUriString(baseUrl).scheme(rpHostUri.getScheme()) + .host(rpHostUri.getHost()).port(rpHostUri.getPort()).build().toUri().toASCIIString(); }).orElse(baseUrl); } private String buildAttributesLink(String basicUrl, ItemAttribute attribute) { if (null != attribute.getKey()) { - return format(COMPOSITE_ATTRIBUTE_FILTER_FORMAT, - basicUrl, - urlPathSegmentEscaper().escape(attribute.getKey()) + ":" + - urlPathSegmentEscaper().escape(attribute.getValue()) + return format(COMPOSITE_ATTRIBUTE_FILTER_FORMAT, basicUrl, + urlPathSegmentEscaper().escape(attribute.getKey()) + ":" + urlPathSegmentEscaper().escape( + attribute.getValue()) ); } else { return format(COMPOSITE_ATTRIBUTE_FILTER_FORMAT, basicUrl, - urlPathSegmentEscaper().escape(attribute.getValue())); + urlPathSegmentEscaper().escape(attribute.getValue()) + ); } } private void fillEmail(Map email, String statisticsName, - Map statistics, - Map locatorsMapping, String regex) { - Optional> pb = Optional.of(statistics.entrySet() - .stream() - .filter(entry -> { - Pattern pattern = Pattern.compile(regex); - return pattern.matcher(entry.getKey()).matches(); - }) - .collect(Collectors.toMap( - entry -> locatorsMapping.get(StringUtils.substringAfterLast(entry.getKey(), "$")), - entry -> ofNullable(entry.getValue()).orElse(0), - (prev, curr) -> prev - ))); + Map statistics, Map locatorsMapping, String regex) { + Optional> pb = Optional.of(statistics.entrySet().stream().filter(entry -> { + Pattern pattern = Pattern.compile(regex); + return pattern.matcher(entry.getKey()).matches(); + }).collect(Collectors.toMap( + entry -> locatorsMapping.get(StringUtils.substringAfterLast(entry.getKey(), "$")), + entry -> ofNullable(entry.getValue()).orElse(0), (prev, curr) -> prev + ))); pb.ifPresent(stats -> email.put(statisticsName, stats)); } @@ -453,7 +446,10 @@ public void sendUserExpirationNotification(String recipient, Map message.setText(text, true); message.addInline("new-logo.png", emailTemplateResource("new-logo.png")); - message.addInline("delete-account-notification.png", emailTemplateResource("delete-account-notification.png")); + message.addInline( + "delete-account-notification.png", + emailTemplateResource("delete-account-notification.png") + ); attachNewSocialImages(message); }; this.send(preparator); diff --git a/src/main/java/com/epam/ta/reportportal/util/email/MailServiceFactory.java b/src/main/java/com/epam/ta/reportportal/util/email/MailServiceFactory.java index 02013f978b..ef8692c058 100644 --- a/src/main/java/com/epam/ta/reportportal/util/email/MailServiceFactory.java +++ b/src/main/java/com/epam/ta/reportportal/util/email/MailServiceFactory.java @@ -16,7 +16,7 @@ package com.epam.ta.reportportal.util.email; import static com.epam.ta.reportportal.commons.Predicates.notNull; -import static com.epam.ta.reportportal.ws.model.ErrorType.EMAIL_CONFIGURATION_IS_INCORRECT; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.EMAIL_CONFIGURATION_IS_INCORRECT; import static java.util.Optional.ofNullable; import com.epam.reportportal.commons.template.TemplateEngine; @@ -28,7 +28,7 @@ import com.epam.ta.reportportal.entity.integration.Integration; import com.epam.ta.reportportal.entity.integration.IntegrationType; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import java.util.Optional; diff --git a/src/main/java/com/epam/ta/reportportal/util/email/strategy/EmailTemplate.java b/src/main/java/com/epam/ta/reportportal/util/email/strategy/EmailTemplate.java index 31072c8738..3332056644 100644 --- a/src/main/java/com/epam/ta/reportportal/util/email/strategy/EmailTemplate.java +++ b/src/main/java/com/epam/ta/reportportal/util/email/strategy/EmailTemplate.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.util.email.strategy; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Arrays; import java.util.stream.Collectors; diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/ActivityController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/ActivityController.java index f35a45596f..7e90972404 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/ActivityController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/ActivityController.java @@ -1,18 +1,18 @@ /* - * Copyright 2019 EPAM Systems - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.ws.controller; @@ -24,12 +24,13 @@ import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.core.activity.ActivityHandler; import com.epam.ta.reportportal.entity.activity.Activity; + import com.epam.ta.reportportal.model.ActivityEventResource; import com.epam.ta.reportportal.util.ProjectExtractor; - import com.epam.ta.reportportal.ws.model.ActivityEventResource; import com.epam.ta.reportportal.ws.model.ActivityResource; import com.epam.ta.reportportal.ws.resolver.FilterFor; import com.epam.ta.reportportal.ws.resolver.SortFor; - import io.swagger.annotations.ApiOperation; + import io.swagger.v3.oas.annotations.Operation; + import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.security.access.prepost.PreAuthorize; @@ -48,40 +49,37 @@ @RequestMapping("/v1/{projectName}/activity") @Transactional(readOnly = true) @PreAuthorize(ASSIGNED_TO_PROJECT) + @Tag(name = "activity-controller", description = "Activity Controller") public class ActivityController { - private final ActivityHandler activityHandler; + private final ActivityHandler activityHandler; - private final ProjectExtractor projectExtractor; + private final ProjectExtractor projectExtractor; - @Autowired - public ActivityController(ActivityHandler activityHandler, ProjectExtractor projectExtractor) { - this.activityHandler = activityHandler; - this.projectExtractor = projectExtractor; - } + @Autowired + public ActivityController(ActivityHandler activityHandler, ProjectExtractor projectExtractor) { + this.activityHandler = activityHandler; + this.projectExtractor = projectExtractor; + } - @RequestMapping(value = "/{activityId}", method = RequestMethod.GET) - @ResponseStatus(OK) - public ActivityResource getActivity(@PathVariable String projectName, @PathVariable Long activityId, - @AuthenticationPrincipal ReportPortalUser user) { - ReportPortalUser.ProjectDetails projectDetails = projectExtractor.extractProjectDetailsAdmin( - user, - EntityUtils.normalizeId(projectName) - ); - return activityHandler.getActivity(projectDetails, activityId); - } + @RequestMapping(value = "/{activityId}", method = RequestMethod.GET) + @ResponseStatus(OK) + @Operation(summary = "Get activity by id") + public ActivityResource getActivity(@PathVariable String projectName, + @PathVariable Long activityId, @AuthenticationPrincipal ReportPortalUser user) { + ReportPortalUser.ProjectDetails projectDetails = + projectExtractor.extractProjectDetailsAdmin(user, EntityUtils.normalizeId(projectName)); + return activityHandler.getActivity(projectDetails, activityId); + } - @RequestMapping(value = "/item/{itemId}", method = RequestMethod.GET) - @ResponseStatus(OK) - @ApiOperation("Get activities for test item") + @RequestMapping(value = "/item/{itemId}", method = RequestMethod.GET) + @ResponseStatus(OK) + @Operation(summary = "Get activities for test item") public Iterable getTestItemActivities(@PathVariable String projectName, - @PathVariable Long itemId, - @FilterFor(Activity.class) Filter filter, @SortFor(Activity.class) Pageable pageable, - @AuthenticationPrincipal ReportPortalUser user) { - ReportPortalUser.ProjectDetails projectDetails = projectExtractor.extractProjectDetailsAdmin( - user, - EntityUtils.normalizeId(projectName) - ); - return activityHandler.getItemActivities(projectDetails, itemId, filter, pageable); - } + @PathVariable Long itemId, @FilterFor(Activity.class) Filter filter, + @SortFor(Activity.class) Pageable pageable, @AuthenticationPrincipal ReportPortalUser user) { + ReportPortalUser.ProjectDetails projectDetails = + projectExtractor.extractProjectDetailsAdmin(user, EntityUtils.normalizeId(projectName)); + return activityHandler.getItemActivities(projectDetails, itemId, filter, pageable); + } } \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/ActivityEventController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/ActivityEventController.java index bcfa33bdbc..276bb655fd 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/ActivityEventController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/ActivityEventController.java @@ -25,12 +25,13 @@ import com.epam.ta.reportportal.core.filter.SearchCriteriaService; import com.epam.ta.reportportal.core.filter.predefined.PredefinedFilterType; import com.epam.ta.reportportal.entity.activity.Activity; +import com.epam.ta.reportportal.model.ActivityEventResource; +import com.epam.ta.reportportal.model.PagedResponse; +import com.epam.ta.reportportal.model.SearchCriteriaRQ; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.ActivityEventResource; -import com.epam.ta.reportportal.ws.model.PagedResponse; -import com.epam.ta.reportportal.ws.model.SearchCriteriaRQ; import com.epam.ta.reportportal.ws.resolver.FilterCriteriaResolver; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import java.util.List; import javax.validation.constraints.Max; import javax.validation.constraints.Min; @@ -57,6 +58,7 @@ @Validated @RestController @RequestMapping("/v1/activities") +@Tag(name = "activity-event-controller", description = "Activity Event Controller") public class ActivityEventController { private final ActivityEventHandler activityEventHandler; @@ -64,8 +66,7 @@ public class ActivityEventController { private final SearchCriteriaService searchCriteriaService; public ActivityEventController(ActivityEventHandler activityEventHandler, - ProjectExtractor projectExtractor, - SearchCriteriaService searchCriteriaService) { + ProjectExtractor projectExtractor, SearchCriteriaService searchCriteriaService) { this.activityEventHandler = activityEventHandler; this.projectExtractor = projectExtractor; this.searchCriteriaService = searchCriteriaService; @@ -84,18 +85,17 @@ public ActivityEventController(ActivityEventHandler activityEventHandler, */ @PreAuthorize(ADMIN_ONLY) @PostMapping("/searches") - @ApiOperation("Get activities by search criteria") + @Operation(summary = "Get activities by search criteria") public PagedResponse getActivities( - @RequestParam @Min(0) @Max(300) int limit, - @RequestParam @Min(0) int offset, - @RequestParam Direction order, - @RequestParam String sort, + @RequestParam @Min(0) @Max(300) int limit, @RequestParam @Min(0) int offset, + @RequestParam Direction order, @RequestParam String sort, @RequestBody SearchCriteriaRQ searchCriteria, @AuthenticationPrincipal ReportPortalUser user) { - Queryable filter = searchCriteriaService.createFilterBySearchCriteria(searchCriteria, - Activity.class, - PredefinedFilterType.ACTIVITIES); + Queryable filter = + searchCriteriaService.createFilterBySearchCriteria(searchCriteria, Activity.class, + PredefinedFilterType.ACTIVITIES + ); Pageable pageable = PageRequest.of(offset / limit, limit, Sort.by(order, sort)); return activityEventHandler.getActivityEventsHistory(filter, pageable); @@ -103,11 +103,10 @@ public PagedResponse getActivities( @GetMapping("/{projectName}/subjectName") @PreAuthorize(ADMIN_ONLY) - @ApiOperation(value = "Load project activities subjectNames by filter", notes = "Only for current project") + @Operation(summary = "Load project activities subjectNames by filter", description = "Only for current project") public List getProjectSubjectName(@PathVariable String projectName, - @RequestParam(FilterCriteriaResolver.DEFAULT_FILTER_PREFIX + Condition.CNT - + "subjectName") String value, - @AuthenticationPrincipal ReportPortalUser user) { + @RequestParam(FilterCriteriaResolver.DEFAULT_FILTER_PREFIX + Condition.CNT + "subjectName") + String value, @AuthenticationPrincipal ReportPortalUser user) { return activityEventHandler.getSubjectNames( projectExtractor.extractProjectDetails(user, projectName), value); } diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/BugTrackingSystemController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/BugTrackingSystemController.java index 82a0c12a6f..6de8f240a9 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/BugTrackingSystemController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/BugTrackingSystemController.java @@ -27,7 +27,8 @@ import com.epam.ta.reportportal.ws.model.externalsystem.PostFormField; import com.epam.ta.reportportal.ws.model.externalsystem.PostTicketRQ; import com.epam.ta.reportportal.ws.model.externalsystem.Ticket; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; @@ -52,6 +53,7 @@ */ @RestController @RequestMapping("/v1/bts") +@Tag(name = "bug-tracking-system-controller", description = "Bug Tracking System Controller") public class BugTrackingSystemController { private final ProjectExtractor projectExtractor; @@ -69,7 +71,7 @@ public BugTrackingSystemController(ProjectExtractor projectExtractor, @Transactional(readOnly = true) @GetMapping(value = "/{projectName}/{integrationId}/fields-set") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get list of fields required for posting ticket in concrete integration") + @Operation(summary = "Get list of fields required for posting ticket in concrete integration") @PreAuthorize(PROJECT_MANAGER) public List getSetOfIntegrationSystemFields( @RequestParam(value = "issueType") String issuetype, @@ -84,7 +86,7 @@ public List getSetOfIntegrationSystemFields( @Transactional(readOnly = true) @GetMapping(value = "/{projectName}/{integrationId}/issue_types") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get list of allowable issue types for bug tracking system") + @Operation(summary = "Get list of allowable issue types for bug tracking system") @PreAuthorize(PROJECT_MANAGER) public List getAllowableIssueTypes(@PathVariable String projectName, @PathVariable Long integrationId, @@ -96,7 +98,7 @@ public List getAllowableIssueTypes(@PathVariable String projectName, @Transactional(readOnly = true) @GetMapping(value = "/{integrationId}/fields-set") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get list of fields required for posting ticket") + @Operation(summary = "Get list of fields required for posting ticket") @PreAuthorize(ADMIN_ONLY) public List getSetOfIntegrationSystemFields( @RequestParam(value = "issueType") String issueType, @@ -107,7 +109,7 @@ public List getSetOfIntegrationSystemFields( @Transactional(readOnly = true) @GetMapping(value = "/{integrationId}/issue_types") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get list of existed issue types in bts") + @Operation(summary = "Get list of existed issue types in bts") @PreAuthorize(ADMIN_ONLY) public List getAllowableIssueTypes(@PathVariable Long integrationId, @AuthenticationPrincipal ReportPortalUser user) { @@ -117,7 +119,7 @@ public List getAllowableIssueTypes(@PathVariable Long integrationId, @Transactional @PostMapping(value = "/{projectName}/{integrationId}/ticket") @ResponseStatus(HttpStatus.CREATED) - @ApiOperation("Post ticket to the bts integration") + @Operation(summary = "Post ticket to the bts integration") public Ticket createIssue(@Validated @RequestBody PostTicketRQ ticketRQ, @PathVariable String projectName, @PathVariable Long integrationId, @AuthenticationPrincipal ReportPortalUser user) { @@ -131,7 +133,7 @@ public Ticket createIssue(@Validated @RequestBody PostTicketRQ ticketRQ, @Transactional(readOnly = true) @GetMapping(value = "/{projectName}/ticket/{ticketId}") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get ticket from the bts integration") + @Operation(summary = "Get ticket from the bts integration") public Ticket getTicket(@PathVariable String ticketId, @PathVariable String projectName, @RequestParam(value = "btsUrl") String btsUrl, @RequestParam(value = "btsProject") String btsProject, diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/DashboardController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/DashboardController.java index e1b8291bd6..336285913f 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/DashboardController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/DashboardController.java @@ -27,16 +27,17 @@ import com.epam.ta.reportportal.core.dashboard.GetDashboardHandler; import com.epam.ta.reportportal.core.dashboard.UpdateDashboardHandler; import com.epam.ta.reportportal.entity.dashboard.Dashboard; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.dashboard.AddWidgetRq; +import com.epam.ta.reportportal.model.dashboard.CreateDashboardRQ; +import com.epam.ta.reportportal.model.dashboard.DashboardResource; +import com.epam.ta.reportportal.model.dashboard.UpdateDashboardRQ; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.dashboard.AddWidgetRq; -import com.epam.ta.reportportal.ws.model.dashboard.CreateDashboardRQ; -import com.epam.ta.reportportal.ws.model.dashboard.DashboardResource; -import com.epam.ta.reportportal.ws.model.dashboard.UpdateDashboardRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.epam.ta.reportportal.ws.resolver.FilterFor; import com.epam.ta.reportportal.ws.resolver.SortFor; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.security.access.prepost.PreAuthorize; @@ -59,6 +60,7 @@ @RestController @PreAuthorize(ASSIGNED_TO_PROJECT) @RequestMapping("/v1/{projectName}/dashboard") +@Tag(name = "dashboard-controller", description = "Dashboard Controller") public class DashboardController { private final ProjectExtractor projectExtractor; @@ -69,20 +71,19 @@ public class DashboardController { @Autowired public DashboardController(ProjectExtractor projectExtractor, - CreateDashboardHandler createDashboardHandler, - UpdateDashboardHandler updateDashboardHandler, GetDashboardHandler getDashboardHandler, - DeleteDashboardHandler deleteDashboardHandler) { - this.projectExtractor = projectExtractor; - this.createDashboardHandler = createDashboardHandler; - this.updateDashboardHandler = updateDashboardHandler; - this.getDashboardHandler = getDashboardHandler; - this.deleteDashboardHandler = deleteDashboardHandler; - } + CreateDashboardHandler createDashboardHandler, UpdateDashboardHandler updateDashboardHandler, + GetDashboardHandler getDashboardHandler, DeleteDashboardHandler deleteDashboardHandler) { + this.projectExtractor = projectExtractor; + this.createDashboardHandler = createDashboardHandler; + this.updateDashboardHandler = updateDashboardHandler; + this.getDashboardHandler = getDashboardHandler; + this.deleteDashboardHandler = deleteDashboardHandler; + } @Transactional @PostMapping @ResponseStatus(CREATED) - @ApiOperation("Create dashboard for specified project") + @Operation(summary = "Create dashboard for specified project") public EntryCreatedRS createDashboard(@PathVariable String projectName, @RequestBody @Validated CreateDashboardRQ createRQ, @AuthenticationPrincipal ReportPortalUser user) { @@ -90,63 +91,67 @@ public EntryCreatedRS createDashboard(@PathVariable String projectName, projectExtractor.extractProjectDetails(user, projectName), createRQ, user); } - @Transactional(readOnly = true) - @GetMapping - @ResponseStatus(OK) - @ApiOperation("Get all permitted dashboard resources for specified project") - public Iterable getAllDashboards(@PathVariable String projectName, @SortFor(Dashboard.class) Pageable pageable, - @FilterFor(Dashboard.class) Filter filter, @AuthenticationPrincipal ReportPortalUser user) { - return getDashboardHandler.getDashboards(projectExtractor.extractProjectDetails(user, projectName), pageable, filter, user); - } + @Transactional(readOnly = true) + @GetMapping + @ResponseStatus(OK) + @Operation(summary = "Get all permitted dashboard resources for specified project") + public Iterable getAllDashboards(@PathVariable String projectName, + @SortFor(Dashboard.class) Pageable pageable, @FilterFor(Dashboard.class) Filter filter, + @AuthenticationPrincipal ReportPortalUser user) { + return getDashboardHandler.getDashboards( + projectExtractor.extractProjectDetails(user, projectName), pageable, filter, user); + } - @Transactional - @PutMapping("/{dashboardId}/add") - @ResponseStatus(OK) - @ApiOperation("Add widget to specified dashboard") - public OperationCompletionRS addWidget(@PathVariable String projectName, @PathVariable Long dashboardId, - @RequestBody @Validated AddWidgetRq addWidgetRq, @AuthenticationPrincipal ReportPortalUser user) { - return updateDashboardHandler.addWidget(dashboardId, projectExtractor.extractProjectDetails(user, projectName), addWidgetRq, user); - } + @Transactional + @PutMapping("/{dashboardId}/add") + @ResponseStatus(OK) + @Operation(summary = "Add widget to specified dashboard") + public OperationCompletionRS addWidget(@PathVariable String projectName, + @PathVariable Long dashboardId, @RequestBody @Validated AddWidgetRq addWidgetRq, + @AuthenticationPrincipal ReportPortalUser user) { + return updateDashboardHandler.addWidget( + dashboardId, projectExtractor.extractProjectDetails(user, projectName), addWidgetRq, user); + } - @Transactional - @DeleteMapping("/{dashboardId}/{widgetId}") - @ResponseStatus(OK) - @ApiOperation("Remove widget from specified dashboard") - public OperationCompletionRS removeWidget(@PathVariable String projectName, @PathVariable Long dashboardId, @PathVariable Long widgetId, - @AuthenticationPrincipal ReportPortalUser user) { - return updateDashboardHandler.removeWidget(widgetId, dashboardId, projectExtractor.extractProjectDetails(user, projectName), user); - } + @Transactional + @DeleteMapping("/{dashboardId}/{widgetId}") + @ResponseStatus(OK) + @Operation(summary = "Remove widget from specified dashboard") + public OperationCompletionRS removeWidget(@PathVariable String projectName, + @PathVariable Long dashboardId, @PathVariable Long widgetId, + @AuthenticationPrincipal ReportPortalUser user) { + return updateDashboardHandler.removeWidget( + widgetId, dashboardId, projectExtractor.extractProjectDetails(user, projectName), user); + } - @Transactional - @PutMapping(value = "/{dashboardId}") - @ResponseStatus(OK) - @ApiOperation("Update specified dashboard for specified project") - public OperationCompletionRS updateDashboard(@PathVariable String projectName, @PathVariable Long dashboardId, - @RequestBody @Validated UpdateDashboardRQ updateRQ, @AuthenticationPrincipal ReportPortalUser user) { - return updateDashboardHandler.updateDashboard( - projectExtractor.extractProjectDetails(user, projectName), - updateRQ, - dashboardId, - user - ); - } + @Transactional + @PutMapping(value = "/{dashboardId}") + @ResponseStatus(OK) + @Operation(summary = "Update specified dashboard for specified project") + public OperationCompletionRS updateDashboard(@PathVariable String projectName, + @PathVariable Long dashboardId, @RequestBody @Validated UpdateDashboardRQ updateRQ, + @AuthenticationPrincipal ReportPortalUser user) { + return updateDashboardHandler.updateDashboard( + projectExtractor.extractProjectDetails(user, projectName), updateRQ, dashboardId, user); + } - @Transactional - @DeleteMapping(value = "/{dashboardId}") - @ResponseStatus(OK) - @ApiOperation("Delete specified dashboard by ID for specified project") - public OperationCompletionRS deleteDashboard(@PathVariable String projectName, @PathVariable Long dashboardId, - @AuthenticationPrincipal ReportPortalUser user) { - return deleteDashboardHandler.deleteDashboard(dashboardId, projectExtractor.extractProjectDetails(user, projectName), user); - } + @Transactional + @DeleteMapping(value = "/{dashboardId}") + @ResponseStatus(OK) + @Operation(summary = "Delete specified dashboard by ID for specified project") + public OperationCompletionRS deleteDashboard(@PathVariable String projectName, + @PathVariable Long dashboardId, @AuthenticationPrincipal ReportPortalUser user) { + return deleteDashboardHandler.deleteDashboard( + dashboardId, projectExtractor.extractProjectDetails(user, projectName), user); + } @Transactional @GetMapping(value = "/{dashboardId}") @ResponseStatus(OK) - @ApiOperation("Get specified dashboard by ID for specified project") + @Operation(summary = "Get specified dashboard by ID for specified project") public DashboardResource getDashboard(@PathVariable String projectName, - @PathVariable Long dashboardId, - @AuthenticationPrincipal ReportPortalUser user) { - return getDashboardHandler.getDashboard(dashboardId, projectExtractor.extractProjectDetails(user, projectName)); - } + @PathVariable Long dashboardId, @AuthenticationPrincipal ReportPortalUser user) { + return getDashboardHandler.getDashboard( + dashboardId, projectExtractor.extractProjectDetails(user, projectName)); + } } diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/DeprecatedUserController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/DeprecatedUserController.java index 0c542985dd..50d21273b3 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/DeprecatedUserController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/DeprecatedUserController.java @@ -16,32 +16,33 @@ import com.epam.ta.reportportal.core.user.GetUserHandler; import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; -import com.epam.ta.reportportal.ws.model.ApiKeyRQ; -import com.epam.ta.reportportal.ws.model.ApiKeyRS; -import com.epam.ta.reportportal.ws.model.ApiKeysRS; -import com.epam.ta.reportportal.ws.model.DeleteBulkRQ; -import com.epam.ta.reportportal.ws.model.DeleteBulkRS; -import com.epam.ta.reportportal.ws.model.ModelViews; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.YesNoRS; -import com.epam.ta.reportportal.ws.model.user.ChangePasswordRQ; -import com.epam.ta.reportportal.ws.model.user.CreateUserBidRS; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQ; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQConfirm; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQFull; -import com.epam.ta.reportportal.ws.model.user.CreateUserRS; -import com.epam.ta.reportportal.ws.model.user.EditUserRQ; -import com.epam.ta.reportportal.ws.model.user.ResetPasswordRQ; -import com.epam.ta.reportportal.ws.model.user.RestorePasswordRQ; -import com.epam.ta.reportportal.ws.model.user.UserBidRS; -import com.epam.ta.reportportal.ws.model.user.UserResource; +import com.epam.ta.reportportal.model.ApiKeyRQ; +import com.epam.ta.reportportal.model.ApiKeyRS; +import com.epam.ta.reportportal.model.ApiKeysRS; +import com.epam.ta.reportportal.model.DeleteBulkRQ; +import com.epam.ta.reportportal.model.DeleteBulkRS; +import com.epam.ta.reportportal.model.ModelViews; +import com.epam.ta.reportportal.model.YesNoRS; +import com.epam.ta.reportportal.model.user.ChangePasswordRQ; +import com.epam.ta.reportportal.model.user.CreateUserBidRS; +import com.epam.ta.reportportal.model.user.CreateUserRQ; +import com.epam.ta.reportportal.model.user.CreateUserRQConfirm; +import com.epam.ta.reportportal.model.user.CreateUserRQFull; +import com.epam.ta.reportportal.model.user.CreateUserRS; +import com.epam.ta.reportportal.model.user.EditUserRQ; +import com.epam.ta.reportportal.model.user.ResetPasswordRQ; +import com.epam.ta.reportportal.model.user.RestorePasswordRQ; +import com.epam.ta.reportportal.model.user.UserBidRS; +import com.epam.ta.reportportal.model.user.UserResource; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.epam.ta.reportportal.ws.resolver.ActiveRole; import com.epam.ta.reportportal.ws.resolver.FilterFor; import com.epam.ta.reportportal.ws.resolver.ResponseView; import com.epam.ta.reportportal.ws.resolver.SortFor; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.tags.Tag; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -67,7 +68,7 @@ @RestController @RequestMapping("/v1/user") @Deprecated -@Api(tags = "deprecated-user-controller", hidden = false, description = "Deprecated UserController") +@Tag(name = "deprecated-user-controller", description = "Deprecated User Controller") public class DeprecatedUserController extends UserController { @Autowired @@ -85,7 +86,7 @@ public DeprecatedUserController(CreateUserHandler createUserMessageHandler, @PostMapping @ResponseStatus(CREATED) @PreAuthorize(ADMIN_ONLY) - @ApiOperation(value = "Create specified user (DEPRECATED)", notes = "Allowable only for users with administrator role") + @Operation(summary = "Create specified user (DEPRECATED)", description = "Allowable only for users with administrator role") public CreateUserRS createUserByAdmin(@RequestBody @Validated CreateUserRQFull rq, @AuthenticationPrincipal ReportPortalUser currentUser, HttpServletRequest request) { return super.createUserByAdmin(rq, currentUser, request); @@ -95,7 +96,7 @@ public CreateUserRS createUserByAdmin(@RequestBody @Validated CreateUserRQFull r @PostMapping(value = "/bid") @ResponseStatus(CREATED) @PreAuthorize("(hasPermission(#createUserRQ.getDefaultProject(), 'projectManagerPermission')) || hasRole('ADMINISTRATOR')") - @ApiOperation("Register invitation for user who will be created (DEPRECATED)") + @Operation(summary = "Register invitation for user who will be created (DEPRECATED)") public CreateUserBidRS createUserBid(@RequestBody @Validated CreateUserRQ createUserRQ, @AuthenticationPrincipal ReportPortalUser currentUser, HttpServletRequest request) { return super.createUserBid(createUserRQ, currentUser, request); @@ -103,7 +104,7 @@ public CreateUserBidRS createUserBid(@RequestBody @Validated CreateUserRQ create @PostMapping(value = "/registration") @ResponseStatus(CREATED) - @ApiOperation("Activate invitation and create user in system (DEPRECATED)") + @Operation(summary = "Activate invitation and create user in system (DEPRECATED)") public CreateUserRS createUser(@RequestBody @Validated CreateUserRQConfirm request, @RequestParam(value = "uuid") String uuid) { return super.createUser(request, uuid); @@ -111,31 +112,22 @@ public CreateUserRS createUser(@RequestBody @Validated CreateUserRQConfirm reque @Transactional(readOnly = true) @GetMapping(value = "/registration") - @ApiOperation(value = "Get user's registration info (DEPRECATED)") + @Operation(summary = "Get user's registration info (DEPRECATED)") public UserBidRS getUserBidInfo(@RequestParam(value = "uuid") String uuid) { return super.getUserBidInfo(uuid); } @DeleteMapping(value = "/{id}") - @ApiOperation(value = "Delete specified user (DEPRECATED)") + @Operation(summary = "Delete specified user (DEPRECATED)") public OperationCompletionRS deleteUser(@PathVariable(value = "id") Long userId, @AuthenticationPrincipal ReportPortalUser currentUser) { return super.deleteUser(userId, currentUser); } - @DeleteMapping - @PreAuthorize(ADMIN_ONLY) - @ResponseStatus(OK) - @ApiOperation("Delete specified users by ids (DEPRECATED)") - public DeleteBulkRS deleteUsers(@RequestBody @Valid DeleteBulkRQ deleteBulkRQ, - @AuthenticationPrincipal ReportPortalUser user) { - return super.deleteUsers(deleteBulkRQ, user); - } - @Transactional @PutMapping(value = "/{login}") @PreAuthorize(ALLOWED_TO_EDIT_USER) - @ApiOperation(value = "Edit specified user (DEPRECATED)", notes = "Only for administrators and profile's owner") + @Operation(summary = "Edit specified user (DEPRECATED)", description = "Only for administrators and profile's owner") public OperationCompletionRS editUser(@PathVariable String login, @RequestBody @Validated EditUserRQ editUserRQ, @ActiveRole UserRole role, @AuthenticationPrincipal ReportPortalUser currentUser) { @@ -146,7 +138,7 @@ public OperationCompletionRS editUser(@PathVariable String login, @GetMapping(value = "/{login}") @ResponseView(ModelViews.FullUserView.class) @PreAuthorize(ALLOWED_TO_EDIT_USER) - @ApiOperation(value = "Return information about specified user (DEPRECATED)", notes = "Only for administrators and profile's owner") + @Operation(summary = "Return information about specified user (DEPRECATED)", description = "Only for administrators and profile's owner") public UserResource getUser(@PathVariable String login, @AuthenticationPrincipal ReportPortalUser currentUser) { return super.getUser(login, currentUser); @@ -154,7 +146,7 @@ public UserResource getUser(@PathVariable String login, @Transactional(readOnly = true) @GetMapping(value = { "", "/" }) - @ApiOperation("Return information about current logged-in user (DEPRECATED)") + @Operation(summary = "Return information about current logged-in user (DEPRECATED)") public UserResource getMyself(@AuthenticationPrincipal ReportPortalUser currentUser) { return super.getMyself(currentUser); } @@ -163,7 +155,7 @@ public UserResource getMyself(@AuthenticationPrincipal ReportPortalUser currentU @GetMapping(value = "/all") @ResponseView(ModelViews.FullUserView.class) @PreAuthorize(ADMIN_ONLY) - @ApiOperation(value = "Return information about all users (DEPRECATED)", notes = "Allowable only for users with administrator role") + @Operation(summary = "Return information about all users (DEPRECATED)", description = "Allowable only for users with administrator role") public Iterable getUsers(@FilterFor(User.class) Filter filter, @SortFor(User.class) Pageable pageable, @FilterFor(User.class) Queryable queryable, @AuthenticationPrincipal ReportPortalUser currentUser) { @@ -172,7 +164,7 @@ public Iterable getUsers(@FilterFor(User.class) Filter filter, @Transactional(readOnly = true) @GetMapping(value = "/registration/info") - @ApiOperation(value = "Validate registration information (DEPRECATED)") + @Operation(summary = "Validate registration information (DEPRECATED)") public YesNoRS validateInfo(@RequestParam(value = "username", required = false) String username, @RequestParam(value = "email", required = false) String email) { return super.validateInfo(username, email); @@ -181,7 +173,7 @@ public YesNoRS validateInfo(@RequestParam(value = "username", required = false) @Transactional @PostMapping(value = "/password/restore") @ResponseStatus(OK) - @ApiOperation("Create a restore password request (DEPRECATED)") + @Operation(summary = "Create a restore password request (DEPRECATED)") public OperationCompletionRS restorePassword(@RequestBody @Validated RestorePasswordRQ rq, HttpServletRequest request) { return super.restorePassword(rq, request); @@ -190,7 +182,7 @@ public OperationCompletionRS restorePassword(@RequestBody @Validated RestorePass @Transactional @PostMapping(value = "/password/reset") @ResponseStatus(OK) - @ApiOperation("Reset password (DEPRECATED") + @Operation(summary = "Reset password (DEPRECATED") public OperationCompletionRS resetPassword(@RequestBody @Validated ResetPasswordRQ rq) { return super.resetPassword(rq); } @@ -198,7 +190,7 @@ public OperationCompletionRS resetPassword(@RequestBody @Validated ResetPassword @Transactional(readOnly = true) @GetMapping(value = "/password/reset/{uuid}") @ResponseStatus(OK) - @ApiOperation("Check if a restore password bid exists (DEPRECATED)") + @Operation(summary = "Check if a restore password bid exists (DEPRECATED)") public YesNoRS isRestorePasswordBidExist(@PathVariable String uuid) { return super.isRestorePasswordBidExist(uuid); } @@ -206,7 +198,7 @@ public YesNoRS isRestorePasswordBidExist(@PathVariable String uuid) { @Transactional @PostMapping(value = "/password/change") @ResponseStatus(OK) - @ApiOperation("Change own password (DEPRECATED)") + @Operation(summary = "Change own password (DEPRECATED)") public OperationCompletionRS changePassword( @RequestBody @Validated ChangePasswordRQ changePasswordRQ, @AuthenticationPrincipal ReportPortalUser currentUser) { @@ -216,7 +208,7 @@ public OperationCompletionRS changePassword( @Transactional(readOnly = true) @GetMapping(value = "/{userName}/projects") @ResponseStatus(OK) - @ApiOperation(value = "Get user's projects (DEPRECATED)") + @Operation(summary = "Get user's projects (DEPRECATED)") public Map getUserProjects(@PathVariable String userName, @AuthenticationPrincipal ReportPortalUser currentUser) { return super.getUserProjects(userName, currentUser); @@ -226,7 +218,7 @@ public Map getUserProjects(@PathVariable S @GetMapping(value = "/search") @ResponseStatus(OK) @PreAuthorize(ADMIN_ONLY) - @ApiOperation(value = "Find users by term (DEPRECATED)", notes = "Only for administrators") + @Operation(summary = "Find users by term (DEPRECATED)", description = "Only for administrators") public Iterable findUsers(@RequestParam(value = "term") String term, Pageable pageable, @AuthenticationPrincipal ReportPortalUser user) { return super.findUsers(term, pageable, user); @@ -235,8 +227,8 @@ public Iterable findUsers(@RequestParam(value = "term") String ter @Transactional(readOnly = true) @GetMapping(value = "/export") @PreAuthorize(ADMIN_ONLY) - @ApiOperation(value = "Exports information about all users (DEPRECATED)", notes = "Allowable only for users with administrator role") - public void export(@ApiParam(allowableValues = "csv") + @Operation(summary = "Exports information about all users (DEPRECATED)", description = "Allowable only for users with administrator role") + public void export(@Parameter(schema = @Schema(allowableValues = "csv")) @RequestParam(value = "view", required = false, defaultValue = "csv") String view, @FilterFor(User.class) Filter filter, @FilterFor(User.class) Queryable queryable, @AuthenticationPrincipal ReportPortalUser currentUser, HttpServletResponse response) { @@ -245,7 +237,7 @@ public void export(@ApiParam(allowableValues = "csv") @PostMapping(value = "/{userId}/api-keys") @ResponseStatus(CREATED) - @ApiOperation("Create new Api Key for current user (DEPRECATED)") + @Operation(summary = "Create new Api Key for current user (DEPRECATED)") public ApiKeyRS createApiKey(@RequestBody @Validated ApiKeyRQ apiKeyRQ, @AuthenticationPrincipal ReportPortalUser currentUser, @PathVariable Long userId) { return super.createApiKey(apiKeyRQ, currentUser, userId); @@ -253,14 +245,14 @@ public ApiKeyRS createApiKey(@RequestBody @Validated ApiKeyRQ apiKeyRQ, @DeleteMapping(value = "/{userId}/api-keys/{keyId}") @ResponseStatus(OK) - @ApiOperation("Delete specified Api Key (DEPRECATED)") + @Operation(summary = "Delete specified Api Key (DEPRECATED)") public OperationCompletionRS deleteApiKey(@PathVariable Long keyId, @PathVariable Long userId) { return super.deleteApiKey(keyId, userId); } @GetMapping(value = "/{userId}/api-keys") @ResponseStatus(OK) - @ApiOperation("Get List of users Api Keys (DEPRECATED)") + @Operation(summary = "Get List of users Api Keys (DEPRECATED)") public ApiKeysRS getUsersApiKeys(@AuthenticationPrincipal ReportPortalUser currentUser, @PathVariable Long userId) { return super.getUsersApiKeys(currentUser, userId); diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/FileStorageController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/FileStorageController.java index c0dff7cca4..9cca1c426f 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/FileStorageController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/FileStorageController.java @@ -28,9 +28,10 @@ import com.epam.ta.reportportal.entity.attachment.BinaryData; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.common.net.HttpHeaders; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import java.io.IOException; import java.io.InputStream; import javax.servlet.http.HttpServletResponse; @@ -55,6 +56,7 @@ */ @RestController @RequestMapping("/v1/data") +@Tag(name = "file-storage-controller", description = "File Storage Controller") public class FileStorageController { private final ProjectExtractor projectExtractor; @@ -74,6 +76,7 @@ public FileStorageController(ProjectExtractor projectExtractor, EditUserHandler @Transactional(readOnly = true) @PreAuthorize(ASSIGNED_TO_PROJECT) @GetMapping(value = "/{projectName}/{dataId}") + @Operation(summary = "Get file") public void getFile(@PathVariable String projectName, @PathVariable("dataId") Long dataId, HttpServletResponse response, @AuthenticationPrincipal ReportPortalUser user) { @@ -83,7 +86,7 @@ public void getFile(@PathVariable String projectName, @PathVariable("dataId") Lo @Transactional(readOnly = true) @GetMapping(value = "/photo") - @ApiOperation("Get photo of current user") + @Operation(summary = "Get photo of current user") public void getMyPhoto(@AuthenticationPrincipal ReportPortalUser user, HttpServletResponse response, @RequestParam(value = "loadThumbnail", required = false) boolean loadThumbnail) { @@ -93,7 +96,7 @@ public void getMyPhoto(@AuthenticationPrincipal ReportPortalUser user, @Transactional(readOnly = true) @PreAuthorize(NOT_CUSTOMER) @GetMapping(value = "/{projectName}/userphoto") - @ApiOperation("Get user's photo") + @Operation(summary = "Get user's photo") public void getUserPhoto(@PathVariable String projectName, @RequestParam(value = "id") String username, @RequestParam(value = "loadThumbnail", required = false) boolean loadThumbnail, @@ -106,7 +109,7 @@ public void getUserPhoto(@PathVariable String projectName, @Transactional @PostMapping(value = "/photo", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) - @ApiOperation("Upload user's photo") + @Operation(summary = "Upload user's photo") public OperationCompletionRS uploadPhoto(@RequestParam("file") MultipartFile file, @AuthenticationPrincipal ReportPortalUser user) { return editUserHandler.uploadPhoto(EntityUtils.normalizeId(user.getUsername()), file); @@ -114,7 +117,7 @@ public OperationCompletionRS uploadPhoto(@RequestParam("file") MultipartFile fil @Transactional @DeleteMapping(value = "/photo") - @ApiOperation("Delete user's photo") + @Operation(summary = "Delete user's photo") public OperationCompletionRS deletePhoto(@AuthenticationPrincipal ReportPortalUser user) { return editUserHandler.deletePhoto(EntityUtils.normalizeId(user.getUsername())); } @@ -122,7 +125,7 @@ public OperationCompletionRS deletePhoto(@AuthenticationPrincipal ReportPortalUs @Transactional @PreAuthorize(ADMIN_ONLY) @PostMapping(value = "/clean", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) - @ApiOperation("Remove attachments from file storage according to uploaded csv file") + @Operation(summary = "Remove attachments from file storage according to uploaded csv file") public OperationCompletionRS removeAttachmentsByCsv(@RequestParam("file") MultipartFile file, @AuthenticationPrincipal ReportPortalUser user) { return deleteFilesHandler.removeFilesByCsv(file); diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/IntegrationController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/IntegrationController.java index 69bcb8ab3b..430de432d3 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/IntegrationController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/IntegrationController.java @@ -27,12 +27,13 @@ import com.epam.ta.reportportal.core.integration.DeleteIntegrationHandler; import com.epam.ta.reportportal.core.integration.ExecuteIntegrationHandler; import com.epam.ta.reportportal.core.integration.GetIntegrationHandler; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.integration.IntegrationRQ; +import com.epam.ta.reportportal.model.integration.IntegrationResource; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.integration.IntegrationRQ; -import com.epam.ta.reportportal.ws.model.integration.IntegrationResource; -import io.swagger.annotations.ApiOperation; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import java.util.List; import java.util.Map; import javax.validation.Valid; @@ -56,6 +57,7 @@ */ @RestController @RequestMapping(value = "/v1/integration") +@Tag(name = "integration-controller", description = "Integration Controller") public class IntegrationController { private final ProjectExtractor projectExtractor; @@ -80,7 +82,7 @@ public IntegrationController(ProjectExtractor projectExtractor, @Transactional(readOnly = true) @GetMapping("/global/all") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get available global integrations") + @Operation(summary = "Get available global integrations") public List getGlobalIntegrations( @AuthenticationPrincipal ReportPortalUser reportPortalUser) { return getIntegrationHandler.getGlobalIntegrations(); @@ -89,10 +91,9 @@ public List getGlobalIntegrations( @Transactional(readOnly = true) @GetMapping("/global/all/{pluginName}") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get available global integrations for plugin") + @Operation(summary = "Get available global integrations for plugin") public List getGlobalIntegrations( - @AuthenticationPrincipal ReportPortalUser reportPortalUser, - @PathVariable String pluginName) { + @AuthenticationPrincipal ReportPortalUser reportPortalUser, @PathVariable String pluginName) { return getIntegrationHandler.getGlobalIntegrations(pluginName); } @@ -100,7 +101,7 @@ public List getGlobalIntegrations( @GetMapping("/project/{projectName}/all") @ResponseStatus(HttpStatus.OK) @PreAuthorize(ASSIGNED_TO_PROJECT) - @ApiOperation("Get available project integrations") + @Operation(summary = "Get available project integrations") public List getProjectIntegrations(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser reportPortalUser) { return getIntegrationHandler.getProjectIntegrations(normalizeId(projectName)); @@ -110,34 +111,34 @@ public List getProjectIntegrations(@PathVariable String pro @GetMapping("/project/{projectName}/all/{pluginName}") @ResponseStatus(HttpStatus.OK) @PreAuthorize(ASSIGNED_TO_PROJECT) - @ApiOperation("Get available project integrations for plugin") + @Operation(summary = "Get available project integrations for plugin") public List getProjectIntegrations( - @AuthenticationPrincipal ReportPortalUser reportPortalUser, - @PathVariable String projectName, @PathVariable String pluginName) { + @AuthenticationPrincipal ReportPortalUser reportPortalUser, @PathVariable String projectName, + @PathVariable String pluginName) { return getIntegrationHandler.getProjectIntegrations(pluginName, normalizeId(projectName)); } @Transactional @PostMapping(value = "/{pluginName}") @ResponseStatus(HttpStatus.CREATED) - @ApiOperation("Create global Report Portal integration instance") + @Operation(summary = "Create global Report Portal integration instance") @PreAuthorize(ADMIN_ONLY) public EntryCreatedRS createGlobalIntegration(@RequestBody @Valid IntegrationRQ createRequest, - @PathVariable String pluginName, - @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable String pluginName, @AuthenticationPrincipal ReportPortalUser user) { return createIntegrationHandler.createGlobalIntegration(createRequest, pluginName, user); } @Transactional @PostMapping(value = "/{projectName}/{pluginName}") @ResponseStatus(HttpStatus.CREATED) - @ApiOperation("Create project Report Portal integration instance") + @Operation(summary = "Create project Report Portal integration instance") @PreAuthorize(PROJECT_MANAGER) public EntryCreatedRS createProjectIntegration(@RequestBody @Valid IntegrationRQ createRequest, - @PathVariable String pluginName, - @PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable String pluginName, @PathVariable String projectName, + @AuthenticationPrincipal ReportPortalUser user) { return createIntegrationHandler.createProjectIntegration(normalizeId(projectName), - createRequest, pluginName, user); + createRequest, pluginName, user + ); } @@ -145,10 +146,9 @@ public EntryCreatedRS createProjectIntegration(@RequestBody @Valid IntegrationRQ @GetMapping(value = "{projectName}/{integrationId}/connection/test") @ResponseStatus(HttpStatus.OK) @PreAuthorize(ASSIGNED_TO_PROJECT) - @ApiOperation("Test connection to the integration through the project config") + @Operation(summary = "Test connection to the integration through the project config") public boolean testIntegrationConnection(@PathVariable Long integrationId, - @PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user) { return getIntegrationHandler.testConnection(integrationId, normalizeId(projectName)); } @@ -156,7 +156,7 @@ public boolean testIntegrationConnection(@PathVariable Long integrationId, @GetMapping(value = "/{integrationId}/connection/test") @ResponseStatus(HttpStatus.OK) @PreAuthorize(ADMIN_ONLY) - @ApiOperation("Test connection to the global integration") + @Operation(summary = "Test connection to the global integration") public boolean testIntegrationConnection(@PathVariable Long integrationId, @AuthenticationPrincipal ReportPortalUser user) { return getIntegrationHandler.testConnection(integrationId); @@ -165,7 +165,7 @@ public boolean testIntegrationConnection(@PathVariable Long integrationId, @Transactional(readOnly = true) @GetMapping(value = "/{integrationId}") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get global Report Portal integration instance") + @Operation(summary = "Get global Report Portal integration instance") @PreAuthorize(ADMIN_ONLY) public IntegrationResource getGlobalIntegration(@PathVariable Long integrationId, @AuthenticationPrincipal ReportPortalUser user) { @@ -175,18 +175,17 @@ public IntegrationResource getGlobalIntegration(@PathVariable Long integrationId @Transactional(readOnly = true) @GetMapping(value = "/{projectName}/{integrationId}") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get integration instance") + @Operation(summary = "Get integration instance") @PreAuthorize(ASSIGNED_TO_PROJECT) public IntegrationResource getProjectIntegration(@PathVariable String projectName, - @PathVariable Long integrationId, - @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable Long integrationId, @AuthenticationPrincipal ReportPortalUser user) { return getIntegrationHandler.getProjectIntegrationById(integrationId, normalizeId(projectName)); } @Transactional @PutMapping(value = "/{integrationId}") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Update global Report Portal integration instance") + @Operation(summary = "Update global Report Portal integration instance") @PreAuthorize(ADMIN_ONLY) public OperationCompletionRS updateGlobalIntegration(@PathVariable Long integrationId, @RequestBody @Valid IntegrationRQ updateRequest, @@ -198,20 +197,21 @@ public OperationCompletionRS updateGlobalIntegration(@PathVariable Long integrat @Transactional @PutMapping(value = "/{projectName}/{integrationId}") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Update project integration instance") + @Operation(summary = "Update project integration instance") @PreAuthorize(PROJECT_MANAGER) public OperationCompletionRS updateProjectIntegration(@PathVariable Long integrationId, - @RequestBody @Valid IntegrationRQ updateRequest, - @PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user) { + @RequestBody @Valid IntegrationRQ updateRequest, @PathVariable String projectName, + @AuthenticationPrincipal ReportPortalUser user) { return createIntegrationHandler.updateProjectIntegration(integrationId, - normalizeId(projectName), updateRequest, user); + normalizeId(projectName), updateRequest, user + ); } @Transactional @DeleteMapping(value = "/{integrationId}") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Delete global integration instance") + @Operation(summary = "Delete global integration instance") @PreAuthorize(ADMIN_ONLY) public OperationCompletionRS deleteGlobalIntegration(@PathVariable Long integrationId, @AuthenticationPrincipal ReportPortalUser user) { @@ -221,7 +221,7 @@ public OperationCompletionRS deleteGlobalIntegration(@PathVariable Long integrat @Transactional @DeleteMapping(value = "/all/{type}") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Delete all global integrations by type") + @Operation(summary = "Delete all global integrations by type") @PreAuthorize(ADMIN_ONLY) public OperationCompletionRS deleteAllIntegrations(@PathVariable String type, @AuthenticationPrincipal ReportPortalUser user) { @@ -231,41 +231,39 @@ public OperationCompletionRS deleteAllIntegrations(@PathVariable String type, @Transactional @DeleteMapping(value = "/{projectName}/{integrationId}") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Delete project integration instance") + @Operation(summary = "Delete project integration instance") @PreAuthorize(PROJECT_MANAGER) public OperationCompletionRS deleteProjectIntegration(@PathVariable String projectName, - @PathVariable Long integrationId, - @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable Long integrationId, @AuthenticationPrincipal ReportPortalUser user) { return deleteIntegrationHandler.deleteProjectIntegration(integrationId, - normalizeId(projectName), user); + normalizeId(projectName), user + ); } @Transactional @DeleteMapping(value = "/{projectName}/all/{type}") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Delete all integrations assigned to specified project") + @Operation(summary = "Delete all integrations assigned to specified project") @PreAuthorize(PROJECT_MANAGER) public OperationCompletionRS deleteAllProjectIntegrations(@PathVariable String type, - @PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user) { return deleteIntegrationHandler.deleteProjectIntegrationsByType(type, normalizeId(projectName), - user); + user + ); } @Transactional @PutMapping(value = "{projectName}/{integrationId}/{command}", consumes = { - APPLICATION_JSON_VALUE}) + APPLICATION_JSON_VALUE }) @ResponseStatus(HttpStatus.OK) @PreAuthorize(ASSIGNED_TO_PROJECT) - @ApiOperation("Execute command to the integration instance") + @Operation(summary = "Execute command to the integration instance") public Object executeIntegrationCommand(@PathVariable String projectName, - @PathVariable("integrationId") Long integrationId, - @PathVariable("command") String command, @RequestBody Map executionParams, + @PathVariable("integrationId") Long integrationId, @PathVariable("command") String command, + @RequestBody Map executionParams, @AuthenticationPrincipal ReportPortalUser user) { return executeIntegrationHandler.executeCommand( - projectExtractor.extractProjectDetails(user, projectName), - integrationId, - command, + projectExtractor.extractProjectDetails(user, projectName), integrationId, command, executionParams ); } diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/InternalApiController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/InternalApiController.java deleted file mode 100644 index 45fb274192..0000000000 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/InternalApiController.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2019 EPAM Systems - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.ws.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - * Allowed for internal (other services) clients ONLY Provides direct access to DAO layer - * - * @author Andrei Varabyeu - */ -@Controller -@RequestMapping("/v1/api-internal") -//@PreAuthorize("hasRole('COMPONENT')") -public class InternalApiController { - - // private final ExternalSystemRepository externalSystemRepository; - // - // @Autowired - // public InternalApiController(ExternalSystemRepository externalSystemRepository) { - // this.externalSystemRepository = externalSystemRepository; - // } - // - // @RequestMapping(value = "/external-system/{systemId}", method = RequestMethod.GET) - // @ResponseBody - // @ResponseStatus(HttpStatus.OK) - // - // public ExternalSystemResource getExternalSystem(@PathVariable String systemId) { - // ExternalSystem externalSystem = externalSystemRepository.findOne(systemId); - // BusinessRule.expect(externalSystem, Predicates.notNull()).verify(ErrorType.EXTERNAL_SYSTEM_NOT_FOUND, systemId); - // return ExternalSystemConverter.TO_RESOURCE.apply(externalSystem); - // } -} diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/LaunchAsyncController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/LaunchAsyncController.java index ee4e818e9e..9bf17f38ad 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/LaunchAsyncController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/LaunchAsyncController.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.ws.controller; import static com.epam.ta.reportportal.auth.permissions.Permissions.ALLOWED_TO_REPORT; @@ -26,15 +27,16 @@ import com.epam.ta.reportportal.core.launch.MergeLaunchHandler; import com.epam.ta.reportportal.core.launch.StartLaunchHandler; import com.epam.ta.reportportal.core.logging.HttpLogging; +import com.epam.ta.reportportal.model.launch.FinishLaunchRS; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; -import com.epam.ta.reportportal.ws.model.launch.FinishLaunchRS; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; -import com.epam.ta.reportportal.ws.model.launch.MergeLaunchesRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRS; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; +import com.epam.ta.reportportal.ws.reporting.MergeLaunchesRQ; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRS; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -51,13 +53,14 @@ import org.springframework.web.bind.annotation.RestController; /** - * Controller implementation for async reporting client API for - * {@link com.epam.ta.reportportal.entity.launch.Launch} entity + * Controller implementation for async reporting client API for {@link + * com.epam.ta.reportportal.entity.launch.Launch} entity * * @author Konstantin Antipin */ @RestController @RequestMapping("/v2/{projectName}/launch") +@Tag(name = "launch-async-controller", description = "Launch Async Controller") public class LaunchAsyncController { private final ProjectExtractor projectExtractor; @@ -80,29 +83,25 @@ public LaunchAsyncController(ProjectExtractor projectExtractor, @PostMapping @PreAuthorize(ALLOWED_TO_REPORT) @ResponseStatus(CREATED) - @ApiOperation("Starts launch for specified project") + @Operation(summary = "Starts launch for specified project") public StartLaunchRS startLaunch(@PathVariable String projectName, - @ApiParam(value = "Start launch request body", required = true) @RequestBody @Validated StartLaunchRQ startLaunchRQ, - @AuthenticationPrincipal ReportPortalUser user) { + @Parameter(description = "Start launch request body", required = true) @RequestBody @Validated + StartLaunchRQ startLaunchRQ, @AuthenticationPrincipal ReportPortalUser user) { return startLaunchHandler.startLaunch(user, - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), startLaunchRQ); + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), startLaunchRQ + ); } @HttpLogging @PutMapping(value = "/{launchId}/finish") @PreAuthorize(ALLOWED_TO_REPORT) @ResponseStatus(OK) - @ApiOperation("Finish launch for specified project") + @Operation(summary = "Finish launch for specified project") public FinishLaunchRS finishLaunch(@PathVariable String projectName, - @PathVariable String launchId, - @RequestBody @Validated FinishExecutionRQ finishLaunchRQ, - @AuthenticationPrincipal ReportPortalUser user, - HttpServletRequest request) { - return finishLaunchHandler.finishLaunch( - launchId, - finishLaunchRQ, - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), - user, + @PathVariable String launchId, @RequestBody @Validated FinishExecutionRQ finishLaunchRQ, + @AuthenticationPrincipal ReportPortalUser user, HttpServletRequest request) { + return finishLaunchHandler.finishLaunch(launchId, finishLaunchRQ, + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user, composeBaseUrl(request) ); } @@ -112,13 +111,14 @@ public FinishLaunchRS finishLaunch(@PathVariable String projectName, @PostMapping("/merge") @PreAuthorize(ALLOWED_TO_REPORT) @ResponseStatus(OK) - @ApiOperation("Merge set of specified launches in common one") + @Operation(summary = "Merge set of specified launches in common one") public LaunchResource mergeLaunches(@PathVariable String projectName, - @ApiParam(value = "Merge launches request body", required = true) @RequestBody @Validated MergeLaunchesRQ mergeLaunchesRQ, - @AuthenticationPrincipal ReportPortalUser user) { + @Parameter(description = "Merge launches request body", required = true) @RequestBody @Validated + MergeLaunchesRQ mergeLaunchesRQ, @AuthenticationPrincipal ReportPortalUser user) { return mergeLaunchesHandler.mergeLaunches( projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user, - mergeLaunchesRQ); + mergeLaunchesRQ + ); } } diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/LaunchController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/LaunchController.java index 30412173f8..940364a5ca 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/LaunchController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/LaunchController.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.epam.ta.reportportal.ws.controller; import static com.epam.ta.reportportal.auth.permissions.Permissions.ALLOWED_TO_REPORT; @@ -38,31 +39,30 @@ import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.entity.widget.content.ChartStatisticsContent; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.BulkRQ; +import com.epam.ta.reportportal.model.DeleteBulkRS; +import com.epam.ta.reportportal.model.launch.AnalyzeLaunchRQ; +import com.epam.ta.reportportal.model.launch.FinishLaunchRS; +import com.epam.ta.reportportal.model.launch.LaunchImportRQ; +import com.epam.ta.reportportal.model.launch.UpdateLaunchRQ; +import com.epam.ta.reportportal.model.launch.cluster.CreateClustersRQ; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.BulkInfoUpdateRQ; -import com.epam.ta.reportportal.ws.model.BulkRQ; -import com.epam.ta.reportportal.ws.model.DeleteBulkRQ; -import com.epam.ta.reportportal.ws.model.DeleteBulkRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.launch.AnalyzeLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.FinishLaunchRS; -import com.epam.ta.reportportal.ws.model.launch.LaunchImportRQ; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; -import com.epam.ta.reportportal.ws.model.launch.MergeLaunchesRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRS; -import com.epam.ta.reportportal.ws.model.launch.UpdateLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.BulkInfoUpdateRQ; import com.epam.ta.reportportal.ws.model.launch.cluster.ClusterInfoResource; -import com.epam.ta.reportportal.ws.model.launch.cluster.CreateClustersRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; +import com.epam.ta.reportportal.ws.reporting.MergeLaunchesRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRS; import com.epam.ta.reportportal.ws.resolver.FilterFor; import com.epam.ta.reportportal.ws.resolver.SortFor; import com.google.common.net.HttpHeaders; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.tags.Tag; import java.io.IOException; import java.io.OutputStream; import java.util.List; @@ -104,6 +104,7 @@ */ @RestController @RequestMapping("/v1/{projectName}/launch") +@Tag(name = "launch-controller", description = "Launch Controller") public class LaunchController { private final ProjectExtractor projectExtractor; @@ -119,9 +120,8 @@ public class LaunchController { @Autowired public LaunchController(ProjectExtractor projectExtractor, StartLaunchHandler startLaunchHandler, - FinishLaunchHandler finishLaunchHandler, - StopLaunchHandler stopLaunchHandler, DeleteLaunchHandler deleteLaunchMessageHandler, - GetLaunchHandler getLaunchMessageHandler, + FinishLaunchHandler finishLaunchHandler, StopLaunchHandler stopLaunchHandler, + DeleteLaunchHandler deleteLaunchMessageHandler, GetLaunchHandler getLaunchMessageHandler, UpdateLaunchHandler updateLaunchHandler, MergeLaunchHandler mergeLaunchesHandler, ImportLaunchHandler importLaunchHandler, @Qualifier("launchJasperReportHandler") GetJasperReportHandler getJasperHandler) { @@ -142,27 +142,24 @@ public LaunchController(ProjectExtractor projectExtractor, StartLaunchHandler st @PostMapping @PreAuthorize(ALLOWED_TO_REPORT) @ResponseStatus(CREATED) - @ApiOperation("Starts launch for specified project") + @Operation(summary = "Starts launch for specified project") public StartLaunchRS startLaunch(@PathVariable String projectName, - @ApiParam(value = "Start launch request body", required = true) @RequestBody @Validated @Valid StartLaunchRQ startLaunchRQ, - @AuthenticationPrincipal ReportPortalUser user) { + @Parameter(description = "Start launch request body", required = true) @RequestBody @Validated + @Valid StartLaunchRQ startLaunchRQ, @AuthenticationPrincipal ReportPortalUser user) { return startLaunchHandler.startLaunch(user, - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), startLaunchRQ); + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), startLaunchRQ + ); } @PutMapping(value = "/{launchId}/finish") @PreAuthorize(ALLOWED_TO_REPORT) @ResponseStatus(OK) - @ApiOperation("Finish launch for specified project") + @Operation(summary = "Finish launch for specified project") public FinishLaunchRS finishLaunch(@PathVariable String projectName, - @PathVariable String launchId, - @RequestBody @Validated FinishExecutionRQ finishLaunchRQ, - @AuthenticationPrincipal ReportPortalUser user, - HttpServletRequest request) { - return finishLaunchHandler.finishLaunch(launchId, - finishLaunchRQ, - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), - user, + @PathVariable String launchId, @RequestBody @Validated FinishExecutionRQ finishLaunchRQ, + @AuthenticationPrincipal ReportPortalUser user, HttpServletRequest request) { + return finishLaunchHandler.finishLaunch(launchId, finishLaunchRQ, + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user, composeBaseUrl(request) ); } @@ -173,97 +170,97 @@ public FinishLaunchRS finishLaunch(@PathVariable String projectName, @PutMapping("/{launchId}/stop") @PreAuthorize(ALLOWED_TO_REPORT) @ResponseStatus(OK) - @ApiOperation("Force finish launch for specified project") + @Operation(summary = "Force finish launch for specified project") public OperationCompletionRS forceFinishLaunch(@PathVariable String projectName, - @PathVariable Long launchId, - @RequestBody @Validated FinishExecutionRQ finishExecutionRQ, + @PathVariable Long launchId, @RequestBody @Validated FinishExecutionRQ finishExecutionRQ, @AuthenticationPrincipal ReportPortalUser user) { return stopLaunchHandler.stopLaunch(launchId, finishExecutionRQ, - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user); + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user + ); } @Transactional @PutMapping("/stop") @PreAuthorize(ALLOWED_TO_REPORT) @ResponseStatus(OK) - @ApiOperation("Force finish launch") + @Operation(summary = "Force finish launch") public List bulkForceFinish(@PathVariable String projectName, @RequestBody @Validated BulkRQ rq, @AuthenticationPrincipal ReportPortalUser user) { return stopLaunchHandler.stopLaunch(rq, - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user); + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user + ); } @Transactional @PutMapping("/{launchId}/update") @PreAuthorize(ALLOWED_TO_REPORT) @ResponseStatus(OK) - @ApiOperation("Updates launch for specified project") + @Operation(summary = "Updates launch for specified project") public OperationCompletionRS updateLaunch(@PathVariable String projectName, - @PathVariable Long launchId, - @RequestBody @Validated UpdateLaunchRQ updateLaunchRQ, + @PathVariable Long launchId, @RequestBody @Validated UpdateLaunchRQ updateLaunchRQ, @AuthenticationPrincipal ReportPortalUser user) { return updateLaunchHandler.updateLaunch(launchId, - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user, - updateLaunchRQ); + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user, updateLaunchRQ + ); } @Transactional @PutMapping("/update") @PreAuthorize(ALLOWED_TO_REPORT) @ResponseStatus(OK) - @ApiOperation("Updates launches for specified project") + @Operation(summary = "Updates launches for specified project") public List updateLaunches(@PathVariable String projectName, @RequestBody @Validated BulkRQ rq, @AuthenticationPrincipal ReportPortalUser user) { return updateLaunchHandler.updateLaunch(rq, - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user); + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user + ); } @Transactional @DeleteMapping("/{launchId}") @PreAuthorize(ALLOWED_TO_REPORT) @ResponseStatus(OK) - @ApiOperation("Delete specified launch by ID") + @Operation(summary = "Delete specified launch by ID") public OperationCompletionRS deleteLaunch(@PathVariable String projectName, - @PathVariable Long launchId, - @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable Long launchId, @AuthenticationPrincipal ReportPortalUser user) { return deleteLaunchMessageHandler.deleteLaunch(launchId, - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user); + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user + ); } @Transactional(readOnly = true) @GetMapping("/{launchId}") @ResponseStatus(OK) - @ApiOperation("Get specified launch by ID") + @Operation(summary = "Get specified launch by ID") public LaunchResource getLaunch(@PathVariable String projectName, @PathVariable String launchId, @AuthenticationPrincipal ReportPortalUser user) { return getLaunchMessageHandler.getLaunch(launchId, - projectExtractor.extractProjectDetails(user, normalizeId(projectName))); + projectExtractor.extractProjectDetails(user, normalizeId(projectName)) + ); } @Transactional(readOnly = true) @GetMapping("/uuid/{launchId}") @ResponseStatus(OK) - @ApiOperation("Get specified launch by UUID") + @Operation(summary = "Get specified launch by UUID") public LaunchResource getLaunchByUuid(@PathVariable String projectName, - @PathVariable String launchId, - @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable String launchId, @AuthenticationPrincipal ReportPortalUser user) { return getLaunchMessageHandler.getLaunch(launchId, - projectExtractor.extractProjectDetails(user, normalizeId(projectName))); + projectExtractor.extractProjectDetails(user, normalizeId(projectName)) + ); } @Transactional(readOnly = true) @GetMapping @ResponseStatus(OK) - @ApiOperation("Get list of project launches by filter") + @Operation(summary = "Get list of project launches by filter") public Iterable getProjectLaunches(@PathVariable String projectName, - @FilterFor(Launch.class) Filter filter, - @SortFor(Launch.class) Pageable pageable, @AuthenticationPrincipal ReportPortalUser user) { + @FilterFor(Launch.class) Filter filter, @SortFor(Launch.class) Pageable pageable, + @AuthenticationPrincipal ReportPortalUser user) { return getLaunchMessageHandler.getProjectLaunches( - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), - filter, - pageable, + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), filter, pageable, user.getUsername() ); } @@ -271,10 +268,10 @@ public Iterable getProjectLaunches(@PathVariable String projectN @Transactional(readOnly = true) @GetMapping(value = "/latest") @ResponseStatus(OK) - @ApiOperation("Get list of latest project launches by filter") + @Operation(summary = "Get list of latest project launches by filter") public Iterable getLatestLaunches(@PathVariable String projectName, - @FilterFor(Launch.class) Filter filter, - @SortFor(Launch.class) Pageable pageable, @AuthenticationPrincipal ReportPortalUser user) { + @FilterFor(Launch.class) Filter filter, @SortFor(Launch.class) Pageable pageable, + @AuthenticationPrincipal ReportPortalUser user) { return getLaunchMessageHandler.getLatestLaunches( projectExtractor.extractProjectDetails(user, normalizeId(projectName)), filter, pageable); } @@ -282,10 +279,10 @@ public Iterable getLatestLaunches(@PathVariable String projectNa @GetMapping(value = "/mode") @ResponseBody @ResponseStatus(OK) - @ApiOperation("Get launches of specified project from DEBUG mode") + @Operation(summary = "Get launches of specified project from DEBUG mode") public Iterable getDebugLaunches(@PathVariable String projectName, - @FilterFor(Launch.class) Filter filter, - @SortFor(Launch.class) Pageable pageable, @AuthenticationPrincipal ReportPortalUser user) { + @FilterFor(Launch.class) Filter filter, @SortFor(Launch.class) Pageable pageable, + @AuthenticationPrincipal ReportPortalUser user) { return getLaunchMessageHandler.getDebugLaunches( projectExtractor.extractProjectDetails(user, normalizeId(projectName)), filter, pageable); } @@ -293,7 +290,7 @@ public Iterable getDebugLaunches(@PathVariable String projectNam @Transactional(readOnly = true) @GetMapping(value = "/attribute/keys") @ResponseStatus(OK) - @ApiOperation("Get all unique attribute keys of project launches") + @Operation(summary = "Get all unique attribute keys of project launches") public List getAttributeKeys(@PathVariable String projectName, @RequestParam(value = "filter." + "cnt." + "attributeKey") String value, @AuthenticationPrincipal ReportPortalUser user) { @@ -304,7 +301,7 @@ public List getAttributeKeys(@PathVariable String projectName, @Transactional(readOnly = true) @GetMapping(value = "/attribute/values") @ResponseStatus(OK) - @ApiOperation("Get all unique attribute values of project launches") + @Operation(summary = "Get all unique attribute values of project launches") public List getAttributeValues(@PathVariable String projectName, @RequestParam(value = "filter." + "eq." + "attributeKey", required = false) String key, @RequestParam(value = "filter." + "cnt." + "attributeValue") String value, @@ -315,13 +312,12 @@ public List getAttributeValues(@PathVariable String projectName, @GetMapping(value = "/cluster/{launchId}") @ResponseStatus(OK) - @ApiOperation("Get all index clusters of the launch") + @Operation(summary = "Get all index clusters of the launch") public Iterable getClusters(@PathVariable String projectName, @PathVariable String launchId, Pageable pageable, @AuthenticationPrincipal ReportPortalUser user) { return getLaunchMessageHandler.getClusters(launchId, - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), - pageable + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), pageable ); } @@ -329,18 +325,19 @@ public Iterable getClusters(@PathVariable String projectNam @PutMapping(value = "/info") @PreAuthorize(PROJECT_MANAGER_OR_ADMIN) @ResponseStatus(OK) - @ApiOperation("Bulk update attributes and description") + @Operation(summary = "Bulk update attributes and description") public OperationCompletionRS bulkUpdate(@PathVariable String projectName, @RequestBody @Validated BulkInfoUpdateRQ bulkInfoUpdateRQ, @AuthenticationPrincipal ReportPortalUser user) { return updateLaunchHandler.bulkInfoUpdate(bulkInfoUpdateRQ, - projectExtractor.extractProjectDetails(user, projectName)); + projectExtractor.extractProjectDetails(user, projectName) + ); } @Transactional(readOnly = true) @GetMapping(value = "/owners") @ResponseStatus(OK) - @ApiOperation("Get all unique owners of project launches") + @Operation(summary = "Get all unique owners of project launches") public List getAllOwners(@PathVariable String projectName, @RequestParam(value = "filter." + "cnt." + "user") String value, @RequestParam(value = "mode", required = false, defaultValue = "DEFAULT") String mode, @@ -352,11 +349,10 @@ public List getAllOwners(@PathVariable String projectName, @Transactional(readOnly = true) @GetMapping(value = "/names") @ResponseStatus(OK) - @ApiOperation("Get launch names of project") + @Operation(summary = "Get launch names of project") public List getAllLaunchNames(@PathVariable String projectName, - @RequestParam(value = "filter." + "cnt." - + "name", required = false, defaultValue = "") String value, - @AuthenticationPrincipal ReportPortalUser user) { + @RequestParam(value = "filter." + "cnt." + "name", required = false, defaultValue = "") + String value, @AuthenticationPrincipal ReportPortalUser user) { return getLaunchMessageHandler.getLaunchNames( projectExtractor.extractProjectDetails(user, normalizeId(projectName)), value); } @@ -364,7 +360,7 @@ public List getAllLaunchNames(@PathVariable String projectName, @Transactional(readOnly = true) @GetMapping(value = "/compare") @ResponseStatus(OK) - @ApiOperation("Compare launches") + @Operation(summary = "Compare launches") public Map> compareLaunches(@PathVariable String projectName, @RequestParam(value = "ids") Long[] ids, @AuthenticationPrincipal ReportPortalUser user) { return getLaunchMessageHandler.getLaunchesComparisonInfo( @@ -375,34 +371,37 @@ public Map> compareLaunches(@PathVariable S @PostMapping("/merge") @PreAuthorize(ALLOWED_TO_REPORT) @ResponseStatus(OK) - @ApiOperation("Merge set of specified launches in common one") + @Operation(summary = "Merge set of specified launches in common one") public LaunchResource mergeLaunches(@PathVariable String projectName, - @ApiParam(value = "Merge launches request body", required = true) @RequestBody @Validated MergeLaunchesRQ mergeLaunchesRQ, - @AuthenticationPrincipal ReportPortalUser user) { + @Parameter(description = "Merge launches request body", required = true) @RequestBody @Validated + MergeLaunchesRQ mergeLaunchesRQ, @AuthenticationPrincipal ReportPortalUser user) { return mergeLaunchesHandler.mergeLaunches( projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user, - mergeLaunchesRQ); + mergeLaunchesRQ + ); } @Transactional @PostMapping(value = "/analyze") @ResponseStatus(OK) - @ApiOperation("Start launch auto-analyzer on demand") + @Operation(summary = "Start launch auto-analyzer on demand") public OperationCompletionRS startLaunchAnalyzer(@PathVariable String projectName, @RequestBody @Validated AnalyzeLaunchRQ analyzeLaunchRQ, @AuthenticationPrincipal ReportPortalUser user) { return updateLaunchHandler.startLaunchAnalyzer(analyzeLaunchRQ, - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user); + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user + ); } @PostMapping(value = "/cluster") @ResponseStatus(OK) - @ApiOperation("Create launch clusters") + @Operation(summary = "Create launch clusters") public OperationCompletionRS createClusters(@PathVariable String projectName, @RequestBody @Validated CreateClustersRQ createClustersRQ, @AuthenticationPrincipal ReportPortalUser user) { return updateLaunchHandler.createClusters(createClustersRQ, - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user); + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user + ); } @Transactional(readOnly = true) @@ -410,8 +409,7 @@ public OperationCompletionRS createClusters(@PathVariable String projectName, @ResponseStatus(OK) public Map getStatuses(@PathVariable String projectName, - @RequestParam(value = "ids") Long[] ids, - @AuthenticationPrincipal ReportPortalUser user) { + @RequestParam(value = "ids") Long[] ids, @AuthenticationPrincipal ReportPortalUser user) { return getLaunchMessageHandler.getStatuses( projectExtractor.extractProjectDetails(user, normalizeId(projectName)), ids); } @@ -420,9 +418,10 @@ public Map getStatuses(@PathVariable String projectName, @GetMapping(value = "/{launchId}/report") @ResponseStatus(OK) @PreAuthorize(ASSIGNED_TO_PROJECT) - @ApiOperation(value = "Export specified launch", notes = "Only following formats are supported: pdf (by default), xls, html.") + @Operation(summary = "Export specified launch", description = "Only following formats are supported: pdf (by default), xls, html.") public void getLaunchReport(@PathVariable String projectName, @PathVariable Long launchId, - @ApiParam(allowableValues = "pdf, xls, html") @RequestParam(value = "view", required = false, defaultValue = "pdf") String view, + @Parameter(schema = @Schema(allowableValues = {"pdf", "xls", "html"})) + @RequestParam(value = "view", required = false, defaultValue = "pdf") String view, @AuthenticationPrincipal ReportPortalUser user, HttpServletResponse response) { ReportFormat format = getJasperHandler.getReportFormat(view); @@ -430,14 +429,16 @@ public void getLaunchReport(@PathVariable String projectName, @PathVariable Long response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=\"RP_LAUNCH_%s_Report.%s\"", format.name(), - format.getValue()) + format.getValue() + ) ); try (OutputStream outputStream = response.getOutputStream()) { getLaunchMessageHandler.exportLaunch(launchId, format, outputStream, user); } catch (IOException e) { throw new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, - "Unable to write data to the response."); + "Unable to write data to the response." + ); } } @@ -445,31 +446,25 @@ public void getLaunchReport(@PathVariable String projectName, @PathVariable Long @DeleteMapping @PreAuthorize(ALLOWED_TO_REPORT) @ResponseStatus(OK) - @ApiOperation("Delete specified launches by ids") + @Operation(summary = "Delete specified launches by ids") public DeleteBulkRS deleteLaunches(@PathVariable String projectName, - @RequestBody @Valid DeleteBulkRQ deleteBulkRQ, + @RequestParam(value = "ids") List ids, @AuthenticationPrincipal ReportPortalUser user) { - return deleteLaunchMessageHandler.deleteLaunches(deleteBulkRQ, - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user); + return deleteLaunchMessageHandler.deleteLaunches(ids, + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user + ); } - @ApiImplicitParams( - @ApiImplicitParam(name = "launchImportRq", dataType = "LaunchImportRQ", paramType = "body") - ) - @PostMapping(value = "/import", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) + @PostMapping(value = "/import", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }) @ResponseStatus(OK) - @ApiOperation(value = "Import junit xml report", notes = "Only following formats are supported: zip and xml.") + @Operation(summary = "Import junit xml report", description = "Only following formats are supported: zip and xml.") public OperationCompletionRS importLaunch(@PathVariable String projectName, - @RequestParam("file") MultipartFile file, - @AuthenticationPrincipal ReportPortalUser user, HttpServletRequest request, + @RequestParam("file") MultipartFile file, @AuthenticationPrincipal ReportPortalUser user, + HttpServletRequest request, @RequestPart(required = false) @Valid LaunchImportRQ launchImportRq) { return importLaunchHandler.importLaunch( - projectExtractor.extractProjectDetails(user, normalizeId(projectName)), - user, - "XUNIT", - file, - composeBaseUrl(request), - launchImportRq + projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user, "XUNIT", file, + composeBaseUrl(request), launchImportRq ); } } diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/LogAsyncController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/LogAsyncController.java index 980ac468fa..6c908d762b 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/LogAsyncController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/LogAsyncController.java @@ -30,13 +30,15 @@ import com.epam.ta.reportportal.core.log.CreateLogHandler; import com.epam.ta.reportportal.core.logging.HttpLogging; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.BatchElementCreatedRS; -import com.epam.ta.reportportal.ws.model.BatchSaveOperatingRS; -import com.epam.ta.reportportal.ws.model.Constants; -import com.epam.ta.reportportal.ws.model.EntryCreatedAsyncRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; -import io.swagger.annotations.ApiOperation; +import com.epam.ta.reportportal.ws.reporting.BatchElementCreatedRS; +import com.epam.ta.reportportal.ws.reporting.BatchSaveOperatingRS; +import com.epam.ta.reportportal.ws.reporting.Constants; +import com.epam.ta.reportportal.ws.reporting.EntryCreatedAsyncRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; +import io.swagger.v3.oas.annotations.Hidden; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import javax.servlet.http.HttpServletRequest; import javax.validation.Validator; import org.apache.commons.collections4.MultiValuedMap; @@ -56,7 +58,6 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; -import springfox.documentation.annotations.ApiIgnore; /** * @author Konstantin Antipin @@ -64,6 +65,7 @@ @RestController @RequestMapping("/v2/{projectName}/log") @PreAuthorize(ASSIGNED_TO_PROJECT) +@Tag(name = "log-async-controller", description = "Log Async Controller") public class LogAsyncController { private final ProjectExtractor projectExtractor; @@ -88,7 +90,7 @@ public LogAsyncController(ProjectExtractor projectExtractor, @HttpLogging @PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE}) @ResponseStatus(CREATED) - @ApiIgnore + @Hidden @PreAuthorize(ALLOWED_TO_REPORT) public EntryCreatedAsyncRS createLog(@PathVariable String projectName, @RequestBody SaveLogRQ createLogRQ, @@ -101,7 +103,7 @@ public EntryCreatedAsyncRS createLog(@PathVariable String projectName, @HttpLogging @PostMapping(value = "/entry", consumes = {MediaType.APPLICATION_JSON_VALUE}) @ResponseStatus(CREATED) - @ApiOperation("Create log") + @Operation(summary = "Create log") @PreAuthorize(ALLOWED_TO_REPORT) public EntryCreatedAsyncRS createLogEntry(@PathVariable String projectName, @RequestBody SaveLogRQ createLogRQ, @@ -113,7 +115,7 @@ public EntryCreatedAsyncRS createLogEntry(@PathVariable String projectName, @HttpLogging @PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) - @ApiOperation("Create log (batching operation)") + @Operation(summary = "Create log (batching operation)") // Specific handler should be added for springfox in case of similar POST // request mappings // @Async diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/LogController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/LogController.java index c55898dc0d..fd84a146a5 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/LogController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/LogController.java @@ -38,23 +38,25 @@ import com.epam.ta.reportportal.core.log.GetLogHandler; import com.epam.ta.reportportal.core.log.impl.PagedLogResource; import com.epam.ta.reportportal.entity.log.Log; +import com.epam.ta.reportportal.model.log.GetLogsUnderRq; +import com.epam.ta.reportportal.model.log.LogResource; +import com.epam.ta.reportportal.model.log.SearchLogRq; +import com.epam.ta.reportportal.model.log.SearchLogRs; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.BatchElementCreatedRS; -import com.epam.ta.reportportal.ws.model.BatchSaveOperatingRS; -import com.epam.ta.reportportal.ws.model.Constants; -import com.epam.ta.reportportal.ws.model.EntryCreatedAsyncRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.log.GetLogsUnderRq; -import com.epam.ta.reportportal.ws.model.log.LogResource; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; -import com.epam.ta.reportportal.ws.model.log.SearchLogRq; -import com.epam.ta.reportportal.ws.model.log.SearchLogRs; +import com.epam.ta.reportportal.ws.reporting.BatchElementCreatedRS; +import com.epam.ta.reportportal.ws.reporting.BatchSaveOperatingRS; +import com.epam.ta.reportportal.ws.reporting.Constants; +import com.epam.ta.reportportal.ws.reporting.EntryCreatedAsyncRS; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; import com.epam.ta.reportportal.ws.resolver.FilterFor; import com.epam.ta.reportportal.ws.resolver.SortFor; import com.google.common.collect.ImmutableMap; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; +import io.swagger.v3.oas.annotations.Hidden; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; import java.io.Serializable; import java.util.List; import java.util.Map; @@ -82,7 +84,6 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; -import springfox.documentation.annotations.ApiIgnore; /** * @author Pavel Bortnik @@ -90,6 +91,7 @@ @RestController @RequestMapping("/v1/{projectName}/log") @PreAuthorize(ASSIGNED_TO_PROJECT) +@Tag(name = "log-controller", description = "Log Controller") public class LogController { private final ProjectExtractor projectExtractor; @@ -102,8 +104,7 @@ public class LogController { @Autowired public LogController(ProjectExtractor projectExtractor, @Autowired CreateLogHandler createLogHandler, DeleteLogHandler deleteLogHandler, - GetLogHandler getLogHandler, - SearchLogService searchLogService, Validator validator) { + GetLogHandler getLogHandler, SearchLogService searchLogService, Validator validator) { this.projectExtractor = projectExtractor; this.createLogHandler = createLogHandler; this.deleteLogHandler = deleteLogHandler; @@ -113,47 +114,45 @@ public LogController(ProjectExtractor projectExtractor, } /** - * @deprecated in favour of - * {@link LogController#createLogEntry(String, SaveLogRQ, ReportPortalUser)} because of mapping - * collisions + * @deprecated in favour of {@link LogController#createLogEntry(String, SaveLogRQ, + * ReportPortalUser)} because of mapping collisions */ /* Report client API */ @Deprecated @PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE}) @ResponseStatus(CREATED) - @ApiIgnore + @Hidden @PreAuthorize(ALLOWED_TO_REPORT) public EntryCreatedAsyncRS createLog(@PathVariable String projectName, - @RequestBody SaveLogRQ createLogRQ, - @AuthenticationPrincipal ReportPortalUser user) { + @RequestBody SaveLogRQ createLogRQ, @AuthenticationPrincipal ReportPortalUser user) { validateSaveRQ(validator, createLogRQ); return createLogHandler.createLog(createLogRQ, null, - projectExtractor.extractProjectDetails(user, projectName)); + projectExtractor.extractProjectDetails(user, projectName) + ); } /* Report client API */ @PostMapping(value = "/entry", consumes = {MediaType.APPLICATION_JSON_VALUE}) @ResponseStatus(CREATED) - @ApiOperation("Create log") + @Operation(summary = "Create log") @PreAuthorize(ALLOWED_TO_REPORT) public EntryCreatedAsyncRS createLogEntry(@PathVariable String projectName, - @RequestBody SaveLogRQ createLogRQ, - @AuthenticationPrincipal ReportPortalUser user) { + @RequestBody SaveLogRQ createLogRQ, @AuthenticationPrincipal ReportPortalUser user) { validateSaveRQ(validator, createLogRQ); return createLogHandler.createLog(createLogRQ, null, - projectExtractor.extractProjectDetails(user, projectName)); + projectExtractor.extractProjectDetails(user, projectName) + ); } @PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) - @ApiOperation("Create log (batching operation)") + @Operation(summary = "Create log (batching operation)") // Specific handler should be added for springfox in case of similar POST // request mappings // @Async @PreAuthorize(ALLOWED_TO_REPORT) public ResponseEntity createLog(@PathVariable String projectName, @RequestPart(value = Constants.LOG_REQUEST_JSON_PART) SaveLogRQ[] createLogRQs, - HttpServletRequest request, - @AuthenticationPrincipal ReportPortalUser user) { + HttpServletRequest request, @AuthenticationPrincipal ReportPortalUser user) { /* * Since this is multipart request we can retrieve list of uploaded @@ -180,7 +179,8 @@ public ResponseEntity createLog(@PathVariable String proje BusinessRule.expect(data, Predicates.notNull()) .verify(ErrorType.BINARY_DATA_CANNOT_BE_SAVED, Suppliers.formattedSupplier("There is no request part or file with name {}", - filename) + filename + ) ); /* * If provided content type is null or this is octet @@ -189,12 +189,14 @@ public ResponseEntity createLog(@PathVariable String proje */ //noinspection ConstantConditions responseItem = createLogHandler.createLog(createLogRq, data, - projectExtractor.extractProjectDetails(user, projectName)); + projectExtractor.extractProjectDetails(user, projectName) + ); } response.addResponse(new BatchElementCreatedRS(responseItem.getId())); } catch (Exception e) { response.addResponse(new BatchElementCreatedRS(ExceptionUtils.getStackTrace(e), - ExceptionUtils.getMessage(e))); + ExceptionUtils.getMessage(e) + )); } } return new ResponseEntity<>(response, CREATED); @@ -204,56 +206,59 @@ public ResponseEntity createLog(@PathVariable String proje /* Frontend API */ @RequestMapping(value = "/{logId}", method = RequestMethod.DELETE) - @ApiOperation("Delete log") + @Operation(summary = "Delete log") @Transactional public OperationCompletionRS deleteLog(@PathVariable String projectName, @PathVariable Long logId, @AuthenticationPrincipal ReportPortalUser user) { return deleteLogHandler.deleteLog(logId, - projectExtractor.extractProjectDetails(user, projectName), user); + projectExtractor.extractProjectDetails(user, projectName), user + ); } @RequestMapping(method = RequestMethod.GET) - @ApiOperation("Get logs by filter") + @Operation(summary = "Get logs by filter") @Transactional(readOnly = true) public Iterable getLogs(@PathVariable String projectName, - @RequestParam(value = DEFAULT_FILTER_PREFIX + UNDR - + CRITERIA_PATH, required = false) String underPath, - @FilterFor(Log.class) Filter filter, + @RequestParam(value = DEFAULT_FILTER_PREFIX + UNDR + CRITERIA_PATH, required = false) + String underPath, @FilterFor(Log.class) Filter filter, @SortDefault({"logTime"}) @SortFor(Log.class) Pageable pageable, @AuthenticationPrincipal ReportPortalUser user) { return getLogHandler.getLogs(underPath, - projectExtractor.extractProjectDetails(user, projectName), filter, pageable); + projectExtractor.extractProjectDetails(user, projectName), filter, pageable + ); } @PostMapping(value = "/under") - @ApiOperation("Get logs under items") + @Operation(summary = "Get logs under items") @Transactional(readOnly = true) public Map> getLogsUnder(@PathVariable String projectName, @RequestBody GetLogsUnderRq logsUnderRq, @AuthenticationPrincipal ReportPortalUser user) { return getLogHandler.getLogs(logsUnderRq, - projectExtractor.extractProjectDetails(user, projectName)); + projectExtractor.extractProjectDetails(user, projectName) + ); } @GetMapping(value = "/{logId}/page") - @ApiOperation("Get logs by filter") + @Operation(summary = "Get logs by filter") @Transactional(readOnly = true) public Map getPageNumber(@PathVariable String projectName, - @PathVariable Long logId, - @FilterFor(Log.class) Filter filter, @SortFor(Log.class) Pageable pageable, - @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable Long logId, @FilterFor(Log.class) Filter filter, + @SortFor(Log.class) Pageable pageable, @AuthenticationPrincipal ReportPortalUser user) { return ImmutableMap.builder().put("number", getLogHandler.getPageNumber(logId, - projectExtractor.extractProjectDetails(user, projectName), filter, pageable) + projectExtractor.extractProjectDetails(user, projectName), filter, pageable + ) ).build(); } @GetMapping(value = "/{logId}") - @ApiOperation("Get log by ID") + @Operation(summary = "Get log by ID") @Transactional(readOnly = true) public LogResource getLog(@PathVariable String projectName, @PathVariable String logId, @AuthenticationPrincipal ReportPortalUser user) { return getLogHandler.getLog(logId, projectExtractor.extractProjectDetails(user, projectName), - user); + user + ); } /** @@ -262,44 +267,48 @@ public LogResource getLog(@PathVariable String projectName, @PathVariable String */ @Deprecated(since = "5.8", forRemoval = true) @GetMapping(value = "/uuid/{logId}") - @ApiOperation("Get log by UUID (Will be removed in version 6.0)") + @Operation(summary = "Get log by UUID (Will be removed in version 6.0)") @Transactional(readOnly = true) public LogResource getLogByUuid(@PathVariable String projectName, @PathVariable String logId, @AuthenticationPrincipal ReportPortalUser user) { return getLogHandler.getLog(logId, projectExtractor.extractProjectDetails(user, projectName), - user); + user + ); } @GetMapping(value = "/nested/{parentId}") - @ApiOperation("Get nested steps with logs for the parent Test Item") + @Operation(summary = "Get nested steps with logs for the parent Test Item") @Transactional(readOnly = true) public Iterable getNestedItems(@PathVariable String projectName, @PathVariable Long parentId, - @ApiParam(required = false) @RequestParam Map params, - @FilterFor(Log.class) Filter filter, - @SortFor(Log.class) Pageable pageable, @AuthenticationPrincipal ReportPortalUser user) { + @Parameter(required = false) @RequestParam Map params, + @FilterFor(Log.class) Filter filter, @SortFor(Log.class) Pageable pageable, + @AuthenticationPrincipal ReportPortalUser user) { return getLogHandler.getNestedItems(parentId, - projectExtractor.extractProjectDetails(user, projectName), params, filter, pageable); + projectExtractor.extractProjectDetails(user, projectName), params, filter, pageable + ); } @GetMapping(value = "/locations/{parentId}") - @ApiOperation("Get next or previous log in test item") + @Operation(summary = "Get next or previous log in test item") @Transactional(readOnly = true) public List getErrorPage(@PathVariable String projectName, @PathVariable Long parentId, @RequestParam Map params, @FilterFor(Log.class) Filter filter, @SortFor(Log.class) Pageable pageable, @AuthenticationPrincipal ReportPortalUser user) { return getLogHandler.getLogsWithLocation(parentId, - projectExtractor.extractProjectDetails(user, projectName), params, filter, pageable); + projectExtractor.extractProjectDetails(user, projectName), params, filter, pageable + ); } @PostMapping("search/{itemId}") @ResponseStatus(OK) - @ApiOperation("Search test items with similar error logs") + @Operation(summary = "Search test items with similar error logs") public Iterable searchLogs(@PathVariable String projectName, @RequestBody SearchLogRq request, @PathVariable Long itemId, @AuthenticationPrincipal ReportPortalUser user) { return searchLogService.search(itemId, request, - projectExtractor.extractProjectDetails(user, projectName)); + projectExtractor.extractProjectDetails(user, projectName) + ); } } diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/OnboardingController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/OnboardingController.java index 92aebdda3a..899e16a940 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/OnboardingController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/OnboardingController.java @@ -16,7 +16,8 @@ package com.epam.ta.reportportal.ws.controller; import com.epam.ta.reportportal.core.onboarding.OnboardingService; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @@ -27,6 +28,7 @@ */ @RestController @RequestMapping("/v1/onboarding") +@Tag(name = "onboarding-controller", description = "Onboarding Controller") public class OnboardingController { private final OnboardingService onboardingService; @@ -40,7 +42,7 @@ public OnboardingController(OnboardingService onboardingService) { * something else. */ @GetMapping(value = { "" }) - @ApiOperation("Return onboarding information for page if available, -1 otherwise") + @Operation(summary = "Return onboarding information for page if available, -1 otherwise") public Object onBoarding(@RequestParam(value = "page", defaultValue = "GENERAL") String page) { // object because it can be different types of onboarding data Object data = onboardingService.getOnboardingDataForPageIfAvailable(page); diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/PluginController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/PluginController.java index 8614e9108b..da775c900e 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/PluginController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/PluginController.java @@ -16,111 +16,125 @@ package com.epam.ta.reportportal.ws.controller; +import static com.epam.ta.reportportal.auth.permissions.Permissions.ADMIN_ONLY; +import static com.epam.ta.reportportal.auth.permissions.Permissions.ASSIGNED_TO_PROJECT; +import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; + import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.core.integration.ExecuteIntegrationHandler; import com.epam.ta.reportportal.core.integration.plugin.CreatePluginHandler; import com.epam.ta.reportportal.core.integration.plugin.DeletePluginHandler; import com.epam.ta.reportportal.core.integration.plugin.GetPluginHandler; import com.epam.ta.reportportal.core.integration.plugin.UpdatePluginHandler; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.integration.IntegrationTypeResource; +import com.epam.ta.reportportal.model.integration.UpdatePluginStateRQ; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.integration.IntegrationTypeResource; -import com.epam.ta.reportportal.ws.model.integration.UpdatePluginStateRQ; -import io.swagger.annotations.ApiOperation; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import java.util.List; +import java.util.Map; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.List; -import java.util.Map; - -import static com.epam.ta.reportportal.auth.permissions.Permissions.ADMIN_ONLY; -import static com.epam.ta.reportportal.auth.permissions.Permissions.ASSIGNED_TO_PROJECT; -import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; - /** * @author Ivan Budayeu */ @RestController @RequestMapping(value = "/v1/plugin") +@Tag(name = "plugin-controller", description = "Plugin Controller") public class PluginController { - private final CreatePluginHandler createPluginHandler; - private final UpdatePluginHandler updatePluginHandler; - private final GetPluginHandler getPluginHandler; - private final DeletePluginHandler deletePluginHandler; - private final ExecuteIntegrationHandler executeIntegrationHandler; - private final ProjectExtractor projectExtractor; + private final CreatePluginHandler createPluginHandler; + private final UpdatePluginHandler updatePluginHandler; + private final GetPluginHandler getPluginHandler; + private final DeletePluginHandler deletePluginHandler; + private final ExecuteIntegrationHandler executeIntegrationHandler; + private final ProjectExtractor projectExtractor; - @Autowired - public PluginController(CreatePluginHandler createPluginHandler, UpdatePluginHandler updatePluginHandler, - GetPluginHandler getPluginHandler, DeletePluginHandler deletePluginHandler, ExecuteIntegrationHandler executeIntegrationHandler, - ProjectExtractor projectExtractor) { - this.createPluginHandler = createPluginHandler; - this.updatePluginHandler = updatePluginHandler; - this.getPluginHandler = getPluginHandler; - this.deletePluginHandler = deletePluginHandler; - this.executeIntegrationHandler = executeIntegrationHandler; - this.projectExtractor = projectExtractor; - } + @Autowired + public PluginController(CreatePluginHandler createPluginHandler, + UpdatePluginHandler updatePluginHandler, GetPluginHandler getPluginHandler, + DeletePluginHandler deletePluginHandler, ExecuteIntegrationHandler executeIntegrationHandler, + ProjectExtractor projectExtractor) { + this.createPluginHandler = createPluginHandler; + this.updatePluginHandler = updatePluginHandler; + this.getPluginHandler = getPluginHandler; + this.deletePluginHandler = deletePluginHandler; + this.executeIntegrationHandler = executeIntegrationHandler; + this.projectExtractor = projectExtractor; + } - @Transactional - @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - @ResponseStatus(HttpStatus.CREATED) - @ApiOperation("Upload new Report Portal plugin") - @PreAuthorize(ADMIN_ONLY) - public EntryCreatedRS uploadPlugin(@NotNull @RequestParam("file") MultipartFile pluginFile, - @AuthenticationPrincipal ReportPortalUser user) { - return createPluginHandler.uploadPlugin(pluginFile, user); - } + @Transactional + @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + @ResponseStatus(HttpStatus.CREATED) + @Operation(summary = "Upload new Report Portal plugin") + @PreAuthorize(ADMIN_ONLY) + public EntryCreatedRS uploadPlugin(@NotNull @RequestParam("file") MultipartFile pluginFile, + @AuthenticationPrincipal ReportPortalUser user) { + return createPluginHandler.uploadPlugin(pluginFile, user); + } - @Transactional - @PutMapping(value = "/{pluginId}") - @ResponseStatus(HttpStatus.OK) - @ApiOperation("Update Report Portal plugin state") - @PreAuthorize(ADMIN_ONLY) - public OperationCompletionRS updatePluginState(@PathVariable(value = "pluginId") Long id, - @RequestBody @Valid UpdatePluginStateRQ updatePluginStateRQ, @AuthenticationPrincipal ReportPortalUser user) { - return updatePluginHandler.updatePluginState(id, updatePluginStateRQ, user); - } + @Transactional + @PutMapping(value = "/{pluginId}") + @ResponseStatus(HttpStatus.OK) + @Operation(summary = "Update Report Portal plugin state") + @PreAuthorize(ADMIN_ONLY) + public OperationCompletionRS updatePluginState(@PathVariable(value = "pluginId") Long id, + @RequestBody @Valid UpdatePluginStateRQ updatePluginStateRQ, + @AuthenticationPrincipal ReportPortalUser user) { + return updatePluginHandler.updatePluginState(id, updatePluginStateRQ, user); + } - @Transactional(readOnly = true) - @GetMapping - @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get all available plugins") - public List getPlugins(@AuthenticationPrincipal ReportPortalUser user) { - return getPluginHandler.getPlugins(); - } + @Transactional(readOnly = true) + @GetMapping + @ResponseStatus(HttpStatus.OK) + @Operation(summary = "Get all available plugins") + public List getPlugins(@AuthenticationPrincipal ReportPortalUser user) { + return getPluginHandler.getPlugins(); + } - @Transactional - @DeleteMapping(value = "/{pluginId}") - @ResponseStatus(HttpStatus.OK) - @ApiOperation("Delete plugin by id") - @PreAuthorize(ADMIN_ONLY) - public OperationCompletionRS deletePlugin(@PathVariable(value = "pluginId") Long id, @AuthenticationPrincipal ReportPortalUser user) { - return deletePluginHandler.deleteById(id, user); - } + @Transactional + @DeleteMapping(value = "/{pluginId}") + @ResponseStatus(HttpStatus.OK) + @Operation(summary = "Delete plugin by id") + @PreAuthorize(ADMIN_ONLY) + public OperationCompletionRS deletePlugin(@PathVariable(value = "pluginId") Long id, + @AuthenticationPrincipal ReportPortalUser user) { + return deletePluginHandler.deleteById(id, user); + } - @Transactional - @PutMapping(value = "{projectName}/{pluginName}/common/{command}", consumes = { APPLICATION_JSON_VALUE }) - @ResponseStatus(HttpStatus.OK) - @PreAuthorize(ASSIGNED_TO_PROJECT) - @ApiOperation("Execute command to the plugin instance") - public Object executePluginCommand(@PathVariable String projectName, @PathVariable("pluginName") String pluginName, - @PathVariable("command") String command, @RequestBody Map executionParams, - @AuthenticationPrincipal ReportPortalUser user) { - return executeIntegrationHandler.executeCommand(projectExtractor.extractProjectDetails(user, projectName), - pluginName, - command, - executionParams - ); - } + @Transactional + @PutMapping(value = "{projectName}/{pluginName}/common/{command}", consumes = { + APPLICATION_JSON_VALUE }) + @ResponseStatus(HttpStatus.OK) + @PreAuthorize(ASSIGNED_TO_PROJECT) + @Operation(summary = "Execute command to the plugin instance") + public Object executePluginCommand(@PathVariable String projectName, + @PathVariable("pluginName") String pluginName, @PathVariable("command") String command, + @RequestBody Map executionParams, + @AuthenticationPrincipal ReportPortalUser user) { + return executeIntegrationHandler.executeCommand( + projectExtractor.extractProjectDetails(user, projectName), pluginName, command, + executionParams + ); + } } diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/PluginPublicController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/PluginPublicController.java index b616ce2210..3e5fec00fe 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/PluginPublicController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/PluginPublicController.java @@ -22,9 +22,10 @@ import com.epam.ta.reportportal.core.integration.plugin.GetPluginHandler; import com.epam.ta.reportportal.core.integration.plugin.binary.PluginFilesProvider; import com.epam.ta.reportportal.entity.attachment.BinaryData; +import com.epam.ta.reportportal.model.integration.IntegrationTypeResource; import com.epam.ta.reportportal.util.BinaryDataResponseWriter; -import com.epam.ta.reportportal.ws.model.integration.IntegrationTypeResource; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; @@ -42,6 +43,7 @@ */ @RestController @RequestMapping(value = "/v1/plugin/public") +@Tag(name = "plugin-public-controller", description = "Plugin Public Controller") public class PluginPublicController { private final PluginFilesProvider pluginPublicFilesProvider; @@ -60,17 +62,16 @@ public PluginPublicController(PluginFilesProvider pluginPublicFilesProvider, @GetMapping(value = "/{pluginName}/file/{name}") @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get public plugin file without authentication") + @Operation(summary = "Get public plugin file without authentication") public void getPublicFile(@PathVariable(value = "pluginName") String pluginName, - @PathVariable(value = "name") String fileName, - HttpServletResponse response) { + @PathVariable(value = "name") String fileName, HttpServletResponse response) { final BinaryData binaryData = pluginPublicFilesProvider.load(pluginName, fileName); binaryDataResponseWriter.write(binaryData, response); } - @PutMapping(value = "/{pluginName}/{command}", consumes = {APPLICATION_JSON_VALUE}) + @PutMapping(value = "/{pluginName}/{command}", consumes = { APPLICATION_JSON_VALUE }) @ResponseStatus(HttpStatus.OK) - @ApiOperation("Execute public command without authentication") + @Operation(summary = "Execute public command without authentication") public Object executePublicPluginCommand(@PathVariable("pluginName") String pluginName, @PathVariable("command") String command, @RequestBody Map executionParams) { return executeIntegrationHandler.executePublicCommand(pluginName, command, executionParams); @@ -78,7 +79,7 @@ public Object executePublicPluginCommand(@PathVariable("pluginName") String plug @GetMapping @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get all available public plugins") + @Operation(summary = "Get all available public plugins") public List getPlugins() { return getPluginHandler.getPublicPlugins(); } diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/ProjectController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/ProjectController.java index ee505599a1..8c25b7c861 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/ProjectController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/ProjectController.java @@ -45,34 +45,34 @@ import com.epam.ta.reportportal.entity.project.ProjectInfo; import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.DeleteBulkRS; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.preference.PreferenceResource; +import com.epam.ta.reportportal.model.project.AssignUsersRQ; +import com.epam.ta.reportportal.model.project.CreateProjectRQ; +import com.epam.ta.reportportal.model.project.ProjectInfoResource; +import com.epam.ta.reportportal.model.project.ProjectResource; +import com.epam.ta.reportportal.model.project.UnassignUsersRQ; +import com.epam.ta.reportportal.model.project.UpdateProjectRQ; +import com.epam.ta.reportportal.model.project.email.ProjectNotificationConfigDTO; +import com.epam.ta.reportportal.model.user.SearchUserResource; +import com.epam.ta.reportportal.model.user.UserResource; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.DeleteBulkRQ; -import com.epam.ta.reportportal.ws.model.DeleteBulkRS; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.preference.PreferenceResource; -import com.epam.ta.reportportal.ws.model.project.AssignUsersRQ; -import com.epam.ta.reportportal.ws.model.project.CreateProjectRQ; -import com.epam.ta.reportportal.ws.model.project.ProjectInfoResource; -import com.epam.ta.reportportal.ws.model.project.ProjectResource; -import com.epam.ta.reportportal.ws.model.project.UnassignUsersRQ; -import com.epam.ta.reportportal.ws.model.project.UpdateProjectRQ; -import com.epam.ta.reportportal.ws.model.project.email.ProjectNotificationConfigDTO; -import com.epam.ta.reportportal.ws.model.user.SearchUserResource; -import com.epam.ta.reportportal.ws.model.user.UserResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.epam.ta.reportportal.ws.resolver.FilterCriteriaResolver; import com.epam.ta.reportportal.ws.resolver.FilterFor; import com.epam.ta.reportportal.ws.resolver.SortFor; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.tags.Tag; import java.io.IOException; import java.io.OutputStream; import java.security.Principal; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; import org.jooq.Operator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -99,6 +99,7 @@ */ @RestController @RequestMapping("/v1/project") +@Tag(name = "project-controller", description = "Project Controller") public class ProjectController { private final ProjectExtractor projectExtractor; @@ -114,13 +115,11 @@ public class ProjectController { @Autowired public ProjectController(ProjectExtractor projectExtractor, GetProjectHandler getProjectHandler, - GetProjectInfoHandler projectInfoHandler, - CreateProjectHandler createProjectHandler, UpdateProjectHandler updateProjectHandler, - DeleteProjectHandler deleteProjectHandler, + GetProjectInfoHandler projectInfoHandler, CreateProjectHandler createProjectHandler, + UpdateProjectHandler updateProjectHandler, DeleteProjectHandler deleteProjectHandler, GetUserHandler getUserHandler, GetPreferenceHandler getPreference, - UpdatePreferenceHandler updatePreference, - @Qualifier("projectJasperReportHandler") - GetJasperReportHandler jasperReportHandler) { + UpdatePreferenceHandler updatePreference, @Qualifier("projectJasperReportHandler") + GetJasperReportHandler jasperReportHandler) { this.projectExtractor = projectExtractor; this.getProjectHandler = getProjectHandler; this.projectInfoHandler = projectInfoHandler; @@ -137,7 +136,7 @@ public ProjectController(ProjectExtractor projectExtractor, GetProjectHandler ge @PostMapping @ResponseStatus(CREATED) @PreAuthorize(ADMIN_ONLY) - @ApiOperation("Create new project") + @Operation(summary = "Create new project") public EntryCreatedRS createProject(@RequestBody @Validated CreateProjectRQ createProjectRQ, @AuthenticationPrincipal ReportPortalUser user) { return createProjectHandler.createProject(createProjectRQ, user); @@ -147,7 +146,7 @@ public EntryCreatedRS createProject(@RequestBody @Validated CreateProjectRQ crea @PutMapping("/{projectName}") @ResponseStatus(OK) @PreAuthorize(PROJECT_MANAGER_OR_ADMIN) - @ApiOperation(value = "Update project") + @Operation(summary = "Update project") public OperationCompletionRS updateProject(@PathVariable String projectName, @RequestBody @Validated UpdateProjectRQ updateProjectRQ, @AuthenticationPrincipal ReportPortalUser user) { @@ -158,27 +157,28 @@ public OperationCompletionRS updateProject(@PathVariable String projectName, @PutMapping("/{projectName}/notification") @ResponseStatus(OK) @PreAuthorize(PROJECT_MANAGER) - @ApiOperation("Update project notifications configuration") + @Operation(summary = "Update project notifications configuration") public OperationCompletionRS updateProjectNotificationConfig(@PathVariable String projectName, @RequestBody @Validated ProjectNotificationConfigDTO updateProjectNotificationConfigRQ, @AuthenticationPrincipal ReportPortalUser user) { return updateProjectHandler.updateProjectNotificationConfig(normalizeId(projectName), user, - updateProjectNotificationConfigRQ); + updateProjectNotificationConfigRQ + ); } @DeleteMapping @ResponseStatus(OK) @PreAuthorize(ADMIN_ONLY) - @ApiOperation(value = "Delete multiple projects", notes = "Could be deleted only by users with administrator role") - public DeleteBulkRS deleteProject(@RequestBody @Valid DeleteBulkRQ deleteBulkRQ, + @Operation(summary = "Delete multiple projects", description = "Could be deleted only by users with administrator role") + public DeleteBulkRS deleteProject(@RequestParam(value = "ids") List ids, @AuthenticationPrincipal ReportPortalUser user) { - return deleteProjectHandler.bulkDeleteProjects(deleteBulkRQ.getIds(), user); + return deleteProjectHandler.bulkDeleteProjects(ids, user); } @DeleteMapping("/{projectId}") @ResponseStatus(OK) @PreAuthorize(ADMIN_ONLY) - @ApiOperation(value = "Delete project", notes = "Could be deleted only by users with administrator role") + @Operation(summary = "Delete project", description = "Could be deleted only by users with administrator role") public OperationCompletionRS deleteProject(@PathVariable Long projectId, @AuthenticationPrincipal ReportPortalUser user) { return deleteProjectHandler.deleteProject(projectId, user); @@ -187,7 +187,7 @@ public OperationCompletionRS deleteProject(@PathVariable Long projectId, @DeleteMapping("/{projectName}/index") @ResponseStatus(OK) @PreAuthorize(PROJECT_MANAGER_OR_ADMIN) - @ApiOperation("Delete project index from ML") + @Operation(summary = "Delete project index from ML") public OperationCompletionRS deleteProjectIndex(@PathVariable String projectName, Principal principal) { return deleteProjectHandler.deleteProjectIndex(normalizeId(projectName), principal.getName()); @@ -197,7 +197,7 @@ public OperationCompletionRS deleteProjectIndex(@PathVariable String projectName @PutMapping("/{projectName}/index") @ResponseStatus(OK) @PreAuthorize(PROJECT_MANAGER_OR_ADMIN) - @ApiOperation(value = "Starts reindex all project data in ML") + @Operation(summary = "Starts reindex all project data in ML") public OperationCompletionRS indexProjectData(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user) { return updateProjectHandler.indexProjectData(normalizeId(projectName), user); @@ -206,17 +206,17 @@ public OperationCompletionRS indexProjectData(@PathVariable String projectName, @Transactional(readOnly = true) @GetMapping("/{projectName}/users") @PreAuthorize(NOT_CUSTOMER) - @ApiOperation("Get users assigned on current project") + @Operation(summary = "Get users assigned on current project") public Iterable getProjectUsers(@PathVariable String projectName, - @FilterFor(User.class) Filter filter, - @SortFor(User.class) Pageable pageable, @AuthenticationPrincipal ReportPortalUser user) { + @FilterFor(User.class) Filter filter, @SortFor(User.class) Pageable pageable, + @AuthenticationPrincipal ReportPortalUser user) { return getProjectHandler.getProjectUsers(normalizeId(projectName), filter, pageable); } @Transactional(readOnly = true) @GetMapping("/{projectName}") @PreAuthorize(ASSIGNED_TO_PROJECT) - @ApiOperation(value = "Get information about project", notes = "Only for users that are assigned to the project") + @Operation(summary = "Get information about project", description = "Only for users that are assigned to the project") public ProjectResource getProject(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user) { return getProjectHandler.getResource(normalizeId(projectName), user); @@ -226,7 +226,7 @@ public ProjectResource getProject(@PathVariable String projectName, @PutMapping("/{projectName}/unassign") @ResponseStatus(OK) @PreAuthorize(PROJECT_MANAGER) - @ApiOperation("Un assign users") + @Operation(summary = "Unassign users") public OperationCompletionRS unassignProjectUsers(@PathVariable String projectName, @RequestBody @Validated UnassignUsersRQ unassignUsersRQ, @AuthenticationPrincipal ReportPortalUser user) { @@ -237,7 +237,7 @@ public OperationCompletionRS unassignProjectUsers(@PathVariable String projectNa @PutMapping("/{projectName}/assign") @ResponseStatus(OK) @PreAuthorize(PROJECT_MANAGER) - @ApiOperation("Assign users") + @Operation(summary = "Assign users") public OperationCompletionRS assignProjectUsers(@PathVariable String projectName, @RequestBody @Validated AssignUsersRQ assignUsersRQ, @AuthenticationPrincipal ReportPortalUser user) { @@ -248,25 +248,26 @@ public OperationCompletionRS assignProjectUsers(@PathVariable String projectName @GetMapping("/{projectName}/assignable") @ResponseStatus(OK) @PreAuthorize(PROJECT_MANAGER) - @ApiOperation(value = "Load users which can be assigned to specified project", notes = "Only for users with project manager permissions") + @Operation(summary = "Load users which can be assigned to specified project", description = "Only for users with project manager permissions") public Iterable getUsersForAssign(@FilterFor(User.class) Filter filter, - @SortFor(User.class) Pageable pageable, - @PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user) { + @SortFor(User.class) Pageable pageable, @PathVariable String projectName, + @AuthenticationPrincipal ReportPortalUser user) { return getUserHandler.getUsers(filter, pageable, - projectExtractor.extractProjectDetails(user, projectName)); + projectExtractor.extractProjectDetails(user, projectName) + ); } @Transactional(readOnly = true) @GetMapping("/{projectName}/usernames") @ResponseStatus(HttpStatus.OK) @PreAuthorize(NOT_CUSTOMER) - @ApiOperation(value = "Load project users by filter", notes = "Only for users that are members of the project") + @Operation(summary = "Load project users by filter", description = "Only for users that are members of the project") public List getProjectUsers(@PathVariable String projectName, @RequestParam(value = FilterCriteriaResolver.DEFAULT_FILTER_PREFIX + Condition.CNT + "users") - String value, - @AuthenticationPrincipal ReportPortalUser user) { + String value, @AuthenticationPrincipal ReportPortalUser user) { return getProjectHandler.getUserNames(projectExtractor.extractProjectDetails(user, projectName), - normalizeId(value)); + normalizeId(value) + ); } @Transactional(readOnly = true) @@ -274,10 +275,11 @@ public List getProjectUsers(@PathVariable String projectName, @ResponseStatus(OK) @PreAuthorize(PROJECT_MANAGER) public Iterable searchForUser(@PathVariable String projectName, - @RequestParam(value = "term") String term, - Pageable pageable, @AuthenticationPrincipal ReportPortalUser user) { + @RequestParam(value = "term") String term, Pageable pageable, + @AuthenticationPrincipal ReportPortalUser user) { return getProjectHandler.getUserNames(term, - projectExtractor.extractProjectDetails(user, projectName), pageable); + projectExtractor.extractProjectDetails(user, projectName), pageable + ); } @Transactional @@ -285,10 +287,11 @@ public Iterable searchForUser(@PathVariable String projectNa @ResponseStatus(HttpStatus.OK) @PreAuthorize(ALLOWED_TO_EDIT_USER) public OperationCompletionRS addUserPreference(@PathVariable String projectName, - @PathVariable String login, - @PathVariable Long filterId, @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable String login, @PathVariable Long filterId, + @AuthenticationPrincipal ReportPortalUser user) { return updatePreference.addPreference(projectExtractor.extractProjectDetails(user, projectName), - user, filterId); + user, filterId + ); } @Transactional @@ -296,8 +299,8 @@ public OperationCompletionRS addUserPreference(@PathVariable String projectName, @ResponseStatus(HttpStatus.OK) @PreAuthorize(ALLOWED_TO_EDIT_USER) public OperationCompletionRS removeUserPreference(@PathVariable String projectName, - @PathVariable String login, - @PathVariable Long filterId, @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable String login, @PathVariable Long filterId, + @AuthenticationPrincipal ReportPortalUser user) { return updatePreference.removePreference( projectExtractor.extractProjectDetails(user, projectName), user, filterId); } @@ -306,12 +309,12 @@ public OperationCompletionRS removeUserPreference(@PathVariable String projectNa @GetMapping("/{projectName}/preference/{login}") @ResponseStatus(HttpStatus.OK) @PreAuthorize(ALLOWED_TO_EDIT_USER) - @ApiOperation(value = "Load user preferences", notes = "Only for users that allowed to edit other users") + @Operation(summary = "Load user preferences", description = "Only for users that allowed to edit other users") public PreferenceResource getUserPreference(@PathVariable String projectName, - @PathVariable String login, - @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable String login, @AuthenticationPrincipal ReportPortalUser user) { return getPreference.getPreference(projectExtractor.extractProjectDetails(user, projectName), - user); + user + ); } @Transactional(readOnly = true) @@ -331,10 +334,9 @@ public Iterable getAllProjectsInfo( @PreAuthorize(ADMIN_ONLY) @GetMapping(value = "/export") @ResponseStatus(HttpStatus.OK) - @ApiOperation(value = "Exports information about all projects", notes = "Allowable only for users with administrator role") - public void exportProjects( - @ApiParam(allowableValues = "csv") - @RequestParam(value = "view", required = false, defaultValue = "csv") String view, + @Operation(summary = "Exports information about all projects", description = "Allowable only for users with administrator role") + public void exportProjects(@Parameter(schema = @Schema(allowableValues = "csv")) + @RequestParam(value = "view", required = false, defaultValue = "csv") String view, @FilterFor(ProjectInfo.class) Filter filter, @FilterFor(ProjectInfo.class) Queryable predefinedFilter, @AuthenticationPrincipal ReportPortalUser user, HttpServletResponse response) { @@ -344,15 +346,18 @@ public void exportProjects( response.setHeader(CONTENT_DISPOSITION, String.format("attachment; filename=\"RP_PROJECTS_%s_Report.%s\"", format.name(), - format.getValue()) + format.getValue() + ) ); try (OutputStream outputStream = response.getOutputStream()) { getProjectHandler.exportProjects(format, - new CompositeFilter(Operator.AND, filter, predefinedFilter), outputStream); + new CompositeFilter(Operator.AND, filter, predefinedFilter), outputStream + ); } catch (IOException e) { throw new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, - "Unable to write data to the response."); + "Unable to write data to the response." + ); } } @@ -373,8 +378,7 @@ public ProjectInfoResource getProjectInfo(@PathVariable String projectName, @ResponseStatus(HttpStatus.OK) public Map getProjectWidget(@PathVariable String projectName, @RequestParam(value = "interval", required = false, defaultValue = "3M") String interval, - @PathVariable String widgetCode, - @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable String widgetCode, @AuthenticationPrincipal ReportPortalUser user) { return projectInfoHandler.getProjectInfoWidgetContent(projectName, interval, widgetCode); } diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/ProjectSettingsController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/ProjectSettingsController.java index f4cc134fbf..ecbf44b091 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/ProjectSettingsController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/ProjectSettingsController.java @@ -33,16 +33,17 @@ import com.epam.ta.reportportal.core.project.settings.notification.DeleteProjectNotificationHandler; import com.epam.ta.reportportal.core.project.settings.notification.GetProjectNotificationsHandler; import com.epam.ta.reportportal.core.project.settings.notification.UpdateProjectNotificationHandler; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.project.config.CreateIssueSubTypeRQ; -import com.epam.ta.reportportal.ws.model.project.config.IssueSubTypeCreatedRS; -import com.epam.ta.reportportal.ws.model.project.config.ProjectSettingsResource; -import com.epam.ta.reportportal.ws.model.project.config.UpdateIssueSubTypeRQ; -import com.epam.ta.reportportal.ws.model.project.config.pattern.CreatePatternTemplateRQ; -import com.epam.ta.reportportal.ws.model.project.config.pattern.UpdatePatternTemplateRQ; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; -import io.swagger.annotations.ApiOperation; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.project.config.CreateIssueSubTypeRQ; +import com.epam.ta.reportportal.model.project.config.IssueSubTypeCreatedRS; +import com.epam.ta.reportportal.model.project.config.ProjectSettingsResource; +import com.epam.ta.reportportal.model.project.config.UpdateIssueSubTypeRQ; +import com.epam.ta.reportportal.model.project.config.pattern.CreatePatternTemplateRQ; +import com.epam.ta.reportportal.model.project.config.pattern.UpdatePatternTemplateRQ; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; @@ -68,6 +69,7 @@ @RestController @RequestMapping("/v1/{projectName}/settings") @PreAuthorize(ASSIGNED_TO_PROJECT) +@Tag(name = "project-settings-controller", description = "Project Settings Controller") public class ProjectSettingsController { private final CreateProjectSettingsHandler createHandler; @@ -90,9 +92,8 @@ public class ProjectSettingsController { @Autowired public ProjectSettingsController(CreateProjectSettingsHandler createHandler, - UpdateProjectSettingsHandler updateHandler, - DeleteProjectSettingsHandler deleteHandler, GetProjectSettingsHandler getHandler, - GetProjectHandler getProjectHandler, + UpdateProjectSettingsHandler updateHandler, DeleteProjectSettingsHandler deleteHandler, + GetProjectSettingsHandler getHandler, GetProjectHandler getProjectHandler, GetProjectNotificationsHandler getProjectNotificationsHandler, CreateProjectNotificationHandler createProjectNotificationHandler, UpdateProjectNotificationHandler updateProjectNotificationHandler, @@ -111,7 +112,7 @@ public ProjectSettingsController(CreateProjectSettingsHandler createHandler, @PostMapping("/sub-type") @ResponseStatus(CREATED) @PreAuthorize(PROJECT_MANAGER) - @ApiOperation("Creation of custom project specific issue sub-type") + @Operation(summary = "Creation of custom project specific issue sub-type") public IssueSubTypeCreatedRS createProjectIssueSubType(@PathVariable String projectName, @RequestBody @Validated CreateIssueSubTypeRQ request, @AuthenticationPrincipal ReportPortalUser user) { @@ -121,7 +122,7 @@ public IssueSubTypeCreatedRS createProjectIssueSubType(@PathVariable String proj @PutMapping("/sub-type") @ResponseStatus(OK) @PreAuthorize(PROJECT_MANAGER) - @ApiOperation("Update of custom project specific issue sub-type") + @Operation(summary = "Update of custom project specific issue sub-type") public OperationCompletionRS updateProjectIssueSubType(@PathVariable String projectName, @RequestBody @Validated UpdateIssueSubTypeRQ request, @AuthenticationPrincipal ReportPortalUser user) { @@ -131,17 +132,16 @@ public OperationCompletionRS updateProjectIssueSubType(@PathVariable String proj @DeleteMapping("/sub-type/{id}") @ResponseStatus(OK) @PreAuthorize(PROJECT_MANAGER) - @ApiOperation("Delete custom project specific issue sub-type") + @Operation(summary = "Delete custom project specific issue sub-type") public OperationCompletionRS deleteProjectIssueSubType(@PathVariable String projectName, - @PathVariable Long id, - @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable Long id, @AuthenticationPrincipal ReportPortalUser user) { return deleteHandler.deleteProjectIssueSubType(normalizeId(projectName), user, id); } @GetMapping @ResponseStatus(OK) @PreAuthorize(ASSIGNED_TO_PROJECT) - @ApiOperation(value = "Get project specific issue sub-types", notes = "Only for users that are assigned to the project") + @Operation(summary = "Get project specific issue sub-types", description = "Only for users that are assigned to the project") public ProjectSettingsResource getProjectSettings(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user) { return getHandler.getProjectSettings(normalizeId(projectName)); @@ -150,33 +150,34 @@ public ProjectSettingsResource getProjectSettings(@PathVariable String projectNa @PostMapping("/pattern") @ResponseStatus(CREATED) @PreAuthorize(PROJECT_MANAGER) - @ApiOperation("Create pattern template for items' log messages pattern analysis") + @Operation(summary = "Create pattern template for items' log messages pattern analysis") public EntryCreatedRS createPatternTemplate(@PathVariable String projectName, @RequestBody @Validated CreatePatternTemplateRQ createPatternTemplateRQ, @AuthenticationPrincipal ReportPortalUser user) { return createHandler.createPatternTemplate(normalizeId(projectName), createPatternTemplateRQ, - user); + user + ); } @PutMapping("/pattern/{id}") @ResponseStatus(OK) @PreAuthorize(PROJECT_MANAGER) - @ApiOperation("Update pattern template for items' log messages pattern analysis") + @Operation(summary = "Update pattern template for items' log messages pattern analysis") public OperationCompletionRS updatePatternTemplate(@PathVariable String projectName, @PathVariable Long id, @RequestBody @Validated UpdatePatternTemplateRQ updatePatternTemplateRQ, @AuthenticationPrincipal ReportPortalUser user) { return updateHandler.updatePatternTemplate(id, normalizeId(projectName), - updatePatternTemplateRQ, user); + updatePatternTemplateRQ, user + ); } @DeleteMapping("/pattern/{id}") @ResponseStatus(OK) @PreAuthorize(PROJECT_MANAGER) - @ApiOperation("Delete pattern template for items' log messages pattern analysis") + @Operation(summary = "Delete pattern template for items' log messages pattern analysis") public OperationCompletionRS deletePatternTemplate(@PathVariable String projectName, - @PathVariable Long id, - @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable Long id, @AuthenticationPrincipal ReportPortalUser user) { return deleteHandler.deletePatternTemplate(normalizeId(projectName), user, id); } @@ -184,7 +185,7 @@ public OperationCompletionRS deletePatternTemplate(@PathVariable String projectN @GetMapping("/notification") @ResponseStatus(OK) @PreAuthorize(ASSIGNED_TO_PROJECT) - @ApiOperation(value = "Returns notifications config of specified project", notes = "Only for users assigned to specified project") + @Operation(summary = "Returns notifications config of specified project", description = "Only for users assigned to specified project") public List getNotifications(@PathVariable String projectName) { return getProjectNotificationsHandler.getProjectNotifications( getProjectHandler.get(normalizeId(projectName)).getId()); @@ -194,40 +195,33 @@ public List getNotifications(@PathVariable String projectName) { @PostMapping("/notification") @ResponseStatus(CREATED) @PreAuthorize(PROJECT_MANAGER_OR_ADMIN) - @ApiOperation(value = "Creates notification for specified project", notes = "Only for users with PROJECT_MANAGER or ADMIN roles") + @Operation(summary = "Creates notification for specified project", description = "Only for users with PROJECT_MANAGER or ADMIN roles") public EntryCreatedRS createNotification(@PathVariable String projectName, @RequestBody @Validated SenderCaseDTO createNotificationRQ, @AuthenticationPrincipal ReportPortalUser user) { return createProjectNotificationHandler.createNotification( - getProjectHandler.get(normalizeId(projectName)), - createNotificationRQ, - user - ); + getProjectHandler.get(normalizeId(projectName)), createNotificationRQ, user); } @Transactional @PutMapping("/notification") @ResponseStatus(CREATED) @PreAuthorize(PROJECT_MANAGER_OR_ADMIN) - @ApiOperation(value = "Updates notification for specified project", notes = "Only for users with PROJECT_MANAGER or ADMIN roles") + @Operation(summary = "Updates notification for specified project", description = "Only for users with PROJECT_MANAGER or ADMIN roles") public OperationCompletionRS updateNotification(@PathVariable String projectName, @RequestBody @Validated SenderCaseDTO updateNotificationRQ, @AuthenticationPrincipal ReportPortalUser user) { return updateProjectNotificationHandler.updateNotification( - getProjectHandler.get(normalizeId(projectName)), - updateNotificationRQ, - user - ); + getProjectHandler.get(normalizeId(projectName)), updateNotificationRQ, user); } @Transactional @DeleteMapping("/notification/{notificationId:\\d+}") @ResponseStatus(OK) @PreAuthorize(PROJECT_MANAGER_OR_ADMIN) - @ApiOperation(value = "Deletes notification for specified project", notes = "Only for users with PROJECT_MANAGER or ADMIN roles") + @Operation(summary = "Deletes notification for specified project", description = "Only for users with PROJECT_MANAGER or ADMIN roles") public OperationCompletionRS deleteNotification(@PathVariable String projectName, - @PathVariable Long notificationId, - @AuthenticationPrincipal ReportPortalUser user) { + @PathVariable Long notificationId, @AuthenticationPrincipal ReportPortalUser user) { return deleteNotificationHandler.deleteNotification( getProjectHandler.get(normalizeId(projectName)), notificationId, user); } diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/SettingsController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/SettingsController.java index f9726ff2df..8880c549e3 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/SettingsController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/SettingsController.java @@ -20,9 +20,10 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.core.admin.ServerAdminHandler; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.settings.AnalyticsResource; -import io.swagger.annotations.ApiOperation; +import com.epam.ta.reportportal.model.settings.AnalyticsResource; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; @@ -44,6 +45,7 @@ @RestController @RequestMapping("/v1/settings") @PreAuthorize(ADMIN_ONLY) +@Tag(name = "settings-controller", description = "Settings Controller") public class SettingsController { private final ServerAdminHandler serverHandler; @@ -54,9 +56,9 @@ public SettingsController(ServerAdminHandler serverHandler) { } @Transactional - @RequestMapping(value = "/analytics", method = {RequestMethod.PUT, RequestMethod.POST}) + @RequestMapping(value = "/analytics", method = { RequestMethod.PUT, RequestMethod.POST }) @ResponseStatus(HttpStatus.OK) - @ApiOperation(value = "Update analytics settings") + @Operation(summary = "Update analytics settings") public OperationCompletionRS saveAnalyticsSettings( @RequestBody @Validated AnalyticsResource request, @AuthenticationPrincipal ReportPortalUser user) { @@ -66,7 +68,7 @@ public OperationCompletionRS saveAnalyticsSettings( @Transactional(readOnly = true) @GetMapping @ResponseStatus(HttpStatus.OK) - @ApiOperation(value = "Get server settings") + @Operation(summary = "Get server settings") public Map getServerSettings(@AuthenticationPrincipal ReportPortalUser user) { return serverHandler.getServerSettings(); } diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/TestItemAsyncController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/TestItemAsyncController.java index 0b234f8aa5..45212bf668 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/TestItemAsyncController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/TestItemAsyncController.java @@ -26,11 +26,12 @@ import com.epam.ta.reportportal.core.item.StartTestItemHandler; import com.epam.ta.reportportal.core.logging.HttpLogging; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.EntryCreatedAsyncRS; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import io.swagger.annotations.ApiOperation; +import com.epam.ta.reportportal.ws.reporting.EntryCreatedAsyncRS; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.access.prepost.PreAuthorize; @@ -54,6 +55,7 @@ @RestController @RequestMapping("/v2/{projectName}/item") @PreAuthorize(ASSIGNED_TO_PROJECT) +@Tag(name = "test-item-async-controller", description = "Test Item Async Controller") public class TestItemAsyncController { private final ProjectExtractor projectExtractor; @@ -72,7 +74,7 @@ public TestItemAsyncController(ProjectExtractor projectExtractor, @HttpLogging @PostMapping @ResponseStatus(CREATED) - @ApiOperation("Start a root test item") + @Operation(summary = "Start a root test item") @PreAuthorize(ALLOWED_TO_REPORT) public EntryCreatedAsyncRS startRootItem(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user, @@ -84,7 +86,7 @@ public EntryCreatedAsyncRS startRootItem(@PathVariable String projectName, @HttpLogging @PostMapping("/{parentItem}") @ResponseStatus(CREATED) - @ApiOperation("Start a child test item") + @Operation(summary = "Start a child test item") @PreAuthorize(ALLOWED_TO_REPORT) public EntryCreatedAsyncRS startChildItem(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user, @@ -96,7 +98,7 @@ public EntryCreatedAsyncRS startChildItem(@PathVariable String projectName, @HttpLogging @PutMapping("/{testItemId}") @ResponseStatus(OK) - @ApiOperation("Finish test item") + @Operation(summary = "Finish test item") @PreAuthorize(ALLOWED_TO_REPORT) public OperationCompletionRS finishTestItem(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user, diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/TestItemController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/TestItemController.java index ae6cf080ab..50a88f964b 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/TestItemController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/TestItemController.java @@ -47,23 +47,26 @@ import com.epam.ta.reportportal.core.item.history.TestItemsHistoryHandler; import com.epam.ta.reportportal.core.item.impl.history.param.HistoryRequestParams; import com.epam.ta.reportportal.entity.item.TestItem; +import com.epam.ta.reportportal.model.TestItemHistoryElement; +import com.epam.ta.reportportal.model.issue.DefineIssueRQ; +import com.epam.ta.reportportal.model.item.LinkExternalIssueRQ; +import com.epam.ta.reportportal.model.item.UnlinkExternalIssueRQ; +import com.epam.ta.reportportal.model.item.UpdateTestItemRQ; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.BulkInfoUpdateRQ; -import com.epam.ta.reportportal.ws.model.EntryCreatedAsyncRS; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.TestItemHistoryElement; -import com.epam.ta.reportportal.ws.model.TestItemResource; -import com.epam.ta.reportportal.ws.model.issue.DefineIssueRQ; -import com.epam.ta.reportportal.ws.model.issue.Issue; -import com.epam.ta.reportportal.ws.model.item.LinkExternalIssueRQ; -import com.epam.ta.reportportal.ws.model.item.UnlinkExternalIssueRQ; -import com.epam.ta.reportportal.ws.model.item.UpdateTestItemRQ; -import com.epam.ta.reportportal.ws.model.statistics.StatisticsResource; +import com.epam.ta.reportportal.ws.reporting.BulkInfoUpdateRQ; +import com.epam.ta.reportportal.ws.reporting.EntryCreatedAsyncRS; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.Issue; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.StatisticsResource; +import com.epam.ta.reportportal.ws.reporting.TestItemResource; import com.epam.ta.reportportal.ws.resolver.FilterFor; import com.epam.ta.reportportal.ws.resolver.SortFor; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.tags.Tag; import java.util.Collections; import java.util.List; import java.util.Map; @@ -94,6 +97,7 @@ @RestController @RequestMapping("/v1/{projectName}/item") @PreAuthorize(ASSIGNED_TO_PROJECT) +@Tag(name = "test-item-controller", description = "Test Item Controller") public class TestItemController { public static final String HISTORY_TYPE_PARAM = "type"; @@ -117,8 +121,8 @@ public class TestItemController { public TestItemController(ProjectExtractor projectExtractor, StartTestItemHandler startTestItemHandler, DeleteTestItemHandler deleteTestItemHandler, FinishTestItemHandler finishTestItemHandler, UpdateTestItemHandler updateTestItemHandler, - GetTestItemHandler getTestItemHandler, - TestItemsHistoryHandler testItemsHistoryHandler, SuggestItemService suggestItemService) { + GetTestItemHandler getTestItemHandler, TestItemsHistoryHandler testItemsHistoryHandler, + SuggestItemService suggestItemService) { this.projectExtractor = projectExtractor; this.startTestItemHandler = startTestItemHandler; this.deleteTestItemHandler = deleteTestItemHandler; @@ -133,35 +137,38 @@ public TestItemController(ProjectExtractor projectExtractor, @PostMapping @ResponseStatus(CREATED) - @ApiOperation("Start a root test item") + @Operation(summary = "Start a root test item") @PreAuthorize(ALLOWED_TO_REPORT) public EntryCreatedAsyncRS startRootItem(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user, @RequestBody @Validated StartTestItemRQ startTestItemRQ) { return startTestItemHandler.startRootItem(user, - projectExtractor.extractProjectDetails(user, projectName), startTestItemRQ); + projectExtractor.extractProjectDetails(user, projectName), startTestItemRQ + ); } @PostMapping("/{parentItem}") @ResponseStatus(CREATED) - @ApiOperation("Start a child test item") + @Operation(summary = "Start a child test item") @PreAuthorize(ALLOWED_TO_REPORT) public EntryCreatedAsyncRS startChildItem(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @PathVariable String parentItem, @RequestBody @Validated StartTestItemRQ startTestItemRQ) { + @AuthenticationPrincipal ReportPortalUser user, @PathVariable String parentItem, + @RequestBody @Validated StartTestItemRQ startTestItemRQ) { return startTestItemHandler.startChildItem(user, - projectExtractor.extractProjectDetails(user, projectName), startTestItemRQ, parentItem); + projectExtractor.extractProjectDetails(user, projectName), startTestItemRQ, parentItem + ); } @PutMapping("/{testItemId}") @ResponseStatus(OK) - @ApiOperation("Finish test item") + @Operation(summary = "Finish test item") @PreAuthorize(ALLOWED_TO_REPORT) public OperationCompletionRS finishTestItem(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @PathVariable String testItemId, @RequestBody @Validated FinishTestItemRQ finishExecutionRQ) { + @AuthenticationPrincipal ReportPortalUser user, @PathVariable String testItemId, + @RequestBody @Validated FinishTestItemRQ finishExecutionRQ) { return finishTestItemHandler.finishTestItem(user, - projectExtractor.extractProjectDetails(user, projectName), testItemId, finishExecutionRQ); + projectExtractor.extractProjectDetails(user, projectName), testItemId, finishExecutionRQ + ); } @@ -170,52 +177,52 @@ public OperationCompletionRS finishTestItem(@PathVariable String projectName, @Transactional(readOnly = true) @GetMapping("/{itemId}") @ResponseStatus(OK) - @ApiOperation("Find test item by ID") + @Operation(summary = "Find test item by ID") public TestItemResource getTestItem(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @PathVariable String itemId) { + @AuthenticationPrincipal ReportPortalUser user, @PathVariable String itemId) { return getTestItemHandler.getTestItem(itemId, - projectExtractor.extractProjectDetails(user, projectName), user); + projectExtractor.extractProjectDetails(user, projectName), user + ); } @Transactional(readOnly = true) @GetMapping("/uuid/{itemId}") @ResponseStatus(OK) - @ApiOperation("Find test item by UUID") + @Operation(summary = "Find test item by UUID") public TestItemResource getTestItemByUuid(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @PathVariable String itemId) { + @AuthenticationPrincipal ReportPortalUser user, @PathVariable String itemId) { return getTestItemHandler.getTestItem(itemId, - projectExtractor.extractProjectDetails(user, projectName), user); + projectExtractor.extractProjectDetails(user, projectName), user + ); } @Transactional(readOnly = true) @GetMapping("/suggest/{itemId}") @ResponseStatus(OK) - @ApiOperation("Search suggested items in analyzer for provided one") + @Operation(summary = "Search suggested items in analyzer for provided one") public List getSuggestedItems(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @PathVariable Long itemId) { + @AuthenticationPrincipal ReportPortalUser user, @PathVariable Long itemId) { return suggestItemService.suggestItems(itemId, - projectExtractor.extractProjectDetails(user, projectName), user); + projectExtractor.extractProjectDetails(user, projectName), user + ); } @GetMapping("/suggest/cluster/{clusterId}") @ResponseStatus(OK) - @ApiOperation("Search suggested items in analyzer for provided one") + @Operation(summary = "Search suggested items in analyzer for provided one") public List getSuggestedClusterItems(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @PathVariable Long clusterId) { + @AuthenticationPrincipal ReportPortalUser user, @PathVariable Long clusterId) { return suggestItemService.suggestClusterItems(clusterId, - projectExtractor.extractProjectDetails(user, projectName), user); + projectExtractor.extractProjectDetails(user, projectName), user + ); } @Transactional @PutMapping("/suggest/choice") @ResponseStatus(OK) - @ApiOperation("Handle user choice from suggested items") + @Operation(summary = "Handle user choice from suggested items") public OperationCompletionRS handleSuggestChoose(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user, @RequestBody @Validated List request) { @@ -227,36 +234,33 @@ public OperationCompletionRS handleSuggestChoose(@PathVariable String projectNam @Transactional(readOnly = true) @GetMapping @ResponseStatus(OK) - @ApiOperation("Find test items by specified filter") + @Operation(summary = "Find test items by specified filter") + @Schema(implementation = TestItemHistoryElement.class) public Iterable getTestItems(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @Nullable @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ - + CRITERIA_LAUNCH_ID, required = false) Long launchId, + @AuthenticationPrincipal ReportPortalUser user, @Nullable + @Parameter(hidden = true) @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ + CRITERIA_LAUNCH_ID, required = false) + Long launchId, @Nullable @RequestParam(value = FILTER_ID_REQUEST_PARAM, required = false) Long filterId, - @RequestParam(value = IS_LATEST_LAUNCHES_REQUEST_PARAM, defaultValue = "false", required = false) boolean isLatest, - @RequestParam(value = LAUNCHES_LIMIT_REQUEST_PARAM, defaultValue = "0", required = false) int launchesLimit, - @FilterFor(TestItem.class) Filter filter, + @RequestParam(value = IS_LATEST_LAUNCHES_REQUEST_PARAM, defaultValue = "false", required = false) + boolean isLatest, + @RequestParam(value = LAUNCHES_LIMIT_REQUEST_PARAM, defaultValue = "0", required = false) + int launchesLimit, @FilterFor(TestItem.class) Filter filter, @FilterFor(TestItem.class) Queryable predefinedFilter, @SortFor(TestItem.class) Pageable pageable) { return getTestItemHandler.getTestItems( - new CompositeFilter(Operator.AND, filter, predefinedFilter), - pageable, - projectExtractor.extractProjectDetails(user, projectName), - user, - launchId, - filterId, - isLatest, - launchesLimit + new CompositeFilter(Operator.AND, filter, predefinedFilter), pageable, + projectExtractor.extractProjectDetails(user, projectName), user, launchId, filterId, + isLatest, launchesLimit ); } @Transactional(readOnly = true) @GetMapping("/v2") @ResponseStatus(OK) - @ApiOperation("Find test items by specified filter") + @Operation(summary = "Find test items by specified filter") public Iterable getTestItemsV2(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @RequestParam Map params, @FilterFor(TestItem.class) Filter filter, + @AuthenticationPrincipal ReportPortalUser user, @RequestParam Map params, + @FilterFor(TestItem.class) Filter filter, @FilterFor(TestItem.class) Queryable predefinedFilter, @SortFor(TestItem.class) Pageable pageable) { // tmp return null for project, to fix perf issue @@ -264,57 +268,51 @@ public Iterable getTestItemsV2(@PathVariable String projectNam return null; } return getTestItemHandler.getTestItemsByProvider( - new CompositeFilter(Operator.AND, filter, predefinedFilter), - pageable, - projectExtractor.extractProjectDetails(user, projectName), - user, - params + new CompositeFilter(Operator.AND, filter, predefinedFilter), pageable, + projectExtractor.extractProjectDetails(user, projectName), user, params ); } @Transactional(readOnly = true) @GetMapping("/statistics") @ResponseStatus(OK) - @ApiOperation("Find accumulated statistics of items by specified filter") + @Operation(summary = "Find accumulated statistics of items by specified filter") public StatisticsResource getTestItems(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @FilterFor(TestItem.class) Filter filter, + @AuthenticationPrincipal ReportPortalUser user, @FilterFor(TestItem.class) Filter filter, @FilterFor(TestItem.class) Queryable predefinedFilter, @RequestParam Map params) { return getTestItemHandler.getStatisticsByProvider( new CompositeFilter(Operator.AND, filter, predefinedFilter), - projectExtractor.extractProjectDetails(user, projectName), - user, - params + projectExtractor.extractProjectDetails(user, projectName), user, params ); } @Transactional @DeleteMapping("/{itemId}") @ResponseStatus(OK) - @ApiOperation("Delete test item") + @Operation(summary = "Delete test item") public OperationCompletionRS deleteTestItem(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @PathVariable Long itemId) { + @AuthenticationPrincipal ReportPortalUser user, @PathVariable Long itemId) { return deleteTestItemHandler.deleteTestItem(itemId, - projectExtractor.extractProjectDetails(user, projectName), user); + projectExtractor.extractProjectDetails(user, projectName), user + ); } @Transactional @DeleteMapping @ResponseStatus(OK) - @ApiOperation("Delete test items by specified ids") + @Operation(summary = "Delete test items by specified ids") public List deleteTestItems(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @RequestParam(value = "ids") Set ids) { + @AuthenticationPrincipal ReportPortalUser user, @RequestParam(value = "ids") Set ids) { return deleteTestItemHandler.deleteTestItems(ids, - projectExtractor.extractProjectDetails(user, projectName), user); + projectExtractor.extractProjectDetails(user, projectName), user + ); } @Transactional @PutMapping @ResponseStatus(OK) - @ApiOperation("Update issues of specified test items") + @Operation(summary = "Update issues of specified test items") public List defineTestItemIssueType(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user, @RequestBody @Validated DefineIssueRQ request) { @@ -325,50 +323,50 @@ public List defineTestItemIssueType(@PathVariable String projectName, @Transactional(readOnly = true) @GetMapping("/history") @ResponseStatus(OK) - @ApiOperation("Load history of test items") + @Operation(summary = "Load history of test items") public Iterable getItemsHistory(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user, @FilterFor(TestItem.class) Filter filter, @FilterFor(TestItem.class) Queryable predefinedFilter, - @SortFor(TestItem.class) Pageable pageable, - @Nullable @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ - + CRITERIA_PARENT_ID, required = false) Long parentId, - @Nullable @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ - + CRITERIA_ID, required = false) Long itemId, - @Nullable @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ - + CRITERIA_LAUNCH_ID, required = false) Long launchId, - @Nullable @RequestParam(value = HISTORY_TYPE_PARAM, required = false) String type, + @SortFor(TestItem.class) Pageable pageable, @Nullable + @Parameter(hidden = true) @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ + CRITERIA_PARENT_ID, required = false) + Long parentId, @Nullable + @Parameter(hidden = true) @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ + CRITERIA_ID, required = false) + Long itemId, @Nullable + @Parameter(hidden = true) @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ + CRITERIA_LAUNCH_ID, required = false) + Long launchId, @Nullable @RequestParam(value = HISTORY_TYPE_PARAM, required = false) String type, @Nullable @RequestParam(value = FILTER_ID_REQUEST_PARAM, required = false) Long filterId, - @RequestParam(value = IS_LATEST_LAUNCHES_REQUEST_PARAM, defaultValue = "false", required = false) boolean isLatest, - @RequestParam(value = LAUNCHES_LIMIT_REQUEST_PARAM, defaultValue = "0", required = false) int launchesLimit, - @RequestParam(value = HISTORY_DEPTH_PARAM, required = false, defaultValue = HISTORY_DEPTH_DEFAULT_VALUE) int historyDepth) { + @RequestParam(value = IS_LATEST_LAUNCHES_REQUEST_PARAM, defaultValue = "false", required = false) + boolean isLatest, + @RequestParam(value = LAUNCHES_LIMIT_REQUEST_PARAM, defaultValue = "0", required = false) + int launchesLimit, + @RequestParam(value = HISTORY_DEPTH_PARAM, required = false, defaultValue = HISTORY_DEPTH_DEFAULT_VALUE) + int historyDepth) { return testItemsHistoryHandler.getItemsHistory( projectExtractor.extractProjectDetails(user, projectName), - new CompositeFilter(Operator.AND, filter, predefinedFilter), - pageable, + new CompositeFilter(Operator.AND, filter, predefinedFilter), pageable, HistoryRequestParams.of(historyDepth, parentId, itemId, launchId, type, filterId, - launchesLimit, isLatest), - user + launchesLimit, isLatest + ), user ); } @Transactional(readOnly = true) @GetMapping("/ticket/ids") @ResponseStatus(OK) - @ApiOperation("Get tickets that contains a term as a part inside for specified launch") + @Operation(summary = "Get tickets that contains a term as a part inside for specified launch") public List getTicketIds(@AuthenticationPrincipal ReportPortalUser user, - @PathVariable String projectName, - @RequestParam(value = "launch") Long id, @RequestParam(value = "term") String term) { + @PathVariable String projectName, @RequestParam(value = "launch") Long id, + @RequestParam(value = "term") String term) { return getTestItemHandler.getTicketIds(id, normalizeId(term)); } @Transactional(readOnly = true) @GetMapping("/ticket/ids/all") @ResponseStatus(OK) - @ApiOperation("Get tickets that contains a term as a part inside for specified launch") + @Operation(summary = "Get tickets that contains a term as a part inside for specified launch") public List getTicketIdsForProject(@AuthenticationPrincipal ReportPortalUser user, - @PathVariable String projectName, - @RequestParam(value = "term") String term) { + @PathVariable String projectName, @RequestParam(value = "term") String term) { return getTestItemHandler.getTicketIds( projectExtractor.extractProjectDetails(user, projectName), normalizeId(term)); } @@ -377,12 +375,11 @@ public List getTicketIdsForProject(@AuthenticationPrincipal ReportPortal @Transactional(readOnly = true) @GetMapping("/attribute/keys") @ResponseStatus(OK) - @ApiOperation("Get all unique attribute keys of specified launch") + @Operation(summary = "Get all unique attribute keys of specified launch") public List getAttributeKeys(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @RequestParam(value = "launch") Long id, - @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.CNT - + CRITERIA_ITEM_ATTRIBUTE_KEY) String value) { + @AuthenticationPrincipal ReportPortalUser user, @RequestParam(value = "launch") Long id, + @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.CNT + CRITERIA_ITEM_ATTRIBUTE_KEY) + String value) { return getTestItemHandler.getAttributeKeys(id, value); } @@ -390,19 +387,16 @@ public List getAttributeKeys(@PathVariable String projectName, @Transactional(readOnly = true) @GetMapping("/attribute/keys/all") @ResponseStatus(OK) - @ApiOperation("Get all unique attribute keys of specified launch") + @Operation(summary = "Get all unique attribute keys of specified launch") public List getAttributeKeysForProject(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user, - @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.CNT - + CRITERIA_ITEM_ATTRIBUTE_KEY) String value, - @RequestParam(value = FILTER_ID_REQUEST_PARAM) Long launchFilterId, - @RequestParam(value = IS_LATEST_LAUNCHES_REQUEST_PARAM, defaultValue = "false", required = false) boolean isLatest, + @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.CNT + CRITERIA_ITEM_ATTRIBUTE_KEY) + String value, @RequestParam(value = FILTER_ID_REQUEST_PARAM) Long launchFilterId, + @RequestParam(value = IS_LATEST_LAUNCHES_REQUEST_PARAM, defaultValue = "false", required = false) + boolean isLatest, @RequestParam(value = LAUNCHES_LIMIT_REQUEST_PARAM, defaultValue = "0") int launchesLimit) { - return getTestItemHandler.getAttributeKeys(launchFilterId, - isLatest, - launchesLimit, - projectExtractor.extractProjectDetails(user, projectName), - value + return getTestItemHandler.getAttributeKeys(launchFilterId, isLatest, launchesLimit, + projectExtractor.extractProjectDetails(user, projectName), value ); } @@ -410,48 +404,46 @@ public List getAttributeKeysForProject(@PathVariable String projectName, @Transactional(readOnly = true) @GetMapping("/attribute/values") @ResponseStatus(OK) - @ApiOperation("Get all unique attribute values of specified launch") + @Operation(summary = "Get all unique attribute values of specified launch") public List getAttributeValues(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @RequestParam(value = "launch") Long id, + @AuthenticationPrincipal ReportPortalUser user, @RequestParam(value = "launch") Long id, @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ + CRITERIA_ITEM_ATTRIBUTE_KEY, required = false) String key, - @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.CNT - + CRITERIA_ITEM_ATTRIBUTE_VALUE) String value) { + @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.CNT + CRITERIA_ITEM_ATTRIBUTE_VALUE) + String value) { return getTestItemHandler.getAttributeValues(id, key, value); } @Transactional(readOnly = true) @GetMapping("/step/attribute/keys") @ResponseStatus(OK) - @ApiOperation("Get all unique attribute keys of step items under specified project") + @Operation(summary = "Get all unique attribute keys of step items under specified project") public List getAttributeKeys(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user, - @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ - + CRITERIA_NAME, required = false) String launchName, - @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.CNT - + CRITERIA_ITEM_ATTRIBUTE_KEY) String value) { - return ofNullable(launchName).filter(StringUtils::isNotBlank) - .map(name -> getTestItemHandler.getAttributeKeys( - projectExtractor.extractProjectDetails(user, projectName), name, value)) + @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ + CRITERIA_NAME, required = false) + String launchName, + @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.CNT + CRITERIA_ITEM_ATTRIBUTE_KEY) + String value) { + return ofNullable(launchName).filter(StringUtils::isNotBlank).map( + name -> getTestItemHandler.getAttributeKeys( + projectExtractor.extractProjectDetails(user, projectName), name, value)) .orElseGet(Collections::emptyList); } @Transactional(readOnly = true) @GetMapping("/step/attribute/values") @ResponseStatus(OK) - @ApiOperation("Get all unique attribute values of step items under specified project") + @Operation(summary = "Get all unique attribute values of step items under specified project") public List getAttributeValues(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user, - @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ - + CRITERIA_NAME, required = false) String launchName, - @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ - + CRITERIA_ITEM_ATTRIBUTE_KEY, required = false) String key, - @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.CNT - + CRITERIA_ITEM_ATTRIBUTE_VALUE) String value) { - return ofNullable(launchName).filter(StringUtils::isNotBlank) - .map(name -> getTestItemHandler.getAttributeValues( - projectExtractor.extractProjectDetails(user, projectName), name, key, value)) + @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ + CRITERIA_NAME, required = false) + String launchName, @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.EQ + + CRITERIA_ITEM_ATTRIBUTE_KEY, required = false) String key, + @RequestParam(value = DEFAULT_FILTER_PREFIX + Condition.CNT + CRITERIA_ITEM_ATTRIBUTE_VALUE) + String value) { + return ofNullable(launchName).filter(StringUtils::isNotBlank).map( + name -> getTestItemHandler.getAttributeValues( + projectExtractor.extractProjectDetails(user, projectName), name, key, value)) .orElseGet(Collections::emptyList); } @@ -459,21 +451,22 @@ public List getAttributeValues(@PathVariable String projectName, @PutMapping(value = "/info") @PreAuthorize(PROJECT_MANAGER_OR_ADMIN) @ResponseStatus(OK) - @ApiOperation("Bulk update attributes and description") + @Operation(summary = "Bulk update attributes and description") public OperationCompletionRS bulkUpdate(@PathVariable String projectName, @RequestBody @Validated BulkInfoUpdateRQ bulkInfoUpdateRQ, @AuthenticationPrincipal ReportPortalUser user) { return updateTestItemHandler.bulkInfoUpdate(bulkInfoUpdateRQ, - projectExtractor.extractProjectDetails(user, projectName)); + projectExtractor.extractProjectDetails(user, projectName) + ); } @Transactional @PutMapping("/{itemId}/update") @ResponseStatus(OK) - @ApiOperation("Update test item") + @Operation(summary = "Update test item") public OperationCompletionRS updateTestItem(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @PathVariable Long itemId, @RequestBody @Validated UpdateTestItemRQ rq) { + @AuthenticationPrincipal ReportPortalUser user, @PathVariable Long itemId, + @RequestBody @Validated UpdateTestItemRQ rq) { return updateTestItemHandler.updateTestItem( projectExtractor.extractProjectDetails(user, projectName), itemId, rq, user); } @@ -481,33 +474,35 @@ public OperationCompletionRS updateTestItem(@PathVariable String projectName, @Transactional @PutMapping("/issue/link") @ResponseStatus(OK) - @ApiOperation("Attach external issue for specified test items") + @Operation(summary = "Attach external issue for specified test items") public List linkExternalIssues(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user, @RequestBody @Validated LinkExternalIssueRQ rq) { return updateTestItemHandler.processExternalIssues(rq, - projectExtractor.extractProjectDetails(user, projectName), user); + projectExtractor.extractProjectDetails(user, projectName), user + ); } @Transactional @PutMapping("/issue/unlink") @ResponseStatus(OK) - @ApiOperation("Unlink external issue for specified test items") + @Operation(summary = "Unlink external issue for specified test items") public List unlinkExternalIssues(@PathVariable String projectName, @AuthenticationPrincipal ReportPortalUser user, @RequestBody @Validated UnlinkExternalIssueRQ rq) { return updateTestItemHandler.processExternalIssues(rq, - projectExtractor.extractProjectDetails(user, projectName), user); + projectExtractor.extractProjectDetails(user, projectName), user + ); } @Transactional(readOnly = true) @GetMapping("/items") @ResponseStatus(OK) - @ApiOperation("Get test items by specified ids") + @Operation(summary = "Get test items by specified ids") public List getTestItems(@PathVariable String projectName, - @AuthenticationPrincipal ReportPortalUser user, - @RequestParam(value = "ids") Long[] ids) { + @AuthenticationPrincipal ReportPortalUser user, @RequestParam(value = "ids") Long[] ids) { return getTestItemHandler.getTestItems(ids, - projectExtractor.extractProjectDetails(user, projectName), user); + projectExtractor.extractProjectDetails(user, projectName), user + ); } } diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/UserController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/UserController.java index d2ccfd71c3..c04405a12a 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/UserController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/UserController.java @@ -37,38 +37,39 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ApiKeyRQ; -import com.epam.ta.reportportal.ws.model.ApiKeyRS; -import com.epam.ta.reportportal.ws.model.ApiKeysRS; -import com.epam.ta.reportportal.ws.model.DeleteBulkRQ; -import com.epam.ta.reportportal.ws.model.DeleteBulkRS; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.ModelViews; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.YesNoRS; -import com.epam.ta.reportportal.ws.model.user.ChangePasswordRQ; -import com.epam.ta.reportportal.ws.model.user.CreateUserBidRS; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQ; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQConfirm; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQFull; -import com.epam.ta.reportportal.ws.model.user.CreateUserRS; -import com.epam.ta.reportportal.ws.model.user.EditUserRQ; -import com.epam.ta.reportportal.ws.model.user.ResetPasswordRQ; -import com.epam.ta.reportportal.ws.model.user.RestorePasswordRQ; -import com.epam.ta.reportportal.ws.model.user.UserBidRS; -import com.epam.ta.reportportal.ws.model.user.UserResource; +import com.epam.ta.reportportal.model.ApiKeyRQ; +import com.epam.ta.reportportal.model.ApiKeyRS; +import com.epam.ta.reportportal.model.ApiKeysRS; +import com.epam.ta.reportportal.model.DeleteBulkRS; +import com.epam.ta.reportportal.model.ModelViews; +import com.epam.ta.reportportal.model.YesNoRS; +import com.epam.ta.reportportal.model.user.ChangePasswordRQ; +import com.epam.ta.reportportal.model.user.CreateUserBidRS; +import com.epam.ta.reportportal.model.user.CreateUserRQ; +import com.epam.ta.reportportal.model.user.CreateUserRQConfirm; +import com.epam.ta.reportportal.model.user.CreateUserRQFull; +import com.epam.ta.reportportal.model.user.CreateUserRS; +import com.epam.ta.reportportal.model.user.EditUserRQ; +import com.epam.ta.reportportal.model.user.ResetPasswordRQ; +import com.epam.ta.reportportal.model.user.RestorePasswordRQ; +import com.epam.ta.reportportal.model.user.UserBidRS; +import com.epam.ta.reportportal.model.user.UserResource; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.epam.ta.reportportal.ws.resolver.ActiveRole; import com.epam.ta.reportportal.ws.resolver.FilterFor; import com.epam.ta.reportportal.ws.resolver.ResponseView; import com.epam.ta.reportportal.ws.resolver.SortFor; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.tags.Tag; import java.io.IOException; import java.io.OutputStream; +import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; import org.jooq.Operator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -90,6 +91,7 @@ @RestController @RequestMapping("/users") +@Tag(name = "user-controller", description = "User Controller") public class UserController { private final CreateUserHandler createUserMessageHandler; @@ -121,7 +123,7 @@ public UserController(CreateUserHandler createUserMessageHandler, @PostMapping @ResponseStatus(CREATED) @PreAuthorize(ADMIN_ONLY) - @ApiOperation(value = "Create specified user", notes = "Allowable only for users with administrator role") + @Operation(summary = "Create specified user", description = "Allowable only for users with administrator role") public CreateUserRS createUserByAdmin(@RequestBody @Validated CreateUserRQFull rq, @AuthenticationPrincipal ReportPortalUser currentUser, HttpServletRequest request) { return createUserMessageHandler.createUserByAdmin(rq, currentUser, composeBaseUrl(request)); @@ -131,7 +133,7 @@ public CreateUserRS createUserByAdmin(@RequestBody @Validated CreateUserRQFull r @PostMapping(value = "/bid") @ResponseStatus(CREATED) @PreAuthorize("(hasPermission(#createUserRQ.getDefaultProject(), 'projectManagerPermission')) || hasRole('ADMINISTRATOR')") - @ApiOperation("Register invitation for user who will be created") + @Operation(summary = "Register invitation for user who will be created") public CreateUserBidRS createUserBid(@RequestBody @Validated CreateUserRQ createUserRQ, @AuthenticationPrincipal ReportPortalUser currentUser, HttpServletRequest request) { return createUserMessageHandler.createUserBid(createUserRQ, currentUser, @@ -141,7 +143,7 @@ public CreateUserBidRS createUserBid(@RequestBody @Validated CreateUserRQ create @PostMapping(value = "/registration") @ResponseStatus(CREATED) - @ApiOperation("Activate invitation and create user in system") + @Operation(summary = "Activate invitation and create user in system") public CreateUserRS createUser(@RequestBody @Validated CreateUserRQConfirm request, @RequestParam(value = "uuid") String uuid) { return createUserMessageHandler.createUser(request, uuid); @@ -154,7 +156,7 @@ public UserBidRS getUserBidInfo(@RequestParam(value = "uuid") String uuid) { } @DeleteMapping(value = "/{id}") - @ApiOperation(value = "Delete specified user") + @Operation(summary = "Delete specified user") public OperationCompletionRS deleteUser(@PathVariable(value = "id") Long userId, @AuthenticationPrincipal ReportPortalUser currentUser) { return deleteUserHandler.deleteUser(userId, currentUser); @@ -163,16 +165,16 @@ public OperationCompletionRS deleteUser(@PathVariable(value = "id") Long userId, @DeleteMapping @PreAuthorize(ADMIN_ONLY) @ResponseStatus(OK) - @ApiOperation("Delete specified users by ids") - public DeleteBulkRS deleteUsers(@RequestBody @Valid DeleteBulkRQ deleteBulkRQ, + @Operation(summary = "Delete specified users by ids") + public DeleteBulkRS deleteUsers(@RequestParam(value = "ids") List ids, @AuthenticationPrincipal ReportPortalUser user) { - return deleteUserHandler.deleteUsers(deleteBulkRQ.getIds(), user); + return deleteUserHandler.deleteUsers(ids, user); } @Transactional @PutMapping(value = "/{login}") @PreAuthorize(ALLOWED_TO_EDIT_USER) - @ApiOperation(value = "Edit specified user", notes = "Only for administrators and profile's owner") + @Operation(summary = "Edit specified user", description = "Only for administrators and profile's owner") public OperationCompletionRS editUser(@PathVariable String login, @RequestBody @Validated EditUserRQ editUserRQ, @ActiveRole UserRole role, @AuthenticationPrincipal ReportPortalUser currentUser) { @@ -183,15 +185,15 @@ public OperationCompletionRS editUser(@PathVariable String login, @GetMapping(value = "/{login}") @ResponseView(ModelViews.FullUserView.class) @PreAuthorize(ALLOWED_TO_EDIT_USER) - @ApiOperation(value = "Return information about specified user", notes = "Only for administrators and profile's owner") + @Operation(summary = "Return information about specified user", description = "Only for administrators and profile's owner") public UserResource getUser(@PathVariable String login, @AuthenticationPrincipal ReportPortalUser currentUser) { return getUserHandler.getUser(EntityUtils.normalizeId(login), currentUser); } @Transactional(readOnly = true) - @GetMapping(value = {"", "/"}) - @ApiOperation("Return information about current logged-in user") + @GetMapping(value = { "", "/" }) + @Operation(summary = "Return information about current logged-in user") public UserResource getMyself(@AuthenticationPrincipal ReportPortalUser currentUser) { return getUserHandler.getUser(currentUser); } @@ -200,7 +202,7 @@ public UserResource getMyself(@AuthenticationPrincipal ReportPortalUser currentU @GetMapping(value = "/all") @ResponseView(ModelViews.FullUserView.class) @PreAuthorize(ADMIN_ONLY) - @ApiOperation(value = "Return information about all users", notes = "Allowable only for users with administrator role") + @Operation(summary = "Return information about all users", description = "Allowable only for users with administrator role") public Iterable getUsers(@FilterFor(User.class) Filter filter, @SortFor(User.class) Pageable pageable, @FilterFor(User.class) Queryable queryable, @AuthenticationPrincipal ReportPortalUser currentUser) { @@ -211,7 +213,6 @@ public Iterable getUsers(@FilterFor(User.class) Filter filter, @Transactional(readOnly = true) @GetMapping(value = "/registration/info") - public YesNoRS validateInfo(@RequestParam(value = "username", required = false) String username, @RequestParam(value = "email", required = false) String email) { return getUserHandler.validateInfo(username, email); @@ -220,7 +221,7 @@ public YesNoRS validateInfo(@RequestParam(value = "username", required = false) @Transactional @PostMapping(value = "/password/restore") @ResponseStatus(OK) - @ApiOperation("Create a restore password request") + @Operation(summary = "Create a restore password request") public OperationCompletionRS restorePassword(@RequestBody @Validated RestorePasswordRQ rq, HttpServletRequest request) { return createUserMessageHandler.createRestorePasswordBid(rq, composeBaseUrl(request)); @@ -229,7 +230,7 @@ public OperationCompletionRS restorePassword(@RequestBody @Validated RestorePass @Transactional @PostMapping(value = "/password/reset") @ResponseStatus(OK) - @ApiOperation("Reset password") + @Operation(summary = "Reset password") public OperationCompletionRS resetPassword(@RequestBody @Validated ResetPasswordRQ rq) { return createUserMessageHandler.resetPassword(rq); } @@ -237,7 +238,7 @@ public OperationCompletionRS resetPassword(@RequestBody @Validated ResetPassword @Transactional(readOnly = true) @GetMapping(value = "/password/reset/{uuid}") @ResponseStatus(OK) - @ApiOperation("Check if a restore password bid exists") + @Operation(summary = "Check if a restore password bid exists") public YesNoRS isRestorePasswordBidExist(@PathVariable String uuid) { return createUserMessageHandler.isResetPasswordBidExist(uuid); } @@ -245,7 +246,7 @@ public YesNoRS isRestorePasswordBidExist(@PathVariable String uuid) { @Transactional @PostMapping(value = "/password/change") @ResponseStatus(OK) - @ApiOperation("Change own password") + @Operation(summary = "Change own password") public OperationCompletionRS changePassword( @RequestBody @Validated ChangePasswordRQ changePasswordRQ, @AuthenticationPrincipal ReportPortalUser currentUser) { @@ -272,8 +273,8 @@ public Iterable findUsers(@RequestParam(value = "term") String ter @Transactional(readOnly = true) @GetMapping(value = "/export") @PreAuthorize(ADMIN_ONLY) - @ApiOperation(value = "Exports information about all users", notes = "Allowable only for users with administrator role") - public void export(@ApiParam(allowableValues = "csv") + @Operation(summary = "Exports information about all users", description = "Allowable only for users with administrator role") + public void export(@Parameter(schema = @Schema(allowableValues = "csv")) @RequestParam(value = "view", required = false, defaultValue = "csv") String view, @FilterFor(User.class) Filter filter, @FilterFor(User.class) Queryable queryable, @AuthenticationPrincipal ReportPortalUser currentUser, HttpServletResponse response) { @@ -300,7 +301,7 @@ public void export(@ApiParam(allowableValues = "csv") @PostMapping(value = "/{userId}/api-keys") @ResponseStatus(CREATED) - @ApiOperation("Create new Api Key for current user") + @Operation(summary = "Create new Api Key for current user") public ApiKeyRS createApiKey(@RequestBody @Validated ApiKeyRQ apiKeyRQ, @AuthenticationPrincipal ReportPortalUser currentUser, @PathVariable Long userId) { return apiKeyHandler.createApiKey(apiKeyRQ.getName(), currentUser.getUserId()); @@ -308,14 +309,14 @@ public ApiKeyRS createApiKey(@RequestBody @Validated ApiKeyRQ apiKeyRQ, @DeleteMapping(value = "/{userId}/api-keys/{keyId}") @ResponseStatus(OK) - @ApiOperation("Delete specified Api Key") + @Operation(summary = "Delete specified Api Key") public OperationCompletionRS deleteApiKey(@PathVariable Long keyId, @PathVariable Long userId) { return apiKeyHandler.deleteApiKey(keyId); } @GetMapping(value = "/{userId}/api-keys") @ResponseStatus(OK) - @ApiOperation("Get List of users Api Keys") + @Operation(summary = "Get List of users Api Keys") public ApiKeysRS getUsersApiKeys(@AuthenticationPrincipal ReportPortalUser currentUser, @PathVariable Long userId) { return apiKeyHandler.getAllUsersApiKeys(currentUser.getUserId()); diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/UserFilterController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/UserFilterController.java index b5aa7464d3..7c67b93e5a 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/UserFilterController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/UserFilterController.java @@ -16,24 +16,29 @@ package com.epam.ta.reportportal.ws.controller; +import static com.epam.ta.reportportal.auth.permissions.Permissions.ASSIGNED_TO_PROJECT; + import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.core.filter.DeleteUserFilterHandler; import com.epam.ta.reportportal.core.filter.GetUserFilterHandler; import com.epam.ta.reportportal.core.filter.UpdateUserFilterHandler; import com.epam.ta.reportportal.entity.filter.UserFilter; +import com.epam.ta.reportportal.model.CollectionsRQ; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.OwnedEntityResource; +import com.epam.ta.reportportal.model.filter.BulkUpdateFilterRQ; +import com.epam.ta.reportportal.model.filter.UpdateUserFilterRQ; +import com.epam.ta.reportportal.model.filter.UserFilterResource; import com.epam.ta.reportportal.util.ProjectExtractor; import com.epam.ta.reportportal.ws.converter.converters.UserFilterConverter; -import com.epam.ta.reportportal.ws.model.CollectionsRQ; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.OwnedEntityResource; -import com.epam.ta.reportportal.ws.model.filter.BulkUpdateFilterRQ; -import com.epam.ta.reportportal.ws.model.filter.UpdateUserFilterRQ; -import com.epam.ta.reportportal.ws.model.filter.UserFilterResource; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.epam.ta.reportportal.ws.resolver.FilterFor; import com.epam.ta.reportportal.ws.resolver.SortFor; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import java.util.List; +import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; @@ -41,12 +46,17 @@ import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.List; -import java.util.stream.Collectors; - -import static com.epam.ta.reportportal.auth.permissions.Permissions.ASSIGNED_TO_PROJECT; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; /** * @author Pavel Bortnik @@ -55,98 +65,109 @@ @RestController @PreAuthorize(ASSIGNED_TO_PROJECT) @RequestMapping("/v1/{projectName}/filter") +@Tag(name = "user-filter-controller", description = "User Filter Controller") public class UserFilterController { - private final ProjectExtractor projectExtractor; - private final GetUserFilterHandler getFilterHandler; - private final DeleteUserFilterHandler deleteFilterHandler; - private final UpdateUserFilterHandler updateUserFilterHandler; - - @Autowired - public UserFilterController(ProjectExtractor projectExtractor, GetUserFilterHandler getFilterHandler, - DeleteUserFilterHandler deleteFilterHandler, UpdateUserFilterHandler updateUserFilterHandler) { - this.projectExtractor = projectExtractor; - this.getFilterHandler = getFilterHandler; - this.deleteFilterHandler = deleteFilterHandler; - this.updateUserFilterHandler = updateUserFilterHandler; - } - - @Transactional - @PostMapping - @ResponseStatus(HttpStatus.CREATED) - @ApiOperation("Create user filter") - public EntryCreatedRS createFilter(@PathVariable String projectName, @RequestBody @Validated UpdateUserFilterRQ createFilterRQ, - @AuthenticationPrincipal ReportPortalUser user) { - return updateUserFilterHandler.createFilter(createFilterRQ, projectName, user); - } - - @Transactional(readOnly = true) - @GetMapping(value = "/{filterId}") - @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get specified user filter by id") - public UserFilterResource getFilter(@PathVariable String projectName, @PathVariable Long filterId, - @AuthenticationPrincipal ReportPortalUser user) { - return getFilterHandler.getUserFilter(filterId, projectExtractor.extractProjectDetails(user, projectName)); - } - - @Transactional(readOnly = true) - @GetMapping - @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get filters") - public Iterable getAllFilters(@PathVariable String projectName, @SortFor(UserFilter.class) Pageable pageable, - @FilterFor(UserFilter.class) Filter filter, @AuthenticationPrincipal ReportPortalUser user) { - return getFilterHandler.getUserFilters(projectName, pageable, filter, user); - } - - @Transactional - @DeleteMapping(value = "/{filterId}") - @ResponseStatus(HttpStatus.OK) - @ApiOperation("Delete specified user filter by id") - public OperationCompletionRS deleteFilter(@PathVariable String projectName, @PathVariable Long filterId, - @AuthenticationPrincipal ReportPortalUser user) { - return deleteFilterHandler.deleteFilter(filterId, projectExtractor.extractProjectDetails(user, projectName), user); - } - - @Transactional(readOnly = true) - @GetMapping(value = "/names") - @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get available filter names") - public Iterable getAllFiltersNames(@PathVariable String projectName, @SortFor(UserFilter.class) Pageable pageable, - @FilterFor(UserFilter.class) Filter filter, @AuthenticationPrincipal ReportPortalUser user) { - return getFilterHandler.getFiltersNames(projectExtractor.extractProjectDetails(user, projectName), pageable, filter, user); - } - - @Transactional - @PutMapping(value = "/{filterId}") - @ResponseStatus(HttpStatus.OK) - @ApiOperation("Update specified user filter") - public OperationCompletionRS updateUserFilter(@PathVariable String projectName, @PathVariable Long filterId, - @RequestBody @Validated UpdateUserFilterRQ updateRQ, @AuthenticationPrincipal ReportPortalUser user) { - return updateUserFilterHandler.updateUserFilter( - filterId, - updateRQ, - projectExtractor.extractProjectDetails(user, projectName), - user - ); - } - - @Transactional(readOnly = true) - @GetMapping(value = "/filters") - @ResponseStatus(HttpStatus.OK) - @ApiOperation("Get list of specified user filters") - public List getUserFilters(@PathVariable String projectName, @RequestParam(value = "ids") Long[] ids, - @AuthenticationPrincipal ReportPortalUser user) { - List filters = getFilterHandler.getFiltersById(ids, projectExtractor.extractProjectDetails(user, projectName), user); - return filters.stream().map(UserFilterConverter.TO_FILTER_RESOURCE).collect(Collectors.toList()); - } - - @Transactional - @RequestMapping(method = RequestMethod.PUT) - @ResponseStatus(HttpStatus.OK) - @ApiOperation("Update list of user filters") - public List updateUserFilters(@PathVariable String projectName, - @RequestBody @Validated CollectionsRQ updateRQ, @AuthenticationPrincipal ReportPortalUser user) { - return updateUserFilterHandler.updateUserFilter(updateRQ, projectExtractor.extractProjectDetails(user, projectName), user); - } + private final ProjectExtractor projectExtractor; + private final GetUserFilterHandler getFilterHandler; + private final DeleteUserFilterHandler deleteFilterHandler; + private final UpdateUserFilterHandler updateUserFilterHandler; + + @Autowired + public UserFilterController(ProjectExtractor projectExtractor, + GetUserFilterHandler getFilterHandler, DeleteUserFilterHandler deleteFilterHandler, + UpdateUserFilterHandler updateUserFilterHandler) { + this.projectExtractor = projectExtractor; + this.getFilterHandler = getFilterHandler; + this.deleteFilterHandler = deleteFilterHandler; + this.updateUserFilterHandler = updateUserFilterHandler; + } + + @Transactional + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + @Operation(summary = "Create user filter") + public EntryCreatedRS createFilter(@PathVariable String projectName, + @RequestBody @Validated UpdateUserFilterRQ createFilterRQ, + @AuthenticationPrincipal ReportPortalUser user) { + return updateUserFilterHandler.createFilter(createFilterRQ, projectName, user); + } + + @Transactional(readOnly = true) + @GetMapping(value = "/{filterId}") + @ResponseStatus(HttpStatus.OK) + @Operation(summary = "Get specified user filter by id") + public UserFilterResource getFilter(@PathVariable String projectName, @PathVariable Long filterId, + @AuthenticationPrincipal ReportPortalUser user) { + return getFilterHandler.getUserFilter( + filterId, projectExtractor.extractProjectDetails(user, projectName)); + } + + @Transactional(readOnly = true) + @GetMapping + @ResponseStatus(HttpStatus.OK) + @Operation(summary = "Get filters") + public Iterable getAllFilters(@PathVariable String projectName, + @SortFor(UserFilter.class) Pageable pageable, @FilterFor(UserFilter.class) Filter filter, + @AuthenticationPrincipal ReportPortalUser user) { + return getFilterHandler.getUserFilters(projectName, pageable, filter, user); + } + + @Transactional + @DeleteMapping(value = "/{filterId}") + @ResponseStatus(HttpStatus.OK) + @Operation(summary = "Delete specified user filter by id") + public OperationCompletionRS deleteFilter(@PathVariable String projectName, + @PathVariable Long filterId, @AuthenticationPrincipal ReportPortalUser user) { + return deleteFilterHandler.deleteFilter( + filterId, projectExtractor.extractProjectDetails(user, projectName), user); + } + + @Transactional(readOnly = true) + @GetMapping(value = "/names") + @ResponseStatus(HttpStatus.OK) + @Operation(summary = "Get available filter names") + public Iterable getAllFiltersNames(@PathVariable String projectName, + @SortFor(UserFilter.class) Pageable pageable, @FilterFor(UserFilter.class) Filter filter, + @AuthenticationPrincipal ReportPortalUser user) { + return getFilterHandler.getFiltersNames( + projectExtractor.extractProjectDetails(user, projectName), pageable, filter, user); + } + + @Transactional + @PutMapping(value = "/{filterId}") + @ResponseStatus(HttpStatus.OK) + @Operation(summary = "Update specified user filter") + public OperationCompletionRS updateUserFilter(@PathVariable String projectName, + @PathVariable Long filterId, @RequestBody @Validated UpdateUserFilterRQ updateRQ, + @AuthenticationPrincipal ReportPortalUser user) { + return updateUserFilterHandler.updateUserFilter(filterId, updateRQ, + projectExtractor.extractProjectDetails(user, projectName), user + ); + } + + @Transactional(readOnly = true) + @GetMapping(value = "/filters") + @ResponseStatus(HttpStatus.OK) + @Operation(summary = "Get list of specified user filters") + public List getUserFilters(@PathVariable String projectName, + @RequestParam(value = "ids") Long[] ids, @AuthenticationPrincipal ReportPortalUser user) { + List filters = getFilterHandler.getFiltersById(ids, + projectExtractor.extractProjectDetails(user, projectName), user + ); + return filters.stream().map(UserFilterConverter.TO_FILTER_RESOURCE) + .collect(Collectors.toList()); + } + + @Transactional + @RequestMapping(method = RequestMethod.PUT) + @ResponseStatus(HttpStatus.OK) + @Operation(summary = "Update list of user filters") + public List updateUserFilters(@PathVariable String projectName, + @RequestBody @Validated CollectionsRQ updateRQ, + @AuthenticationPrincipal ReportPortalUser user) { + return updateUserFilterHandler.updateUserFilter( + updateRQ, projectExtractor.extractProjectDetails(user, projectName), user); + } } diff --git a/src/main/java/com/epam/ta/reportportal/ws/controller/WidgetController.java b/src/main/java/com/epam/ta/reportportal/ws/controller/WidgetController.java index 14a9fc7eb7..5216a86043 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/controller/WidgetController.java +++ b/src/main/java/com/epam/ta/reportportal/ws/controller/WidgetController.java @@ -16,21 +16,28 @@ package com.epam.ta.reportportal.ws.controller; +import static com.epam.ta.reportportal.auth.permissions.Permissions.ASSIGNED_TO_PROJECT; +import static com.epam.ta.reportportal.commons.EntityUtils.normalizeId; +import static org.springframework.http.HttpStatus.CREATED; +import static org.springframework.http.HttpStatus.OK; + import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.core.widget.CreateWidgetHandler; import com.epam.ta.reportportal.core.widget.GetWidgetHandler; import com.epam.ta.reportportal.core.widget.UpdateWidgetHandler; import com.epam.ta.reportportal.entity.widget.Widget; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.widget.WidgetPreviewRQ; +import com.epam.ta.reportportal.model.widget.WidgetRQ; +import com.epam.ta.reportportal.model.widget.WidgetResource; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.widget.WidgetPreviewRQ; -import com.epam.ta.reportportal.ws.model.widget.WidgetRQ; -import com.epam.ta.reportportal.ws.model.widget.WidgetResource; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.epam.ta.reportportal.ws.resolver.FilterFor; import com.epam.ta.reportportal.ws.resolver.SortFor; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import java.util.Map; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; @@ -39,14 +46,15 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.util.MultiValueMap; import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.Map; - -import static com.epam.ta.reportportal.auth.permissions.Permissions.ASSIGNED_TO_PROJECT; -import static com.epam.ta.reportportal.commons.EntityUtils.normalizeId; -import static org.springframework.http.HttpStatus.CREATED; -import static org.springframework.http.HttpStatus.OK; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; /** * @author Pavel Bortnik @@ -54,73 +62,88 @@ @RestController @PreAuthorize(ASSIGNED_TO_PROJECT) @RequestMapping("/v1/{projectName}/widget") +@Tag(name = "widget-controller", description = "Widget Controller") public class WidgetController { - private final ProjectExtractor projectExtractor; - private final CreateWidgetHandler createWidgetHandler; - private final UpdateWidgetHandler updateWidgetHandler; - private final GetWidgetHandler getWidgetHandler; + private final ProjectExtractor projectExtractor; + private final CreateWidgetHandler createWidgetHandler; + private final UpdateWidgetHandler updateWidgetHandler; + private final GetWidgetHandler getWidgetHandler; - @Autowired - public WidgetController(ProjectExtractor projectExtractor, CreateWidgetHandler createWidgetHandler, UpdateWidgetHandler updateWidgetHandler, - GetWidgetHandler getWidgetHandler) { - this.projectExtractor = projectExtractor; - this.createWidgetHandler = createWidgetHandler; - this.updateWidgetHandler = updateWidgetHandler; - this.getWidgetHandler = getWidgetHandler; - } + @Autowired + public WidgetController(ProjectExtractor projectExtractor, + CreateWidgetHandler createWidgetHandler, UpdateWidgetHandler updateWidgetHandler, + GetWidgetHandler getWidgetHandler) { + this.projectExtractor = projectExtractor; + this.createWidgetHandler = createWidgetHandler; + this.updateWidgetHandler = updateWidgetHandler; + this.getWidgetHandler = getWidgetHandler; + } - @Transactional - @PostMapping - @ResponseStatus(CREATED) - @ApiOperation("Create a new widget") - public EntryCreatedRS createWidget(@RequestBody @Validated WidgetRQ createWidget, @AuthenticationPrincipal ReportPortalUser user, - @PathVariable String projectName) { - return createWidgetHandler.createWidget(createWidget, projectExtractor.extractProjectDetails(user, projectName), user); - } + @Transactional + @PostMapping + @ResponseStatus(CREATED) + @Operation(summary = "Create a new widget") + public EntryCreatedRS createWidget(@RequestBody @Validated WidgetRQ createWidget, + @AuthenticationPrincipal ReportPortalUser user, @PathVariable String projectName) { + return createWidgetHandler.createWidget( + createWidget, projectExtractor.extractProjectDetails(user, projectName), user); + } - @Transactional(readOnly = true) - @GetMapping(value = "/{widgetId}") - @ResponseStatus(OK) - @ApiOperation("Get widget by ID") - public WidgetResource getWidget(@PathVariable String projectName, @PathVariable Long widgetId, - @AuthenticationPrincipal ReportPortalUser user) { - return getWidgetHandler.getWidget(widgetId, projectExtractor.extractProjectDetails(user, projectName), user); - } + @Transactional(readOnly = true) + @GetMapping(value = "/{widgetId}") + @ResponseStatus(OK) + @Operation(summary = "Get widget by ID") + public WidgetResource getWidget(@PathVariable String projectName, @PathVariable Long widgetId, + @AuthenticationPrincipal ReportPortalUser user) { + return getWidgetHandler.getWidget( + widgetId, projectExtractor.extractProjectDetails(user, projectName), user); + } - @Transactional(readOnly = true) - @GetMapping(value = "multilevel/{widgetId}") - @ResponseStatus(OK) - @ApiOperation("Get multilevel widget by ID") - public WidgetResource getWidget(@PathVariable String projectName, @PathVariable Long widgetId, - @RequestParam(required = false, name = "attributes") String[] attributes, @RequestParam MultiValueMap params, @AuthenticationPrincipal ReportPortalUser user) { - return getWidgetHandler.getWidget(widgetId, ArrayUtils.nullToEmpty(attributes), params, projectExtractor.extractProjectDetails(user, projectName), user); - } + @Transactional(readOnly = true) + @GetMapping(value = "multilevel/{widgetId}") + @ResponseStatus(OK) + @Operation(summary = "Get multilevel widget by ID") + public WidgetResource getWidget(@PathVariable String projectName, @PathVariable Long widgetId, + @RequestParam(required = false, name = "attributes") String[] attributes, + @RequestParam MultiValueMap params, + @AuthenticationPrincipal ReportPortalUser user) { + return getWidgetHandler.getWidget( + widgetId, ArrayUtils.nullToEmpty(attributes), params, + projectExtractor.extractProjectDetails(user, projectName), user + ); + } - @Transactional(readOnly = true) - @PostMapping(value = "/preview") - @ResponseStatus(OK) - @ApiOperation("Get widget preview") - public Map getWidgetPreview(@PathVariable String projectName, @RequestBody @Validated WidgetPreviewRQ previewRQ, - @AuthenticationPrincipal ReportPortalUser user) { - return getWidgetHandler.getWidgetPreview(previewRQ, projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user); - } + @Transactional(readOnly = true) + @PostMapping(value = "/preview") + @ResponseStatus(OK) + @Operation(summary = "Get widget preview") + public Map getWidgetPreview(@PathVariable String projectName, + @RequestBody @Validated WidgetPreviewRQ previewRQ, + @AuthenticationPrincipal ReportPortalUser user) { + return getWidgetHandler.getWidgetPreview( + previewRQ, projectExtractor.extractProjectDetails(user, normalizeId(projectName)), user); + } - @Transactional - @PutMapping(value = "/{widgetId}") - @ResponseStatus(OK) - @ApiOperation("Update specified widget") - public OperationCompletionRS updateWidget(@PathVariable String projectName, @PathVariable Long widgetId, - @RequestBody @Validated WidgetRQ updateRQ, @AuthenticationPrincipal ReportPortalUser user) { - return updateWidgetHandler.updateWidget(widgetId, updateRQ, projectExtractor.extractProjectDetails(user, projectName), user); - } + @Transactional + @PutMapping(value = "/{widgetId}") + @ResponseStatus(OK) + @Operation(summary = "Update specified widget") + public OperationCompletionRS updateWidget(@PathVariable String projectName, + @PathVariable Long widgetId, @RequestBody @Validated WidgetRQ updateRQ, + @AuthenticationPrincipal ReportPortalUser user) { + return updateWidgetHandler.updateWidget( + widgetId, updateRQ, projectExtractor.extractProjectDetails(user, projectName), user); + } - @Transactional(readOnly = true) - @GetMapping(value = "/names/all") - @ResponseStatus(OK) - @ApiOperation("Load all widget names which belong to a user") - public Iterable getWidgetNames(@PathVariable String projectName, @SortFor(Widget.class) Pageable pageable, - @FilterFor(Widget.class) Filter filter, @AuthenticationPrincipal ReportPortalUser user) { - return getWidgetHandler.getOwnNames(projectExtractor.extractProjectDetails(user, projectName), pageable, filter, user); - } + @Transactional(readOnly = true) + @GetMapping(value = "/names/all") + @ResponseStatus(OK) + @Operation(summary = "Load all widget names which belong to a user") + public Iterable getWidgetNames(@PathVariable String projectName, + @SortFor(Widget.class) Pageable pageable, @FilterFor(Widget.class) Filter filter, + @AuthenticationPrincipal ReportPortalUser user) { + return getWidgetHandler.getOwnNames( + projectExtractor.extractProjectDetails(user, projectName), pageable, filter, user); + } } \ No newline at end of file diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/LogResourceAssembler.java b/src/main/java/com/epam/ta/reportportal/ws/converter/LogResourceAssembler.java index 79910bbbe5..ae7f4f0d25 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/LogResourceAssembler.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/LogResourceAssembler.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.ws.converter; import com.epam.ta.reportportal.entity.log.LogFull; +import com.epam.ta.reportportal.model.log.LogResource; import com.epam.ta.reportportal.ws.converter.converters.LogConverter; -import com.epam.ta.reportportal.ws.model.log.LogResource; import org.springframework.stereotype.Service; /** diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/PagedResourcesAssembler.java b/src/main/java/com/epam/ta/reportportal/ws/converter/PagedResourcesAssembler.java index c4fb6315a9..95fa131a6d 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/PagedResourcesAssembler.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/PagedResourcesAssembler.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.ws.converter; -import com.epam.ta.reportportal.ws.model.PagedResponse; +import com.epam.ta.reportportal.model.PagedResponse; import com.google.common.base.Preconditions; import java.util.List; import java.util.function.Function; @@ -35,16 +35,16 @@ */ public abstract class PagedResourcesAssembler extends ResourceAssembler { - public static Function, com.epam.ta.reportportal.ws.model.Page> pageConverter() { - return page -> new com.epam.ta.reportportal.ws.model.Page<>(page.getContent(), - new com.epam.ta.reportportal.ws.model.Page.PageMetadata(page.getSize(), + public static Function, com.epam.ta.reportportal.model.Page> pageConverter() { + return page -> new com.epam.ta.reportportal.model.Page<>(page.getContent(), + new com.epam.ta.reportportal.model.Page.PageMetadata(page.getSize(), page.getNumber() + 1L, page.getTotalElements(), page.getTotalPages() ) ); } - public static Function, com.epam.ta.reportportal.ws.model.Page> pageConverter( + public static Function, com.epam.ta.reportportal.model.Page> pageConverter( Function modelConverter) { return page -> PagedResourcesAssembler.pageConverter().apply(page.map(modelConverter)); } @@ -67,7 +67,7 @@ public static Function, PagedResponse> pagedResponseConverter( .apply(page.map(modelConverter)); } - public static Function, com.epam.ta.reportportal.ws.model.Page> pageMultiConverter( + public static Function, com.epam.ta.reportportal.model.Page> pageMultiConverter( Function, List> modelConverter) { return page -> PagedResourcesAssembler.pageConverter() .apply(new PageImpl<>(modelConverter.apply(page.getContent()), @@ -77,18 +77,18 @@ public static Function, com.epam.ta.reportportal.ws.model.Page } /** - * Creates {@link com.epam.ta.reportportal.ws.model.Page} from {@link Page} DB query result + * Creates {@link com.epam.ta.reportportal.model.Page} from {@link Page} DB query result * * @param content Page to be processed * @return Transformed Page * @deprecated in favor of using converters based on JDK8 Functions */ @Deprecated - public com.epam.ta.reportportal.ws.model.Page toPagedResources(Page content) { + public com.epam.ta.reportportal.model.Page toPagedResources(Page content) { Preconditions.checkNotNull(content, "Content should be null"); - return new com.epam.ta.reportportal.ws.model.Page<>(toResources(content), - new com.epam.ta.reportportal.ws.model.Page.PageMetadata(content.getSize(), + return new com.epam.ta.reportportal.model.Page<>(toResources(content), + new com.epam.ta.reportportal.model.Page.PageMetadata(content.getSize(), content.getNumber() + 1L, content.getTotalElements(), content.getTotalPages() ) diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/TestItemResourceAssembler.java b/src/main/java/com/epam/ta/reportportal/ws/converter/TestItemResourceAssembler.java index cf5ac71417..e8bbd6f7c7 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/TestItemResourceAssembler.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/TestItemResourceAssembler.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.entity.item.PathName; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.ws.converter.converters.TestItemConverter; -import com.epam.ta.reportportal.ws.model.TestItemResource; +import com.epam.ta.reportportal.ws.reporting.TestItemResource; import javax.annotation.Nullable; import org.springframework.stereotype.Component; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/DashboardBuilder.java b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/DashboardBuilder.java index 4ed3e4e8ef..06afe99aaa 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/DashboardBuilder.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/DashboardBuilder.java @@ -16,75 +16,75 @@ package com.epam.ta.reportportal.ws.converter.builders; +import static java.util.Optional.ofNullable; + import com.epam.ta.reportportal.entity.dashboard.Dashboard; import com.epam.ta.reportportal.entity.dashboard.DashboardWidget; import com.epam.ta.reportportal.entity.project.Project; -import com.epam.ta.reportportal.ws.model.dashboard.CreateDashboardRQ; -import com.epam.ta.reportportal.ws.model.dashboard.UpdateDashboardRQ; - +import com.epam.ta.reportportal.model.dashboard.CreateDashboardRQ; +import com.epam.ta.reportportal.model.dashboard.UpdateDashboardRQ; import java.util.Objects; import java.util.Optional; import java.util.function.Supplier; -import static java.util.Optional.ofNullable; - /** * @author Pavel Bortnik */ public class DashboardBuilder implements Supplier { - private Dashboard dashboard; + private Dashboard dashboard; - public DashboardBuilder() { - dashboard = new Dashboard(); - } + public DashboardBuilder() { + dashboard = new Dashboard(); + } - public DashboardBuilder(Dashboard dashboard) { - this.dashboard = dashboard; - } + public DashboardBuilder(Dashboard dashboard) { + this.dashboard = dashboard; + } - public DashboardBuilder addDashboardRq(CreateDashboardRQ rq) { - dashboard.setName(rq.getName()); - dashboard.setDescription(rq.getDescription()); - return this; - } + public DashboardBuilder addDashboardRq(CreateDashboardRQ rq) { + dashboard.setName(rq.getName()); + dashboard.setDescription(rq.getDescription()); + return this; + } - public DashboardBuilder addProject(Long projectId) { - Project project = new Project(); - project.setId(projectId); - dashboard.setProject(project); - return this; - } + public DashboardBuilder addProject(Long projectId) { + Project project = new Project(); + project.setId(projectId); + dashboard.setProject(project); + return this; + } - public DashboardBuilder addUpdateRq(UpdateDashboardRQ rq) { - Optional.ofNullable(rq.getName()).ifPresent(name -> dashboard.setName(name)); - Optional.ofNullable(rq.getDescription()).ifPresent(description -> dashboard.setDescription(description)); - Optional.ofNullable(rq.getWidgets()).ifPresent(widgets -> { - for (DashboardWidget dashboardWidget : dashboard.getDashboardWidgets()) { - widgets.stream() - .filter(updWidget -> Objects.equals(dashboardWidget.getId().getWidgetId(), updWidget.getWidgetId())) - .forEach(updWidget -> { - ofNullable(updWidget.getWidgetPosition()).ifPresent(position -> { - dashboardWidget.setPositionX(position.getX()); - dashboardWidget.setPositionY(position.getY()); - }); - ofNullable(updWidget.getWidgetSize()).ifPresent(size -> { - dashboardWidget.setWidth(size.getWidth()); - dashboardWidget.setHeight(size.getHeight()); - }); - }); - } - }); - return this; - } + public DashboardBuilder addUpdateRq(UpdateDashboardRQ rq) { + Optional.ofNullable(rq.getName()).ifPresent(name -> dashboard.setName(name)); + Optional.ofNullable(rq.getDescription()) + .ifPresent(description -> dashboard.setDescription(description)); + Optional.ofNullable(rq.getWidgets()).ifPresent(widgets -> { + for (DashboardWidget dashboardWidget : dashboard.getDashboardWidgets()) { + widgets.stream().filter(updWidget -> Objects.equals(dashboardWidget.getId().getWidgetId(), + updWidget.getWidgetId() + )).forEach(updWidget -> { + ofNullable(updWidget.getWidgetPosition()).ifPresent(position -> { + dashboardWidget.setPositionX(position.getX()); + dashboardWidget.setPositionY(position.getY()); + }); + ofNullable(updWidget.getWidgetSize()).ifPresent(size -> { + dashboardWidget.setWidth(size.getWidth()); + dashboardWidget.setHeight(size.getHeight()); + }); + }); + } + }); + return this; + } - public DashboardBuilder addOwner(String owner) { - dashboard.setOwner(owner); - return this; - } + public DashboardBuilder addOwner(String owner) { + dashboard.setOwner(owner); + return this; + } - @Override - public Dashboard get() { - return dashboard; - } + @Override + public Dashboard get() { + return dashboard; + } } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/LaunchBuilder.java b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/LaunchBuilder.java index de875316f3..dde78b5014 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/LaunchBuilder.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/LaunchBuilder.java @@ -25,11 +25,11 @@ import com.epam.ta.reportportal.entity.enums.StatusEnum; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributesRQ; -import com.epam.ta.reportportal.ws.model.launch.Mode; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributesRQ; +import com.epam.ta.reportportal.ws.reporting.Mode; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; import com.google.common.base.Preconditions; import java.util.Date; import java.util.Optional; @@ -85,7 +85,8 @@ public LaunchBuilder addProject(Long projectId) { return this; } - public LaunchBuilder addAttribute(ItemAttributeResource attributeResource) { + public LaunchBuilder addAttribute( + com.epam.ta.reportportal.ws.reporting.ItemAttributeResource attributeResource) { ItemAttribute itemAttribute = FROM_RESOURCE.apply(attributeResource); itemAttribute.setLaunch(launch); launch.getAttributes().add(itemAttribute); diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/LogFullBuilder.java b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/LogFullBuilder.java index 9f679b4dce..b8b0be4fa9 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/LogFullBuilder.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/LogFullBuilder.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.entity.log.LogFull; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; import java.util.UUID; import java.util.function.Supplier; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/PatternTemplateBuilder.java b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/PatternTemplateBuilder.java index f60ef03f0c..80754792ac 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/PatternTemplateBuilder.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/PatternTemplateBuilder.java @@ -20,8 +20,8 @@ import com.epam.ta.reportportal.entity.pattern.PatternTemplate; import com.epam.ta.reportportal.entity.pattern.PatternTemplateType; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.project.config.pattern.CreatePatternTemplateRQ; +import com.epam.ta.reportportal.model.project.config.pattern.CreatePatternTemplateRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.function.Supplier; import org.apache.commons.lang3.StringUtils; @@ -38,10 +38,10 @@ public PatternTemplateBuilder() { public PatternTemplateBuilder withCreateRequest(CreatePatternTemplateRQ createRequest) { patternTemplate.setTemplateType(PatternTemplateType.fromString(createRequest.getType()) - .orElseThrow(() -> new ReportPortalException( - ErrorType.BAD_REQUEST_ERROR, + .orElseThrow(() -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, Suppliers.formattedSupplier("Unknown pattern template type - '{}'", - createRequest.getType()).get() + createRequest.getType() + ).get() ))); patternTemplate.setName(StringUtils.trim(createRequest.getName())); patternTemplate.setValue(createRequest.getValue()); diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/TestItemBuilder.java b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/TestItemBuilder.java index 504b9885b0..6cedf7fed2 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/TestItemBuilder.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/TestItemBuilder.java @@ -28,11 +28,11 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.item.TestItemResults; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.ParameterResource; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributesRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributesRQ; +import com.epam.ta.reportportal.ws.reporting.ParameterResource; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.List; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/UserBuilder.java b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/UserBuilder.java index 1586fc65f1..ed44e2dc4f 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/UserBuilder.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/UserBuilder.java @@ -23,8 +23,8 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.entity.user.UserType; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQConfirm; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQFull; +import com.epam.ta.reportportal.model.user.CreateUserRQConfirm; +import com.epam.ta.reportportal.model.user.CreateUserRQFull; import java.util.Date; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/UserFilterBuilder.java b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/UserFilterBuilder.java index a53778e74d..900f6a7916 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/UserFilterBuilder.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/UserFilterBuilder.java @@ -16,6 +16,9 @@ package com.epam.ta.reportportal.ws.converter.builders; +import static java.util.Optional.ofNullable; +import static java.util.stream.Collectors.toList; + import com.epam.ta.reportportal.commons.querygen.Condition; import com.epam.ta.reportportal.commons.querygen.FilterCondition; import com.epam.ta.reportportal.entity.filter.FilterSort; @@ -23,97 +26,91 @@ import com.epam.ta.reportportal.entity.filter.UserFilter; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.filter.Order; -import com.epam.ta.reportportal.ws.model.filter.UpdateUserFilterRQ; -import com.epam.ta.reportportal.ws.model.filter.UserFilterCondition; -import org.springframework.data.domain.Sort; - +import com.epam.ta.reportportal.model.filter.Order; +import com.epam.ta.reportportal.model.filter.UpdateUserFilterRQ; +import com.epam.ta.reportportal.model.filter.UserFilterCondition; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Set; import java.util.function.Supplier; - -import static java.util.Optional.ofNullable; -import static java.util.stream.Collectors.toList; +import org.springframework.data.domain.Sort; /** * @author Pavel Bortnik */ public class UserFilterBuilder implements Supplier { - private UserFilter userFilter; + private UserFilter userFilter; - public UserFilterBuilder() { - userFilter = new UserFilter(); - } + public UserFilterBuilder() { + userFilter = new UserFilter(); + } - public UserFilterBuilder(UserFilter userFilter) { - this.userFilter = userFilter; - } + public UserFilterBuilder(UserFilter userFilter) { + this.userFilter = userFilter; + } - public UserFilterBuilder addFilterRq(UpdateUserFilterRQ rq) { - userFilter.setDescription(rq.getDescription()); - ofNullable(rq.getName()).ifPresent(it -> userFilter.setName(it)); - ofNullable(rq.getObjectType()).ifPresent(it -> userFilter.setTargetClass(ObjectType.getObjectTypeByName(rq.getObjectType()))); - addFilterConditions(rq.getConditions()); - addSelectionParameters(rq.getOrders()); - return this; - } + public UserFilterBuilder addFilterRq(UpdateUserFilterRQ rq) { + userFilter.setDescription(rq.getDescription()); + ofNullable(rq.getName()).ifPresent(it -> userFilter.setName(it)); + ofNullable(rq.getObjectType()).ifPresent( + it -> userFilter.setTargetClass(ObjectType.getObjectTypeByName(rq.getObjectType()))); + addFilterConditions(rq.getConditions()); + addSelectionParameters(rq.getOrders()); + return this; + } - /** - * Convert provided conditions into db and add them to filter object - * - * @param conditions Conditions from rq - * @return UserFilterBuilder - */ - public UserFilterBuilder addFilterConditions(Set conditions) { - userFilter.getFilterCondition().clear(); - ofNullable(conditions).ifPresent(c -> userFilter.getFilterCondition() - .addAll(c.stream() - .map(entity -> FilterCondition.builder() - .withSearchCriteria(entity.getFilteringField()) - .withValue(entity.getValue()) - .withNegative(Condition.isNegative(entity.getCondition())) - .withCondition(Condition.findByMarker(entity.getCondition()) - .orElseThrow(() -> new ReportPortalException(ErrorType.INCORRECT_REQUEST, entity.getCondition()))) - .build()) - .collect(toList()))); + /** + * Convert provided conditions into db and add them to filter object + * + * @param conditions Conditions from rq + * @return UserFilterBuilder + */ + public UserFilterBuilder addFilterConditions(Set conditions) { + userFilter.getFilterCondition().clear(); + ofNullable(conditions).ifPresent(c -> userFilter.getFilterCondition().addAll(c.stream().map( + entity -> FilterCondition.builder().withSearchCriteria(entity.getFilteringField()) + .withValue(entity.getValue()).withNegative(Condition.isNegative(entity.getCondition())) + .withCondition(Condition.findByMarker(entity.getCondition()).orElseThrow( + () -> new ReportPortalException(ErrorType.INCORRECT_REQUEST, + entity.getCondition() + ))).build()).collect(toList()))); - return this; - } + return this; + } - /** - * Convert provided selection into db and add them in correct order - * to filter object - * - * @param orders Filter sorting conditions - * @return UserFilterBuilder - */ - public UserFilterBuilder addSelectionParameters(List orders) { - userFilter.getFilterSorts().clear(); - ofNullable(orders).ifPresent(o -> o.forEach(order -> { - FilterSort filterSort = new FilterSort(); - filterSort.setField(order.getSortingColumnName()); - filterSort.setDirection(order.getIsAsc() ? Sort.Direction.ASC : Sort.Direction.DESC); - userFilter.getFilterSorts().add(filterSort); - })); - return this; - } + /** + * Convert provided selection into db and add them in correct order + * to filter object + * + * @param orders Filter sorting conditions + * @return UserFilterBuilder + */ + public UserFilterBuilder addSelectionParameters(List orders) { + userFilter.getFilterSorts().clear(); + ofNullable(orders).ifPresent(o -> o.forEach(order -> { + FilterSort filterSort = new FilterSort(); + filterSort.setField(order.getSortingColumnName()); + filterSort.setDirection(order.getIsAsc() ? Sort.Direction.ASC : Sort.Direction.DESC); + userFilter.getFilterSorts().add(filterSort); + })); + return this; + } - public UserFilterBuilder addProject(Long projectId) { - Project project = new Project(); - project.setId(projectId); - userFilter.setProject(project); - return this; - } + public UserFilterBuilder addProject(Long projectId) { + Project project = new Project(); + project.setId(projectId); + userFilter.setProject(project); + return this; + } - public UserFilterBuilder addOwner(String owner) { - userFilter.setOwner(owner); - return this; - } + public UserFilterBuilder addOwner(String owner) { + userFilter.setOwner(owner); + return this; + } - @Override - public UserFilter get() { - return userFilter; - } + @Override + public UserFilter get() { + return userFilter; + } } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/WidgetBuilder.java b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/WidgetBuilder.java index 7dcc0e1465..820af285ff 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/builders/WidgetBuilder.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/builders/WidgetBuilder.java @@ -16,106 +16,113 @@ package com.epam.ta.reportportal.ws.converter.builders; +import static java.util.Optional.ofNullable; + import com.epam.ta.reportportal.entity.filter.UserFilter; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.widget.WidgetPreviewRQ; -import com.epam.ta.reportportal.ws.model.widget.WidgetRQ; +import com.epam.ta.reportportal.model.widget.WidgetPreviewRQ; +import com.epam.ta.reportportal.model.widget.WidgetRQ; import com.google.common.collect.Sets; - import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Supplier; -import static java.util.Optional.ofNullable; - /** * @author Pavel Bortnik */ public class WidgetBuilder implements Supplier { - private Widget widget; - - public WidgetBuilder() { - widget = new Widget(); - } - - public WidgetBuilder(Widget widget) { - this.widget = widget; - } - - public WidgetBuilder addWidgetRq(WidgetRQ widgetRQ) { - ofNullable(widgetRQ.getName()).ifPresent(name -> widget.setName(name)); - widget.setDescription(widgetRQ.getDescription()); - - ofNullable(widgetRQ.getContentParameters().getWidgetOptions()).ifPresent(wo -> { - WidgetOptions widgetOptions = ofNullable(widget.getWidgetOptions()).orElseGet(WidgetOptions::new); - Map options = ofNullable(widgetOptions.getOptions()).orElseGet(LinkedHashMap::new); - options.putAll(wo); - widgetOptions.setOptions(options); - widget.setWidgetOptions(widgetOptions); - }); - - widget.setWidgetType(widgetRQ.getWidgetType()); - widget.setItemsCount(widgetRQ.getContentParameters().getItemsCount()); - - widget.getContentFields().clear(); - widget.getContentFields().addAll(ofNullable(widgetRQ.getContentParameters().getContentFields()).orElse(Collections.emptyList())); - return this; - } - - public WidgetBuilder addWidgetPreviewRq(WidgetPreviewRQ previewRQ) { - WidgetOptions widgetOptions = ofNullable(widget.getWidgetOptions()).orElseGet(WidgetOptions::new); - Map options = ofNullable(widgetOptions.getOptions()).orElseGet(LinkedHashMap::new); - options.putAll(previewRQ.getContentParameters().getWidgetOptions()); - - widgetOptions.setOptions(options); - widget.setWidgetOptions(widgetOptions); - - widget.setWidgetType(previewRQ.getWidgetType()); - widget.setItemsCount(previewRQ.getContentParameters().getItemsCount()); - - widget.getContentFields().clear(); - widget.getContentFields().addAll(ofNullable(previewRQ.getContentParameters().getContentFields()).orElse(Collections.emptyList())); - return this; - } - - public WidgetBuilder addProject(Long projectId) { - Project project = new Project(); - project.setId(projectId); - widget.setProject(project); - return this; - } - - public WidgetBuilder addFilters(Iterable userFilters) { - ofNullable(userFilters).ifPresent(it -> widget.setFilters(Sets.newLinkedHashSet(it))); - return this; - } - - public WidgetBuilder addOwner(String owner) { - widget.setOwner(owner); - return this; - } - - public WidgetBuilder addOption(String key, Object value) { - WidgetOptions widgetOptions = ofNullable(widget.getWidgetOptions()).orElseGet(() -> { - WidgetOptions opts = new WidgetOptions(); - widget.setWidgetOptions(opts); - return opts; - }); - Map options = ofNullable(widgetOptions.getOptions()).orElseGet(() -> { - LinkedHashMap opts = new LinkedHashMap<>(); - widgetOptions.setOptions(opts); - return opts; - }); - options.put(key, value); - return this; - } - - @Override - public Widget get() { - return widget; - } + private Widget widget; + + public WidgetBuilder() { + widget = new Widget(); + } + + public WidgetBuilder(Widget widget) { + this.widget = widget; + } + + public WidgetBuilder addWidgetRq(WidgetRQ widgetRQ) { + ofNullable(widgetRQ.getName()).ifPresent(name -> widget.setName(name)); + widget.setDescription(widgetRQ.getDescription()); + + ofNullable(widgetRQ.getContentParameters().getWidgetOptions()).ifPresent(wo -> { + WidgetOptions widgetOptions = + ofNullable(widget.getWidgetOptions()).orElseGet(WidgetOptions::new); + Map options = + ofNullable(widgetOptions.getOptions()).orElseGet(LinkedHashMap::new); + options.putAll(wo); + widgetOptions.setOptions(options); + widget.setWidgetOptions(widgetOptions); + }); + + widget.setWidgetType(widgetRQ.getWidgetType()); + widget.setItemsCount(widgetRQ.getContentParameters().getItemsCount()); + + widget.getContentFields().clear(); + widget.getContentFields().addAll( + ofNullable(widgetRQ.getContentParameters().getContentFields()).orElse( + Collections.emptyList())); + return this; + } + + public WidgetBuilder addWidgetPreviewRq(WidgetPreviewRQ previewRQ) { + WidgetOptions widgetOptions = + ofNullable(widget.getWidgetOptions()).orElseGet(WidgetOptions::new); + Map options = + ofNullable(widgetOptions.getOptions()).orElseGet(LinkedHashMap::new); + options.putAll(previewRQ.getContentParameters().getWidgetOptions()); + + widgetOptions.setOptions(options); + widget.setWidgetOptions(widgetOptions); + + widget.setWidgetType(previewRQ.getWidgetType()); + widget.setItemsCount(previewRQ.getContentParameters().getItemsCount()); + + widget.getContentFields().clear(); + widget.getContentFields().addAll( + ofNullable(previewRQ.getContentParameters().getContentFields()).orElse( + Collections.emptyList())); + return this; + } + + public WidgetBuilder addProject(Long projectId) { + Project project = new Project(); + project.setId(projectId); + widget.setProject(project); + return this; + } + + public WidgetBuilder addFilters(Iterable userFilters) { + ofNullable(userFilters).ifPresent(it -> widget.setFilters(Sets.newLinkedHashSet(it))); + return this; + } + + public WidgetBuilder addOwner(String owner) { + widget.setOwner(owner); + return this; + } + + public WidgetBuilder addOption(String key, Object value) { + WidgetOptions widgetOptions = ofNullable(widget.getWidgetOptions()).orElseGet(() -> { + WidgetOptions opts = new WidgetOptions(); + widget.setWidgetOptions(opts); + return opts; + }); + Map options = ofNullable(widgetOptions.getOptions()).orElseGet(() -> { + LinkedHashMap opts = new LinkedHashMap<>(); + widgetOptions.setOptions(opts); + return opts; + }); + options.put(key, value); + return this; + } + + @Override + public Widget get() { + return widget; + } } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ActivityEventConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ActivityEventConverter.java index 3889e3bab4..528af4e1bf 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ActivityEventConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ActivityEventConverter.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.commons.EntityUtils; import com.epam.ta.reportportal.entity.activity.Activity; -import com.epam.ta.reportportal.ws.model.ActivityEventResource; +import com.epam.ta.reportportal.model.ActivityEventResource; import java.util.Objects; import java.util.function.Function; @@ -32,20 +32,14 @@ public final class ActivityEventConverter { private ActivityEventConverter() { } - public static final Function TO_RESOURCE = activity -> - ActivityEventResource.builder() - .id(activity.getId()) + public static final Function TO_RESOURCE = + activity -> ActivityEventResource.builder().id(activity.getId()) .createdAt(EntityUtils.TO_DATE.apply(activity.getCreatedAt())) - .eventName(activity.getEventName()) - .objectId(activity.getObjectId()) - .objectName(activity.getObjectName()) - .objectType(activity.getObjectType().getValue()) - .projectId(activity.getProjectId()) - .projectName(activity.getProjectName()) - .subjectName(activity.getSubjectName()) - .subjectType(activity.getSubjectType().getValue()) - .subjectId(Objects.toString(activity.getSubjectId(), null)) - .details(activity.getDetails()) + .eventName(activity.getEventName()).objectId(activity.getObjectId()) + .objectName(activity.getObjectName()).objectType(activity.getObjectType().getValue()) + .projectId(activity.getProjectId()).projectName(activity.getProjectName()) + .subjectName(activity.getSubjectName()).subjectType(activity.getSubjectType().getValue()) + .subjectId(Objects.toString(activity.getSubjectId(), null)).details(activity.getDetails()) .build(); } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ApiKeyConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ApiKeyConverter.java index fb88ee5de0..980182a12c 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ApiKeyConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ApiKeyConverter.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.commons.EntityUtils; import com.epam.ta.reportportal.entity.user.ApiKey; -import com.epam.ta.reportportal.ws.model.ApiKeyRS; +import com.epam.ta.reportportal.model.ApiKeyRS; import java.util.function.Function; /** diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/BaseEntityConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/BaseEntityConverter.java index 96f6c2086b..3ec2f15c33 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/BaseEntityConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/BaseEntityConverter.java @@ -17,8 +17,7 @@ package com.epam.ta.reportportal.ws.converter.converters; import com.epam.ta.reportportal.entity.OwnedEntity; -import com.epam.ta.reportportal.ws.model.OwnedEntityResource; - +import com.epam.ta.reportportal.model.OwnedEntityResource; import java.util.function.Function; /** @@ -30,10 +29,11 @@ private BaseEntityConverter() { //static only } - public static final Function TO_OWNED_ENTITY = shareable -> { - OwnedEntityResource ownedEntity = new OwnedEntityResource(); - ownedEntity.setId(String.valueOf(shareable.getId())); - ownedEntity.setOwner(shareable.getOwner()); - return ownedEntity; - }; + public static final Function TO_OWNED_ENTITY = + shareable -> { + OwnedEntityResource ownedEntity = new OwnedEntityResource(); + ownedEntity.setId(String.valueOf(shareable.getId())); + ownedEntity.setOwner(shareable.getOwner()); + return ownedEntity; + }; } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/DashboardConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/DashboardConverter.java index 8a2188a33a..26f6924520 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/DashboardConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/DashboardConverter.java @@ -17,9 +17,8 @@ package com.epam.ta.reportportal.ws.converter.converters; import com.epam.ta.reportportal.entity.dashboard.Dashboard; -import com.epam.ta.reportportal.ws.model.activity.DashboardActivityResource; -import com.epam.ta.reportportal.ws.model.dashboard.DashboardResource; - +import com.epam.ta.reportportal.model.activity.DashboardActivityResource; +import com.epam.ta.reportportal.model.dashboard.DashboardResource; import java.util.function.Function; import java.util.stream.Collectors; @@ -28,27 +27,30 @@ */ public final class DashboardConverter { - private DashboardConverter() { - //static only - } - - public static final Function TO_RESOURCE = dashboard -> { - DashboardResource resource = new DashboardResource(); - resource.setDashboardId(dashboard.getId()); - resource.setName(dashboard.getName()); - resource.setDescription(dashboard.getDescription()); - resource.setWidgets(dashboard.getDashboardWidgets().stream().map(WidgetConverter.TO_OBJECT_MODEL).collect(Collectors.toList())); - resource.setOwner(dashboard.getOwner()); - return resource; - }; - - public static final Function TO_ACTIVITY_RESOURCE = dashboard -> { - DashboardActivityResource resource = new DashboardActivityResource(); - resource.setId(dashboard.getId()); - resource.setName(dashboard.getName()); - resource.setProjectId(dashboard.getProject().getId()); - resource.setDescription(dashboard.getDescription()); - return resource; - }; + private DashboardConverter() { + //static only + } + + public static final Function TO_RESOURCE = dashboard -> { + DashboardResource resource = new DashboardResource(); + resource.setDashboardId(dashboard.getId()); + resource.setName(dashboard.getName()); + resource.setDescription(dashboard.getDescription()); + resource.setWidgets( + dashboard.getDashboardWidgets().stream().map(WidgetConverter.TO_OBJECT_MODEL) + .collect(Collectors.toList())); + resource.setOwner(dashboard.getOwner()); + return resource; + }; + + public static final Function TO_ACTIVITY_RESOURCE = + dashboard -> { + DashboardActivityResource resource = new DashboardActivityResource(); + resource.setId(dashboard.getId()); + resource.setName(dashboard.getName()); + resource.setProjectId(dashboard.getProject().getId()); + resource.setDescription(dashboard.getDescription()); + return resource; + }; } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ExceptionConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ExceptionConverter.java index 5bda88f895..fefe924672 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ExceptionConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ExceptionConverter.java @@ -1,7 +1,7 @@ package com.epam.ta.reportportal.ws.converter.converters; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorRS; +import com.epam.ta.reportportal.ws.reporting.ErrorRS; import java.util.function.Function; public class ExceptionConverter { diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IntegrationConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IntegrationConverter.java index 0200049578..837c5d803e 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IntegrationConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IntegrationConverter.java @@ -25,10 +25,10 @@ import com.epam.ta.reportportal.entity.EmailSettingsEnum; import com.epam.ta.reportportal.entity.integration.Integration; import com.epam.ta.reportportal.entity.integration.IntegrationParams; -import com.epam.ta.reportportal.ws.model.activity.IntegrationActivityResource; -import com.epam.ta.reportportal.ws.model.integration.AuthFlowEnum; -import com.epam.ta.reportportal.ws.model.integration.IntegrationResource; -import com.epam.ta.reportportal.ws.model.integration.IntegrationTypeResource; +import com.epam.ta.reportportal.model.activity.IntegrationActivityResource; +import com.epam.ta.reportportal.model.integration.AuthFlowEnum; +import com.epam.ta.reportportal.model.integration.IntegrationResource; +import com.epam.ta.reportportal.model.integration.IntegrationTypeResource; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -41,62 +41,61 @@ */ public final class IntegrationConverter { - private static final List IGNORE_FIELDS = List.of( - EmailSettingsEnum.PASSWORD.getAttribute(), - SauceLabsProperties.ACCESS_TOKEN.getName(), - BtsProperties.OAUTH_ACCESS_KEY.getName(), - BtsProperties.API_TOKEN.getName(), - AuthProperties.MANAGER_PASSWORD.getName() - ); + private static final List IGNORE_FIELDS = + List.of(EmailSettingsEnum.PASSWORD.getAttribute(), SauceLabsProperties.ACCESS_TOKEN.getName(), + BtsProperties.OAUTH_ACCESS_KEY.getName(), BtsProperties.API_TOKEN.getName(), + AuthProperties.MANAGER_PASSWORD.getName() + ); - private static final Predicate> IGNORE_FIELDS_CONDITION = entry -> IGNORE_FIELDS.stream() - .noneMatch(field -> field.equalsIgnoreCase(entry.getKey())); + private static final Predicate> IGNORE_FIELDS_CONDITION = + entry -> IGNORE_FIELDS.stream().noneMatch(field -> field.equalsIgnoreCase(entry.getKey())); - public static final Function TO_INTEGRATION_RESOURCE = integration -> { - IntegrationResource resource = new IntegrationResource(); - resource.setId(integration.getId()); - resource.setName(integration.getName()); - resource.setCreator(integration.getCreator()); - resource.setCreationDate(EntityUtils.TO_DATE.apply(integration.getCreationDate())); - resource.setEnabled(integration.isEnabled()); - ofNullable(integration.getProject()).ifPresent(p -> resource.setProjectId(p.getId())); - ofNullable(integration.getParams()).flatMap(IntegrationConverter::convertToResourceParams) - .ifPresent(resource::setIntegrationParams); - IntegrationTypeResource type = new IntegrationTypeResource(); - type.setId(integration.getType().getId()); - type.setName(integration.getType().getName()); - type.setEnabled(integration.getType().isEnabled()); - type.setCreationDate(EntityUtils.TO_DATE.apply(integration.getType().getCreationDate())); - type.setGroupType(integration.getType().getIntegrationGroup().name()); - ofNullable(integration.getType().getDetails()).ifPresent( - it -> type.setDetails(it.getDetails())); - ofNullable(integration.getType().getAuthFlow()).ifPresent( - it -> type.setAuthFlow(AuthFlowEnum.valueOf(it.name()))); - resource.setIntegrationType(type); + public static final Function TO_INTEGRATION_RESOURCE = + integration -> { + IntegrationResource resource = new IntegrationResource(); + resource.setId(integration.getId()); + resource.setName(integration.getName()); + resource.setCreator(integration.getCreator()); + resource.setCreationDate(EntityUtils.TO_DATE.apply(integration.getCreationDate())); + resource.setEnabled(integration.isEnabled()); + ofNullable(integration.getProject()).ifPresent(p -> resource.setProjectId(p.getId())); + ofNullable(integration.getParams()).flatMap(IntegrationConverter::convertToResourceParams) + .ifPresent(resource::setIntegrationParams); + IntegrationTypeResource type = new IntegrationTypeResource(); + type.setId(integration.getType().getId()); + type.setName(integration.getType().getName()); + type.setEnabled(integration.getType().isEnabled()); + type.setCreationDate(EntityUtils.TO_DATE.apply(integration.getType().getCreationDate())); + type.setGroupType(integration.getType().getIntegrationGroup().name()); + ofNullable(integration.getType().getDetails()).ifPresent( + it -> type.setDetails(it.getDetails())); + ofNullable(integration.getType().getAuthFlow()).ifPresent( + it -> type.setAuthFlow(AuthFlowEnum.valueOf(it.name()))); + resource.setIntegrationType(type); - return resource; - }; + return resource; + }; private static Optional> convertToResourceParams(IntegrationParams it) { - return ofNullable(it.getParams()).map(p -> p.entrySet() - .stream() - .filter(IGNORE_FIELDS_CONDITION) + return ofNullable(it.getParams()).map(p -> p.entrySet().stream().filter(IGNORE_FIELDS_CONDITION) .collect(HashMap::new, (resourceParams, entry) -> resourceParams.put(entry.getKey(), entry.getValue()), - Map::putAll)); + Map::putAll + )); } - public static final Function TO_ACTIVITY_RESOURCE = integration -> { - IntegrationActivityResource resource = new IntegrationActivityResource(); - resource.setId(integration.getId()); - resource.setName(integration.getName()); - ofNullable(integration.getProject()).ifPresent(p -> { - resource.setProjectId(p.getId()); - resource.setProjectName(p.getName()); - }); - resource.setTypeName(integration.getType().getName()); - return resource; - }; + public static final Function TO_ACTIVITY_RESOURCE = + integration -> { + IntegrationActivityResource resource = new IntegrationActivityResource(); + resource.setId(integration.getId()); + resource.setName(integration.getName()); + ofNullable(integration.getProject()).ifPresent(p -> { + resource.setProjectId(p.getId()); + resource.setProjectName(p.getName()); + }); + resource.setTypeName(integration.getType().getName()); + return resource; + }; private IntegrationConverter() { //static only diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IntegrationTypeConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IntegrationTypeConverter.java index ee68f161e9..62c2518c86 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IntegrationTypeConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IntegrationTypeConverter.java @@ -20,7 +20,7 @@ import com.epam.ta.reportportal.commons.EntityUtils; import com.epam.ta.reportportal.entity.integration.IntegrationType; -import com.epam.ta.reportportal.ws.model.integration.IntegrationTypeResource; +import com.epam.ta.reportportal.model.integration.IntegrationTypeResource; import java.util.function.Function; /** @@ -28,17 +28,18 @@ */ public final class IntegrationTypeConverter { - public static final Function TO_RESOURCE = integrationType -> { - IntegrationTypeResource resource = new IntegrationTypeResource(); - resource.setId(integrationType.getId()); - resource.setName(integrationType.getName()); - resource.setEnabled(integrationType.isEnabled()); - resource.setCreationDate(EntityUtils.TO_DATE.apply(integrationType.getCreationDate())); - resource.setGroupType(integrationType.getIntegrationGroup().name()); - ofNullable(integrationType.getDetails()).ifPresent( - it -> resource.setDetails(integrationType.getDetails().getDetails())); - return resource; - }; + public static final Function TO_RESOURCE = + integrationType -> { + IntegrationTypeResource resource = new IntegrationTypeResource(); + resource.setId(integrationType.getId()); + resource.setName(integrationType.getName()); + resource.setEnabled(integrationType.isEnabled()); + resource.setCreationDate(EntityUtils.TO_DATE.apply(integrationType.getCreationDate())); + resource.setGroupType(integrationType.getIntegrationGroup().name()); + ofNullable(integrationType.getDetails()).ifPresent( + it -> resource.setDetails(integrationType.getDetails().getDetails())); + return resource; + }; private IntegrationTypeConverter() { //static only diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IssueConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IssueConverter.java index 10bc73c11d..9cbdaa77e0 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IssueConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IssueConverter.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.entity.bts.Ticket; import com.epam.ta.reportportal.entity.item.issue.IssueEntity; -import com.epam.ta.reportportal.ws.model.issue.Issue; +import com.epam.ta.reportportal.ws.reporting.Issue; import com.google.common.base.Preconditions; import java.util.Optional; import java.util.function.Function; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IssueTypeConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IssueTypeConverter.java index 98e0423176..3e84edeb9b 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IssueTypeConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/IssueTypeConverter.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.ws.converter.converters; import com.epam.ta.reportportal.entity.item.issue.IssueType; -import com.epam.ta.reportportal.ws.model.activity.IssueTypeActivityResource; +import com.epam.ta.reportportal.model.activity.IssueTypeActivityResource; import java.util.function.Function; /** @@ -29,10 +29,11 @@ private IssueTypeConverter() { //static only } - public static final Function TO_ACTIVITY_RESOURCE = issueType -> { - IssueTypeActivityResource resource = new IssueTypeActivityResource(); - resource.setId(issueType.getId()); - resource.setLongName(issueType.getLongName()); - return resource; - }; + public static final Function TO_ACTIVITY_RESOURCE = + issueType -> { + IssueTypeActivityResource resource = new IssueTypeActivityResource(); + resource.setId(issueType.getId()); + resource.setLongName(issueType.getLongName()); + return resource; + }; } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ItemAttributeConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ItemAttributeConverter.java index e40a5524b9..1a17d6142f 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ItemAttributeConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ItemAttributeConverter.java @@ -19,9 +19,8 @@ import com.epam.ta.reportportal.entity.ItemAttribute; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributesRQ; - +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributesRQ; import java.util.function.BiFunction; import java.util.function.Function; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/LaunchConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/LaunchConverter.java index eeceb6ae92..472bd02984 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/LaunchConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/LaunchConverter.java @@ -25,12 +25,12 @@ import com.epam.ta.reportportal.dao.UserRepository; import com.epam.ta.reportportal.entity.ItemAttribute; import com.epam.ta.reportportal.entity.launch.Launch; +import com.epam.ta.reportportal.model.activity.LaunchActivityResource; import com.epam.ta.reportportal.ws.converter.resource.handler.attribute.ItemAttributeType; import com.epam.ta.reportportal.ws.converter.resource.handler.attribute.ResourceAttributeHandler; import com.epam.ta.reportportal.ws.converter.resource.handler.attribute.resolver.ItemAttributeTypeResolver; -import com.epam.ta.reportportal.ws.model.activity.LaunchActivityResource; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; -import com.epam.ta.reportportal.ws.model.launch.Mode; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; +import com.epam.ta.reportportal.ws.reporting.Mode; import com.google.common.base.Preconditions; import java.util.Collections; import java.util.Map; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/LogConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/LogConverter.java index 05a4ca0801..ba9678adeb 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/LogConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/LogConverter.java @@ -24,8 +24,8 @@ import com.epam.ta.reportportal.entity.enums.LogLevel; import com.epam.ta.reportportal.entity.log.Log; import com.epam.ta.reportportal.entity.log.LogFull; -import com.epam.ta.reportportal.ws.model.log.LogResource; -import com.epam.ta.reportportal.ws.model.log.SearchLogRs; +import com.epam.ta.reportportal.model.log.LogResource; +import com.epam.ta.reportportal.model.log.SearchLogRs; import com.google.common.base.Preconditions; import java.util.function.BiFunction; import java.util.function.Function; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/NotificationConfigConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/NotificationConfigConverter.java index f2a6feb6e3..f826e19e1a 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/NotificationConfigConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/NotificationConfigConverter.java @@ -16,100 +16,102 @@ package com.epam.ta.reportportal.ws.converter.converters; +import static java.util.Optional.ofNullable; + import com.epam.ta.reportportal.entity.enums.LogicalOperator; import com.epam.ta.reportportal.entity.enums.SendCase; import com.epam.ta.reportportal.entity.project.email.LaunchAttributeRule; import com.epam.ta.reportportal.entity.project.email.SenderCase; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import com.epam.ta.reportportal.ws.model.ValidationConstraints; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Sets; - import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; -import static java.util.Optional.ofNullable; - /** * @author Ivan Budayeu */ public final class NotificationConfigConverter { - private NotificationConfigConverter() { - //static only - } + private NotificationConfigConverter() { + //static only + } - public final static Function, List> TO_RESOURCE = senderCaseSet -> senderCaseSet.stream() - .map(NotificationConfigConverter.TO_CASE_RESOURCE) - .collect(Collectors.toList()); + public final static Function, List> TO_RESOURCE = + senderCaseSet -> senderCaseSet.stream().map(NotificationConfigConverter.TO_CASE_RESOURCE) + .collect(Collectors.toList()); - public static final Function TO_ATTRIBUTE_RULE_RESOURCE = model -> { - ItemAttributeResource attributeResource = new ItemAttributeResource(); - attributeResource.setKey(model.getKey()); - attributeResource.setValue(model.getValue()); - return attributeResource; - }; + public static final Function + TO_ATTRIBUTE_RULE_RESOURCE = model -> { + ItemAttributeResource attributeResource = new ItemAttributeResource(); + attributeResource.setKey(model.getKey()); + attributeResource.setValue(model.getValue()); + return attributeResource; + }; - public final static Function TO_CASE_RESOURCE = model -> { - Preconditions.checkNotNull(model); - SenderCaseDTO resource = new SenderCaseDTO(); - resource.setLaunchNames(Lists.newArrayList(model.getLaunchNames())); - ofNullable(model.getLaunchAttributeRules()).ifPresent(launchAttributeRules -> resource.setAttributes(launchAttributeRules.stream() - .map(TO_ATTRIBUTE_RULE_RESOURCE) - .collect(Collectors.toSet()))); - resource.setSendCase(model.getSendCase().getCaseString()); - resource.setRecipients(Lists.newArrayList(model.getRecipients())); - resource.setEnabled(model.isEnabled()); - resource.setAttributesOperator(model.getAttributesOperator().getOperator()); - resource.setRuleName(model.getRuleName()); - resource.setId(model.getId()); - return resource; - }; + public final static Function TO_CASE_RESOURCE = model -> { + Preconditions.checkNotNull(model); + SenderCaseDTO resource = new SenderCaseDTO(); + resource.setLaunchNames(Lists.newArrayList(model.getLaunchNames())); + ofNullable(model.getLaunchAttributeRules()).ifPresent( + launchAttributeRules -> resource.setAttributes( + launchAttributeRules.stream().map(TO_ATTRIBUTE_RULE_RESOURCE) + .collect(Collectors.toSet()))); + resource.setSendCase(model.getSendCase().getCaseString()); + resource.setRecipients(Lists.newArrayList(model.getRecipients())); + resource.setEnabled(model.isEnabled()); + resource.setAttributesOperator(model.getAttributesOperator().getOperator()); + resource.setRuleName(model.getRuleName()); + resource.setId(model.getId()); + return resource; + }; - public static final Function TO_ATTRIBUTE_RULE_MODEL = resource -> { - LaunchAttributeRule launchAttributeRule = new LaunchAttributeRule(); - cutAttributeToMaxLength(resource); - launchAttributeRule.setKey(resource.getKey()); - launchAttributeRule.setValue(resource.getValue()); - return launchAttributeRule; - }; + public static final Function TO_ATTRIBUTE_RULE_MODEL = + resource -> { + LaunchAttributeRule launchAttributeRule = new LaunchAttributeRule(); + cutAttributeToMaxLength(resource); + launchAttributeRule.setKey(resource.getKey()); + launchAttributeRule.setValue(resource.getValue()); + return launchAttributeRule; + }; - private static void cutAttributeToMaxLength(ItemAttributeResource entity) { - String key = entity.getKey(); - String value = entity.getValue(); - if (key != null && key.length() > ValidationConstraints.MAX_ATTRIBUTE_LENGTH) { - entity.setKey(key.trim().substring(0, ValidationConstraints.MAX_ATTRIBUTE_LENGTH)); - } - if (value != null && value.length() > ValidationConstraints.MAX_ATTRIBUTE_LENGTH) { - entity.setValue(value.trim().substring(0, ValidationConstraints.MAX_ATTRIBUTE_LENGTH)); - } - } + private static void cutAttributeToMaxLength(ItemAttributeResource entity) { + String key = entity.getKey(); + String value = entity.getValue(); + if (key != null && key.length() > ValidationConstraints.MAX_ATTRIBUTE_LENGTH) { + entity.setKey(key.trim().substring(0, ValidationConstraints.MAX_ATTRIBUTE_LENGTH)); + } + if (value != null && value.length() > ValidationConstraints.MAX_ATTRIBUTE_LENGTH) { + entity.setValue(value.trim().substring(0, ValidationConstraints.MAX_ATTRIBUTE_LENGTH)); + } + } - public final static Function TO_CASE_MODEL = resource -> { - SenderCase senderCase = new SenderCase(); - ofNullable(resource.getAttributes()).ifPresent(attributes -> senderCase.setLaunchAttributeRules(attributes.stream() - .map(attribute -> { - LaunchAttributeRule launchAttributeRule = TO_ATTRIBUTE_RULE_MODEL.apply(attribute); - launchAttributeRule.setSenderCase(senderCase); - return launchAttributeRule; - }) - .collect(Collectors.toSet()))); - ofNullable(resource.getLaunchNames()).ifPresent(launchNames -> senderCase.setLaunchNames(Sets.newHashSet(launchNames))); - senderCase.setRecipients(Sets.newHashSet(resource.getRecipients())); - senderCase.setSendCase(SendCase.findByName(resource.getSendCase()) - .orElseThrow(() -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, - "Incorrect send case type " + resource.getSendCase() - ))); - senderCase.setEnabled(resource.isEnabled()); - senderCase.setAttributesOperator(LogicalOperator.valueOf(resource.getAttributesOperator())); - senderCase.setRuleName(resource.getRuleName()); - senderCase.setId(resource.getId()); - return senderCase; - }; + public final static Function TO_CASE_MODEL = resource -> { + SenderCase senderCase = new SenderCase(); + ofNullable(resource.getAttributes()).ifPresent( + attributes -> senderCase.setLaunchAttributeRules(attributes.stream().map(attribute -> { + LaunchAttributeRule launchAttributeRule = TO_ATTRIBUTE_RULE_MODEL.apply(attribute); + launchAttributeRule.setSenderCase(senderCase); + return launchAttributeRule; + }).collect(Collectors.toSet()))); + ofNullable(resource.getLaunchNames()).ifPresent( + launchNames -> senderCase.setLaunchNames(Sets.newHashSet(launchNames))); + senderCase.setRecipients(Sets.newHashSet(resource.getRecipients())); + senderCase.setSendCase(SendCase.findByName(resource.getSendCase()).orElseThrow( + () -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR, + "Incorrect send case type " + resource.getSendCase() + ))); + senderCase.setEnabled(resource.isEnabled()); + senderCase.setAttributesOperator(LogicalOperator.valueOf(resource.getAttributesOperator())); + senderCase.setRuleName(resource.getRuleName()); + senderCase.setId(resource.getId()); + return senderCase; + }; } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ParametersConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ParametersConverter.java index b1a829e943..a5c5e7bed7 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ParametersConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ParametersConverter.java @@ -16,7 +16,7 @@ package com.epam.ta.reportportal.ws.converter.converters; import com.epam.ta.reportportal.entity.item.Parameter; -import com.epam.ta.reportportal.ws.model.ParameterResource; +import com.epam.ta.reportportal.ws.reporting.ParameterResource; import java.util.function.Function; /** diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/PatternTemplateConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/PatternTemplateConverter.java index 9c5214db63..592adcde2f 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/PatternTemplateConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/PatternTemplateConverter.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.ws.converter.converters; import com.epam.ta.reportportal.entity.pattern.PatternTemplate; -import com.epam.ta.reportportal.ws.model.activity.PatternTemplateActivityResource; -import com.epam.ta.reportportal.ws.model.project.config.pattern.PatternTemplateResource; +import com.epam.ta.reportportal.model.activity.PatternTemplateActivityResource; +import com.epam.ta.reportportal.model.project.config.pattern.PatternTemplateResource; import java.util.function.Function; /** @@ -30,18 +30,20 @@ private PatternTemplateConverter() { //static only } - public static final Function TO_RESOURCE = patternTemplate -> { - PatternTemplateResource resource = new PatternTemplateResource(); - resource.setId(patternTemplate.getId()); - resource.setType(patternTemplate.getTemplateType().name()); - resource.setName(patternTemplate.getName()); - resource.setValue(patternTemplate.getValue()); - resource.setEnabled(patternTemplate.isEnabled()); + public static final Function TO_RESOURCE = + patternTemplate -> { + PatternTemplateResource resource = new PatternTemplateResource(); + resource.setId(patternTemplate.getId()); + resource.setType(patternTemplate.getTemplateType().name()); + resource.setName(patternTemplate.getName()); + resource.setValue(patternTemplate.getValue()); + resource.setEnabled(patternTemplate.isEnabled()); - return resource; - }; + return resource; + }; - public static final Function TO_ACTIVITY_RESOURCE = patternTemplate -> { + public static final Function + TO_ACTIVITY_RESOURCE = patternTemplate -> { PatternTemplateActivityResource resource = new PatternTemplateActivityResource(); resource.setId(patternTemplate.getId()); resource.setName(patternTemplate.getName()); diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ProjectActivityConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ProjectActivityConverter.java index 6bdb4d288c..09308eb3ea 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ProjectActivityConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ProjectActivityConverter.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectUtils; -import com.epam.ta.reportportal.ws.model.activity.ProjectAttributesActivityResource; +import com.epam.ta.reportportal.model.activity.ProjectAttributesActivityResource; import java.util.function.Function; /** @@ -30,12 +30,13 @@ private ProjectActivityConverter() { //static only } - public static final Function TO_ACTIVITY_RESOURCE = project -> { - ProjectAttributesActivityResource resource = new ProjectAttributesActivityResource(); - resource.setProjectId(project.getId()); - resource.setProjectName(project.getName()); - resource.setConfig(ProjectUtils.getConfigParameters(project.getProjectAttributes())); - return resource; - }; + public static final Function TO_ACTIVITY_RESOURCE = + project -> { + ProjectAttributesActivityResource resource = new ProjectAttributesActivityResource(); + resource.setProjectId(project.getId()); + resource.setProjectName(project.getName()); + resource.setConfig(ProjectUtils.getConfigParameters(project.getProjectAttributes())); + return resource; + }; } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ProjectConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ProjectConverter.java index e54485239b..b03929c96c 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ProjectConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ProjectConverter.java @@ -16,26 +16,25 @@ package com.epam.ta.reportportal.ws.converter.converters; +import static com.epam.ta.reportportal.ws.converter.converters.ProjectSettingsConverter.TO_SUBTYPE_RESOURCE; +import static java.util.Optional.ofNullable; + import com.epam.ta.reportportal.core.analyzer.auto.indexer.IndexerStatusCache; import com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectIssueType; import com.epam.ta.reportportal.entity.project.ProjectUtils; -import com.epam.ta.reportportal.ws.model.project.ProjectConfiguration; -import com.epam.ta.reportportal.ws.model.project.ProjectResource; -import com.epam.ta.reportportal.ws.model.project.config.IssueSubTypeResource; -import com.epam.ta.reportportal.ws.model.project.email.ProjectNotificationConfigDTO; -import org.apache.commons.lang3.BooleanUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - +import com.epam.ta.reportportal.model.project.ProjectConfiguration; +import com.epam.ta.reportportal.model.project.ProjectResource; +import com.epam.ta.reportportal.model.project.config.IssueSubTypeResource; +import com.epam.ta.reportportal.model.project.email.ProjectNotificationConfigDTO; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; - -import static com.epam.ta.reportportal.ws.converter.converters.ProjectSettingsConverter.TO_SUBTYPE_RESOURCE; -import static java.util.Optional.ofNullable; +import org.apache.commons.lang3.BooleanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; /** * @author Pavel Bortnik @@ -43,69 +42,68 @@ @Service public final class ProjectConverter { - private final static String INDEXING_RUN = "analyzer.indexingRunning"; - - @Autowired - private IndexerStatusCache indexerStatusCache; - - public Function TO_PROJECT_RESOURCE = project -> { - if (project == null) { - return null; - } - - ProjectResource projectResource = new ProjectResource(); - projectResource.setProjectId(project.getId()); - projectResource.setProjectName(project.getName()); - projectResource.setEntryType(project.getProjectType().name()); - projectResource.setCreationDate(project.getCreationDate()); - projectResource.setAllocatedStorage(project.getAllocatedStorage()); - projectResource.setUsers(project.getUsers().stream().map(user -> { - ProjectResource.ProjectUser projectUser = new ProjectResource.ProjectUser(); - projectUser.setLogin(user.getUser().getLogin()); - projectUser.setProjectRole(user.getProjectRole().toString()); - return projectUser; - }).collect(Collectors.toList())); - - Map> subTypes = project.getProjectIssueTypes() - .stream() - .map(ProjectIssueType::getIssueType) - .collect(Collectors.groupingBy( - it -> it.getIssueGroup().getTestItemIssueGroup().getValue(), - Collectors.mapping(TO_SUBTYPE_RESOURCE, Collectors.toList()) - )); - - ProjectConfiguration projectConfiguration = new ProjectConfiguration(); - - Map attributes = ProjectUtils.getConfigParameters(project.getProjectAttributes()); - - attributes.put( - INDEXING_RUN, - String.valueOf(ofNullable(indexerStatusCache.getIndexingStatus().getIfPresent(project.getId())).orElse(false)) - ); - - projectConfiguration.setProjectAttributes(attributes); - - projectConfiguration.setPatterns(project.getPatternTemplates() - .stream() - .map(PatternTemplateConverter.TO_RESOURCE) - .collect(Collectors.toList())); - - projectResource.setIntegrations(project.getIntegrations() - .stream() - .map(IntegrationConverter.TO_INTEGRATION_RESOURCE) - .collect(Collectors.toList())); - - ProjectNotificationConfigDTO notificationConfig = new ProjectNotificationConfigDTO(); - notificationConfig.setEnabled(BooleanUtils.toBoolean(attributes.get(ProjectAttributeEnum.NOTIFICATIONS_ENABLED.getAttribute()))); - - ofNullable(project.getSenderCases()).ifPresent(senderCases -> notificationConfig.setSenderCases(NotificationConfigConverter.TO_RESOURCE - .apply(senderCases))); - projectConfiguration.setProjectConfig(notificationConfig); - - projectConfiguration.setSubTypes(subTypes); - - projectResource.setConfiguration(projectConfiguration); - return projectResource; - }; + private final static String INDEXING_RUN = "analyzer.indexingRunning"; + + @Autowired + private IndexerStatusCache indexerStatusCache; + + public Function TO_PROJECT_RESOURCE = project -> { + if (project == null) { + return null; + } + + ProjectResource projectResource = new ProjectResource(); + projectResource.setProjectId(project.getId()); + projectResource.setProjectName(project.getName()); + projectResource.setEntryType(project.getProjectType().name()); + projectResource.setCreationDate(project.getCreationDate()); + projectResource.setAllocatedStorage(project.getAllocatedStorage()); + projectResource.setUsers(project.getUsers().stream().map(user -> { + ProjectResource.ProjectUser projectUser = new ProjectResource.ProjectUser(); + projectUser.setLogin(user.getUser().getLogin()); + projectUser.setProjectRole(user.getProjectRole().toString()); + return projectUser; + }).collect(Collectors.toList())); + + Map> subTypes = + project.getProjectIssueTypes().stream().map(ProjectIssueType::getIssueType) + .collect(Collectors.groupingBy( + it -> it.getIssueGroup().getTestItemIssueGroup().getValue(), + Collectors.mapping(TO_SUBTYPE_RESOURCE, Collectors.toList()) + )); + + ProjectConfiguration projectConfiguration = new ProjectConfiguration(); + + Map attributes = + ProjectUtils.getConfigParameters(project.getProjectAttributes()); + + attributes.put( + INDEXING_RUN, String.valueOf( + ofNullable(indexerStatusCache.getIndexingStatus().getIfPresent(project.getId())).orElse( + false))); + + projectConfiguration.setProjectAttributes(attributes); + + projectConfiguration.setPatterns( + project.getPatternTemplates().stream().map(PatternTemplateConverter.TO_RESOURCE) + .collect(Collectors.toList())); + + projectResource.setIntegrations( + project.getIntegrations().stream().map(IntegrationConverter.TO_INTEGRATION_RESOURCE) + .collect(Collectors.toList())); + + ProjectNotificationConfigDTO notificationConfig = new ProjectNotificationConfigDTO(); + notificationConfig.setEnabled(BooleanUtils.toBoolean( + attributes.get(ProjectAttributeEnum.NOTIFICATIONS_ENABLED.getAttribute()))); + + ofNullable(project.getSenderCases()).ifPresent(senderCases -> notificationConfig.setSenderCases( + NotificationConfigConverter.TO_RESOURCE.apply(senderCases))); + projectConfiguration.setProjectConfig(notificationConfig); + + projectConfiguration.setSubTypes(subTypes); + + projectResource.setConfiguration(projectConfiguration); + return projectResource; + }; } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ProjectSettingsConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ProjectSettingsConverter.java index 66deb60f28..b3e80010bb 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ProjectSettingsConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ProjectSettingsConverter.java @@ -23,9 +23,9 @@ import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectInfo; import com.epam.ta.reportportal.entity.project.ProjectIssueType; -import com.epam.ta.reportportal.ws.model.project.ProjectInfoResource; -import com.epam.ta.reportportal.ws.model.project.config.IssueSubTypeResource; -import com.epam.ta.reportportal.ws.model.project.config.ProjectSettingsResource; +import com.epam.ta.reportportal.model.project.ProjectInfoResource; +import com.epam.ta.reportportal.model.project.config.IssueSubTypeResource; +import com.epam.ta.reportportal.model.project.config.ProjectSettingsResource; import com.google.common.base.Preconditions; import java.util.List; import java.util.Map; @@ -41,19 +41,20 @@ private ProjectSettingsConverter() { //static only } - public static final Function TO_PROJECT_INFO_RESOURCE = project -> { - Preconditions.checkNotNull(project); - ProjectInfoResource resource = new ProjectInfoResource(); - resource.setUsersQuantity(project.getUsersQuantity()); - resource.setLaunchesQuantity(project.getLaunchesQuantity()); - resource.setProjectId(project.getId()); - resource.setProjectName(project.getName()); - resource.setCreationDate(EntityUtils.TO_DATE.apply(project.getCreationDate())); - resource.setLastRun(ofNullable(project.getLastRun()).map(EntityUtils.TO_DATE).orElse(null)); - resource.setEntryType(project.getProjectType()); - resource.setOrganization(project.getOrganization()); - return resource; - }; + public static final Function TO_PROJECT_INFO_RESOURCE = + project -> { + Preconditions.checkNotNull(project); + ProjectInfoResource resource = new ProjectInfoResource(); + resource.setUsersQuantity(project.getUsersQuantity()); + resource.setLaunchesQuantity(project.getLaunchesQuantity()); + resource.setProjectId(project.getId()); + resource.setProjectName(project.getName()); + resource.setCreationDate(EntityUtils.TO_DATE.apply(project.getCreationDate())); + resource.setLastRun(ofNullable(project.getLastRun()).map(EntityUtils.TO_DATE).orElse(null)); + resource.setEntryType(project.getProjectType()); + resource.setOrganization(project.getOrganization()); + return resource; + }; public static final Function TO_SUBTYPE_RESOURCE = issueType -> { IssueSubTypeResource issueSubTypeResource = new IssueSubTypeResource(); @@ -66,21 +67,21 @@ private ProjectSettingsConverter() { return issueSubTypeResource; }; - public static final Function, Map>> TO_PROJECT_SUB_TYPES_RESOURCE = issueTypes -> issueTypes - .stream() - .collect(Collectors.groupingBy( + public static final Function, Map>> + TO_PROJECT_SUB_TYPES_RESOURCE = + issueTypes -> issueTypes.stream().collect(Collectors.groupingBy( it -> it.getIssueGroup().getTestItemIssueGroup().getValue(), Collectors.mapping(TO_SUBTYPE_RESOURCE, Collectors.toList()) )); - public static final Function TO_PROJECT_SETTINGS_RESOURCE = project -> { - ProjectSettingsResource resource = new ProjectSettingsResource(); - resource.setProjectId(project.getId()); - resource.setSubTypes(TO_PROJECT_SUB_TYPES_RESOURCE.apply(project.getProjectIssueTypes() - .stream() - .map(ProjectIssueType::getIssueType) - .collect(Collectors.toList()))); - return resource; - }; + public static final Function TO_PROJECT_SETTINGS_RESOURCE = + project -> { + ProjectSettingsResource resource = new ProjectSettingsResource(); + resource.setProjectId(project.getId()); + resource.setSubTypes(TO_PROJECT_SUB_TYPES_RESOURCE.apply( + project.getProjectIssueTypes().stream().map(ProjectIssueType::getIssueType) + .collect(Collectors.toList()))); + return resource; + }; } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/RestorePasswordBidConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/RestorePasswordBidConverter.java index ab08b88c3e..9bba77cdfb 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/RestorePasswordBidConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/RestorePasswordBidConverter.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.ws.converter.converters; import com.epam.ta.reportportal.entity.user.RestorePasswordBid; -import com.epam.ta.reportportal.ws.model.user.RestorePasswordRQ; +import com.epam.ta.reportportal.model.user.RestorePasswordRQ; import com.google.common.base.Preconditions; import java.util.UUID; import java.util.function.Function; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ServerSettingsConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ServerSettingsConverter.java index 78ecd5b7e5..5b016996b8 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ServerSettingsConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/ServerSettingsConverter.java @@ -19,7 +19,7 @@ import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect; import com.epam.ta.reportportal.entity.ServerSettings; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.Map; import java.util.function.Function; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/StatisticsConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/StatisticsConverter.java index f736e464ca..c627508750 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/StatisticsConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/StatisticsConverter.java @@ -21,7 +21,7 @@ import static java.util.Optional.ofNullable; import com.epam.ta.reportportal.entity.statistics.Statistics; -import com.epam.ta.reportportal.ws.model.statistics.StatisticsResource; +import com.epam.ta.reportportal.ws.reporting.StatisticsResource; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/TestItemConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/TestItemConverter.java index 19ec0aaabf..f41e17d8c8 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/TestItemConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/TestItemConverter.java @@ -24,13 +24,13 @@ import com.epam.ta.reportportal.entity.item.PathName; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.item.issue.IssueEntity; -import com.epam.ta.reportportal.ws.model.NestedStepResource; -import com.epam.ta.reportportal.ws.model.TestItemResource; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.item.ItemPathName; -import com.epam.ta.reportportal.ws.model.item.LaunchPathName; -import com.epam.ta.reportportal.ws.model.item.PathNameResource; +import com.epam.ta.reportportal.model.NestedStepResource; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ItemPathName; +import com.epam.ta.reportportal.ws.reporting.LaunchPathName; +import com.epam.ta.reportportal.ws.reporting.PathNameResource; +import com.epam.ta.reportportal.ws.reporting.TestItemResource; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/TicketConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/TicketConverter.java index 73052d8db0..0eaaa65bdf 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/TicketConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/TicketConverter.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.ws.converter.converters; import com.epam.ta.reportportal.entity.bts.Ticket; -import com.epam.ta.reportportal.ws.model.issue.Issue; +import com.epam.ta.reportportal.ws.reporting.Issue; import com.google.common.base.Preconditions; import java.util.function.Function; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/UserConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/UserConverter.java index bbae034468..155a42d2fa 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/UserConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/UserConverter.java @@ -20,9 +20,9 @@ import com.epam.ta.reportportal.entity.user.ProjectUser; import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserType; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; -import com.epam.ta.reportportal.ws.model.user.SearchUserResource; -import com.epam.ta.reportportal.ws.model.user.UserResource; +import com.epam.ta.reportportal.model.activity.UserActivityResource; +import com.epam.ta.reportportal.model.user.SearchUserResource; +import com.epam.ta.reportportal.model.user.UserResource; import com.google.common.collect.Lists; import java.util.Comparator; import java.util.List; @@ -37,53 +37,53 @@ */ public final class UserConverter { - private UserConverter() { - //static only - } + private UserConverter() { + //static only + } - public static final Function TO_RESOURCE = user -> { - UserResource resource = new UserResource(); - resource.setId(user.getId()); - resource.setUserId(user.getLogin()); - resource.setEmail(user.getEmail()); - resource.setPhotoId(user.getAttachment()); - resource.setFullName(user.getFullName()); - resource.setAccountType(user.getUserType().toString()); - resource.setUserRole(user.getRole().toString()); - resource.setIsLoaded(UserType.UPSA != user.getUserType()); - resource.setMetadata(user.getMetadata().getMetadata()); + public static final Function TO_RESOURCE = user -> { + UserResource resource = new UserResource(); + resource.setId(user.getId()); + resource.setUserId(user.getLogin()); + resource.setEmail(user.getEmail()); + resource.setPhotoId(user.getAttachment()); + resource.setFullName(user.getFullName()); + resource.setAccountType(user.getUserType().toString()); + resource.setUserRole(user.getRole().toString()); + resource.setIsLoaded(UserType.UPSA != user.getUserType()); + resource.setMetadata(user.getMetadata().getMetadata()); - if (null != user.getProjects()) { - List projects = Lists.newArrayList(user.getProjects()); - projects.sort(Comparator.comparing(compare -> compare.getProject().getName())); - Map userProjects = user.getProjects() - .stream() - .collect(MoreCollectors.toLinkedMap(p -> p.getProject().getName(), p -> { - UserResource.AssignedProject assignedProject = new UserResource.AssignedProject(); - assignedProject.setEntryType(p.getProject().getProjectType().name()); - assignedProject.setProjectRole(p.getProjectRole().toString()); - return assignedProject; - })); - resource.setAssignedProjects(userProjects); - } - return resource; - }; + if (null != user.getProjects()) { + List projects = Lists.newArrayList(user.getProjects()); + projects.sort(Comparator.comparing(compare -> compare.getProject().getName())); + Map userProjects = user.getProjects().stream() + .collect(MoreCollectors.toLinkedMap(p -> p.getProject().getName(), p -> { + UserResource.AssignedProject assignedProject = new UserResource.AssignedProject(); + assignedProject.setEntryType(p.getProject().getProjectType().name()); + assignedProject.setProjectRole(p.getProjectRole().toString()); + return assignedProject; + })); + resource.setAssignedProjects(userProjects); + } + return resource; + }; - public static final Function TO_SEARCH_RESOURCE = user -> { - final SearchUserResource resource = new SearchUserResource(); - resource.setId(user.getId()); - resource.setLogin(user.getLogin()); - resource.setEmail(user.getEmail()); - resource.setFullName(user.getFullName()); - return resource; - }; + public static final Function TO_SEARCH_RESOURCE = user -> { + final SearchUserResource resource = new SearchUserResource(); + resource.setId(user.getId()); + resource.setLogin(user.getLogin()); + resource.setEmail(user.getEmail()); + resource.setFullName(user.getFullName()); + return resource; + }; - public static final BiFunction TO_ACTIVITY_RESOURCE = (user, projectId) -> { - UserActivityResource resource = new UserActivityResource(); - resource.setId(user.getId()); - resource.setDefaultProjectId(projectId); - resource.setFullName(user.getLogin()); - return resource; - }; + public static final BiFunction TO_ACTIVITY_RESOURCE = + (user, projectId) -> { + UserActivityResource resource = new UserActivityResource(); + resource.setId(user.getId()); + resource.setDefaultProjectId(projectId); + resource.setFullName(user.getLogin()); + return resource; + }; } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/UserCreationBidConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/UserCreationBidConverter.java index 137353c8a4..b217522e81 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/UserCreationBidConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/UserCreationBidConverter.java @@ -19,7 +19,7 @@ import com.epam.ta.reportportal.commons.EntityUtils; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.user.UserCreationBid; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQ; +import com.epam.ta.reportportal.model.user.CreateUserRQ; import com.google.common.base.Preconditions; import java.util.UUID; import java.util.function.BiFunction; @@ -35,13 +35,14 @@ private UserCreationBidConverter() { //static only } - public static final BiFunction TO_USER = (request, project) -> { - Preconditions.checkNotNull(request); - UserCreationBid user = new UserCreationBid(); - user.setUuid(UUID.randomUUID().toString()); - user.setEmail(EntityUtils.normalizeId(request.getEmail().trim())); - user.setProjectName(project.getName()); - user.setRole(request.getRole()); - return user; - }; + public static final BiFunction TO_USER = + (request, project) -> { + Preconditions.checkNotNull(request); + UserCreationBid user = new UserCreationBid(); + user.setUuid(UUID.randomUUID().toString()); + user.setEmail(EntityUtils.normalizeId(request.getEmail().trim())); + user.setProjectName(project.getName()); + user.setRole(request.getRole()); + return user; + }; } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/UserFilterConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/UserFilterConverter.java index 199729a60d..d253088e2f 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/UserFilterConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/UserFilterConverter.java @@ -16,91 +16,94 @@ package com.epam.ta.reportportal.ws.converter.converters; +import static java.util.Optional.ofNullable; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toSet; + import com.epam.ta.reportportal.commons.querygen.FilterCondition; import com.epam.ta.reportportal.entity.filter.FilterSort; import com.epam.ta.reportportal.entity.filter.UserFilter; -import com.epam.ta.reportportal.ws.model.OwnedEntityResource; -import com.epam.ta.reportportal.ws.model.activity.UserFilterActivityResource; -import com.epam.ta.reportportal.ws.model.filter.Order; -import com.epam.ta.reportportal.ws.model.filter.UserFilterCondition; -import com.epam.ta.reportportal.ws.model.filter.UserFilterResource; - +import com.epam.ta.reportportal.model.OwnedEntityResource; +import com.epam.ta.reportportal.model.activity.UserFilterActivityResource; +import com.epam.ta.reportportal.model.filter.Order; +import com.epam.ta.reportportal.model.filter.UserFilterCondition; +import com.epam.ta.reportportal.model.filter.UserFilterResource; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; -import static java.util.Optional.ofNullable; -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toSet; - /** * @author Pavel Bortnik */ public final class UserFilterConverter { - private UserFilterConverter() { - //static only - } + private UserFilterConverter() { + //static only + } - public static final Function TO_OWNED_ENTITY_RESOURCE = filter -> { - OwnedEntityResource ownedEntity = BaseEntityConverter.TO_OWNED_ENTITY.apply(filter); - ownedEntity.setName(filter.getName()); - ownedEntity.setDescription(filter.getDescription()); - return ownedEntity; - }; + public static final Function TO_OWNED_ENTITY_RESOURCE = + filter -> { + OwnedEntityResource ownedEntity = BaseEntityConverter.TO_OWNED_ENTITY.apply(filter); + ownedEntity.setName(filter.getName()); + ownedEntity.setDescription(filter.getDescription()); + return ownedEntity; + }; - public static final Function, List> FILTER_SET_TO_FILTER_RESOURCE = filters -> filters.stream() - .map(UserFilterConverter::buildFilterResource) - .collect(Collectors.toList()); + public static final Function, List> + FILTER_SET_TO_FILTER_RESOURCE = + filters -> filters.stream().map(UserFilterConverter::buildFilterResource) + .collect(Collectors.toList()); - public static final Function TO_FILTER_RESOURCE = UserFilterConverter::buildFilterResource; + public static final Function TO_FILTER_RESOURCE = + UserFilterConverter::buildFilterResource; - public static final Function TO_ACTIVITY_RESOURCE = filter -> { - UserFilterActivityResource resource = new UserFilterActivityResource(); - resource.setId(filter.getId()); - resource.setName(filter.getName()); - resource.setDescription(filter.getDescription()); - resource.setProjectId(filter.getProject().getId()); - return resource; - }; + public static final Function TO_ACTIVITY_RESOURCE = + filter -> { + UserFilterActivityResource resource = new UserFilterActivityResource(); + resource.setId(filter.getId()); + resource.setName(filter.getName()); + resource.setDescription(filter.getDescription()); + resource.setProjectId(filter.getProject().getId()); + return resource; + }; - private static final Function TO_FILTER_CONDITION = filterCondition -> { - UserFilterCondition condition = new UserFilterCondition(); - ofNullable(filterCondition.getCondition()).ifPresent(c -> { - if (filterCondition.isNegative()) { - condition.setCondition("!".concat(c.getMarker())); - } else { - condition.setCondition(c.getMarker()); - } - }); - condition.setFilteringField(filterCondition.getSearchCriteria()); - condition.setValue(filterCondition.getValue()); + private static final Function TO_FILTER_CONDITION = + filterCondition -> { + UserFilterCondition condition = new UserFilterCondition(); + ofNullable(filterCondition.getCondition()).ifPresent(c -> { + if (filterCondition.isNegative()) { + condition.setCondition("!".concat(c.getMarker())); + } else { + condition.setCondition(c.getMarker()); + } + }); + condition.setFilteringField(filterCondition.getSearchCriteria()); + condition.setValue(filterCondition.getValue()); - return condition; - }; + return condition; + }; - private static final Function TO_FILTER_ORDER = filterSort -> { - Order order = new Order(); - order.setSortingColumnName(filterSort.getField()); - order.setIsAsc(filterSort.getDirection().isAscending()); - return order; - }; + private static final Function TO_FILTER_ORDER = filterSort -> { + Order order = new Order(); + order.setSortingColumnName(filterSort.getField()); + order.setIsAsc(filterSort.getDirection().isAscending()); + return order; + }; - private static UserFilterResource buildFilterResource(UserFilter filter) { - UserFilterResource userFilterResource = new UserFilterResource(); - userFilterResource.setFilterId(filter.getId()); - userFilterResource.setName(filter.getName()); - userFilterResource.setDescription(filter.getDescription()); - userFilterResource.setOwner(filter.getOwner()); - ofNullable(filter.getTargetClass()).ifPresent(tc -> userFilterResource.setObjectType(tc.getClassObject().getSimpleName())); - ofNullable(filter.getFilterCondition()).ifPresent(fcs -> userFilterResource.setConditions(fcs.stream() - .map(UserFilterConverter.TO_FILTER_CONDITION) - .collect(toSet()))); - ofNullable(filter.getFilterSorts()).ifPresent(fs -> userFilterResource.setOrders(fs.stream() - .map(UserFilterConverter.TO_FILTER_ORDER) - .collect(toList()))); + private static UserFilterResource buildFilterResource(UserFilter filter) { + UserFilterResource userFilterResource = new UserFilterResource(); + userFilterResource.setFilterId(filter.getId()); + userFilterResource.setName(filter.getName()); + userFilterResource.setDescription(filter.getDescription()); + userFilterResource.setOwner(filter.getOwner()); + ofNullable(filter.getTargetClass()).ifPresent( + tc -> userFilterResource.setObjectType(tc.getClassObject().getSimpleName())); + ofNullable(filter.getFilterCondition()).ifPresent(fcs -> userFilterResource.setConditions( + fcs.stream().map(UserFilterConverter.TO_FILTER_CONDITION).collect(toSet()))); + ofNullable(filter.getFilterSorts()).ifPresent(fs -> userFilterResource.setOrders( + fs.stream().map(UserFilterConverter.TO_FILTER_ORDER).collect(toList()))); - return userFilterResource; - } + return userFilterResource; + } } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/WidgetConverter.java b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/WidgetConverter.java index 87b95395e9..e96b9edab6 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/converters/WidgetConverter.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/converters/WidgetConverter.java @@ -20,12 +20,12 @@ import com.epam.ta.reportportal.entity.dashboard.DashboardWidget; import com.epam.ta.reportportal.entity.dashboard.DashboardWidgetId; import com.epam.ta.reportportal.entity.widget.Widget; -import com.epam.ta.reportportal.ws.model.Position; -import com.epam.ta.reportportal.ws.model.Size; -import com.epam.ta.reportportal.ws.model.activity.WidgetActivityResource; -import com.epam.ta.reportportal.ws.model.dashboard.DashboardResource; -import com.epam.ta.reportportal.ws.model.widget.ContentParameters; -import com.epam.ta.reportportal.ws.model.widget.WidgetResource; +import com.epam.ta.reportportal.model.Position; +import com.epam.ta.reportportal.model.Size; +import com.epam.ta.reportportal.model.activity.WidgetActivityResource; +import com.epam.ta.reportportal.model.dashboard.DashboardResource; +import com.epam.ta.reportportal.model.widget.ContentParameters; +import com.epam.ta.reportportal.model.widget.WidgetResource; import com.google.common.collect.Lists; import com.google.common.collect.Sets; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceAttributeLogger.java b/src/main/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceAttributeLogger.java index 226ebc48e9..c22d07e615 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceAttributeLogger.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceAttributeLogger.java @@ -18,7 +18,7 @@ import com.epam.ta.reportportal.entity.ItemAttribute; import com.epam.ta.reportportal.ws.converter.resource.handler.attribute.ResourceAttributeHandler; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; import java.util.Collection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceAttributeUpdater.java b/src/main/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceAttributeUpdater.java index 1ff7947d06..f52fd01f4d 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceAttributeUpdater.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceAttributeUpdater.java @@ -20,8 +20,8 @@ import com.epam.ta.reportportal.entity.ItemAttribute; import com.epam.ta.reportportal.ws.converter.resource.handler.attribute.ResourceAttributeHandler; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; import java.util.Collection; /** diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceMetadataAttributeUpdater.java b/src/main/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceMetadataAttributeUpdater.java index f33bc8d6bf..6b955d6329 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceMetadataAttributeUpdater.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceMetadataAttributeUpdater.java @@ -16,18 +16,17 @@ package com.epam.ta.reportportal.ws.converter.resource.handler.attribute.launch; +import static java.util.Optional.ofNullable; + import com.epam.ta.reportportal.entity.ItemAttribute; import com.epam.ta.reportportal.ws.converter.resource.handler.attribute.ResourceAttributeHandler; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; import com.google.common.collect.Maps; - import java.util.Collection; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; -import static java.util.Optional.ofNullable; - /** * @author Ivan Budayeu */ diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/provider/PathNameUpdaterProvider.java b/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/provider/PathNameUpdaterProvider.java index ed707962aa..5b89f5965c 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/provider/PathNameUpdaterProvider.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/provider/PathNameUpdaterProvider.java @@ -22,7 +22,7 @@ import com.epam.ta.reportportal.ws.converter.utils.ResourceUpdaterProvider; import com.epam.ta.reportportal.ws.converter.utils.item.content.TestItemUpdaterContent; import com.epam.ta.reportportal.ws.converter.utils.item.updater.PathNameUpdater; -import com.epam.ta.reportportal.ws.model.TestItemResource; +import com.epam.ta.reportportal.ws.reporting.TestItemResource; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -31,8 +31,8 @@ * @author Ivan Budayeu */ @Service -public class PathNameUpdaterProvider implements - ResourceUpdaterProvider { +public class PathNameUpdaterProvider + implements ResourceUpdaterProvider { private final TestItemRepository testItemRepository; @@ -43,8 +43,8 @@ public PathNameUpdaterProvider(TestItemRepository testItemRepository) { @Override public ResourceUpdater retrieve(TestItemUpdaterContent updaterContent) { - Map pathNamesMapping = testItemRepository.selectPathNames( - updaterContent.getTestItems()); + Map pathNamesMapping = + testItemRepository.selectPathNames(updaterContent.getTestItems()); return PathNameUpdater.of(pathNamesMapping); } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/provider/RetriesUpdaterProvider.java b/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/provider/RetriesUpdaterProvider.java index 46b8d3e11e..80194b03d2 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/provider/RetriesUpdaterProvider.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/provider/RetriesUpdaterProvider.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.ws.converter.utils.ResourceUpdaterProvider; import com.epam.ta.reportportal.ws.converter.utils.item.content.TestItemUpdaterContent; import com.epam.ta.reportportal.ws.converter.utils.item.updater.RetriesUpdater; -import com.epam.ta.reportportal.ws.model.TestItemResource; +import com.epam.ta.reportportal.ws.reporting.TestItemResource; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -35,8 +35,8 @@ * @author Ivan Budayeu */ @Service -public class RetriesUpdaterProvider implements - ResourceUpdaterProvider { +public class RetriesUpdaterProvider + implements ResourceUpdaterProvider { private final TestItemRepository testItemRepository; @@ -48,11 +48,9 @@ public RetriesUpdaterProvider(TestItemRepository testItemRepository) { @Override public ResourceUpdater retrieve(TestItemUpdaterContent updaterContent) { Map> retriesMapping = testItemRepository.selectRetries( - updaterContent.getTestItems() - .stream() - .filter(TestItem::isHasRetries) - .map(TestItem::getItemId) - .collect(Collectors.toList())).stream().collect(groupingBy(TestItem::getRetryOf)); + updaterContent.getTestItems().stream().filter(TestItem::isHasRetries) + .map(TestItem::getItemId).collect(Collectors.toList())).stream() + .collect(groupingBy(TestItem::getRetryOf)); return RetriesUpdater.of(retriesMapping); } } diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/updater/PathNameUpdater.java b/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/updater/PathNameUpdater.java index 5521cbb97c..b75c2d9dec 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/updater/PathNameUpdater.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/updater/PathNameUpdater.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.entity.item.PathName; import com.epam.ta.reportportal.ws.converter.converters.TestItemConverter; import com.epam.ta.reportportal.ws.converter.utils.ResourceUpdater; -import com.epam.ta.reportportal.ws.model.TestItemResource; +import com.epam.ta.reportportal.ws.reporting.TestItemResource; import java.util.Map; /** @@ -38,8 +38,7 @@ private PathNameUpdater(Map pathNamesMapping) { @Override public void updateResource(TestItemResource resource) { ofNullable(pathNamesMapping.get(resource.getItemId())).ifPresent( - pathName -> resource.setPathNames(TestItemConverter.PATH_NAME_TO_RESOURCE - .apply(pathName))); + pathName -> resource.setPathNames(TestItemConverter.PATH_NAME_TO_RESOURCE.apply(pathName))); } public static PathNameUpdater of(Map pathNameMapping) { diff --git a/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/updater/RetriesUpdater.java b/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/updater/RetriesUpdater.java index 5b2d2bc442..a49f998851 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/updater/RetriesUpdater.java +++ b/src/main/java/com/epam/ta/reportportal/ws/converter/utils/item/updater/RetriesUpdater.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.ws.converter.converters.TestItemConverter; import com.epam.ta.reportportal.ws.converter.utils.ResourceUpdater; -import com.epam.ta.reportportal.ws.model.TestItemResource; +import com.epam.ta.reportportal.ws.reporting.TestItemResource; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -39,10 +39,8 @@ private RetriesUpdater(Map> retriesMapping) { @Override public void updateResource(TestItemResource resource) { - ofNullable(retriesMapping.get(resource.getItemId())).ifPresent( - retries -> resource.setRetries(retries.stream() - .map(TestItemConverter.TO_RESOURCE) - .collect(Collectors.toList()))); + ofNullable(retriesMapping.get(resource.getItemId())).ifPresent(retries -> resource.setRetries( + retries.stream().map(TestItemConverter.TO_RESOURCE).collect(Collectors.toList()))); } public static RetriesUpdater of(Map> retriesMapping) { diff --git a/src/main/java/com/epam/ta/reportportal/ws/rabbit/AsyncReportingListener.java b/src/main/java/com/epam/ta/reportportal/ws/rabbit/AsyncReportingListener.java index 54e9a9bfe3..15b8c1f67d 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/rabbit/AsyncReportingListener.java +++ b/src/main/java/com/epam/ta/reportportal/ws/rabbit/AsyncReportingListener.java @@ -45,12 +45,12 @@ import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.util.ProjectExtractor; import com.epam.ta.reportportal.ws.converter.builders.LogFullBuilder; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; import com.google.common.base.Strings; import java.time.LocalDateTime; import java.time.ZoneOffset; diff --git a/src/main/java/com/epam/ta/reportportal/ws/rabbit/EmailNotificationConsumer.java b/src/main/java/com/epam/ta/reportportal/ws/rabbit/EmailNotificationConsumer.java index abb21b6c85..8281ecc548 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/rabbit/EmailNotificationConsumer.java +++ b/src/main/java/com/epam/ta/reportportal/ws/rabbit/EmailNotificationConsumer.java @@ -16,9 +16,9 @@ package com.epam.ta.reportportal.ws.rabbit; +import com.epam.ta.reportportal.model.notification.EmailNotificationRQ; import com.epam.ta.reportportal.util.email.strategy.EmailNotificationStrategy; import com.epam.ta.reportportal.util.email.strategy.EmailTemplate; -import com.epam.ta.reportportal.ws.model.notification.EmailNotificationRQ; import java.util.Map; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/main/java/com/epam/ta/reportportal/ws/resolver/FilterCriteriaResolver.java b/src/main/java/com/epam/ta/reportportal/ws/resolver/FilterCriteriaResolver.java index ae8a5a5107..479d60b431 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/resolver/FilterCriteriaResolver.java +++ b/src/main/java/com/epam/ta/reportportal/ws/resolver/FilterCriteriaResolver.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.commons.validation.Suppliers; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; diff --git a/src/main/java/com/epam/ta/reportportal/ws/resolver/PredefinedFilterCriteriaResolver.java b/src/main/java/com/epam/ta/reportportal/ws/resolver/PredefinedFilterCriteriaResolver.java index 479f56227e..7daffe5ee5 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/resolver/PredefinedFilterCriteriaResolver.java +++ b/src/main/java/com/epam/ta/reportportal/ws/resolver/PredefinedFilterCriteriaResolver.java @@ -22,7 +22,7 @@ import com.epam.ta.reportportal.commons.validation.BusinessRule; import com.epam.ta.reportportal.core.filter.predefined.PredefinedFilterType; import com.epam.ta.reportportal.core.filter.predefined.PredefinedFilters; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Collections; import java.util.List; import java.util.Optional; diff --git a/src/main/java/com/epam/ta/reportportal/ws/resolver/SortArgumentResolver.java b/src/main/java/com/epam/ta/reportportal/ws/resolver/SortArgumentResolver.java index 5841d34f05..2914a35cc8 100644 --- a/src/main/java/com/epam/ta/reportportal/ws/resolver/SortArgumentResolver.java +++ b/src/main/java/com/epam/ta/reportportal/ws/resolver/SortArgumentResolver.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.commons.querygen.CriteriaHolder; import com.epam.ta.reportportal.commons.querygen.FilterTarget; import com.epam.ta.reportportal.commons.validation.BusinessRule; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Optional; import java.util.stream.StreamSupport; import org.springframework.core.MethodParameter; diff --git a/src/main/resources/application-elastic.yaml b/src/main/resources/application-elastic.yaml index 359c09f7a8..8e7bba8cf1 100644 --- a/src/main/resources/application-elastic.yaml +++ b/src/main/resources/application-elastic.yaml @@ -1,5 +1,5 @@ rp: - elasticsearchLogmessage: + searchengine: host: elasticsearch port: 9200 username: diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 7ff12905eb..78c9b76a9a 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -55,3 +55,4 @@ com.ta.reportportal.rp.flushing.time.cron=\${rp.environment.variable.flushing.ti spring.profiles.active=\${rp.profiles:default} rp.feature.flags= +springdoc.default-produces-media-type=application/json diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 6cbd6f282e..97c7bde5c3 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -42,11 +42,9 @@ logging: org.elasticsearch.client.RestClient: error -springfox: - documentation: - swagger: - v2: - path: /v1/api-docs +springdoc: + api-docs: + path: /v1/api-docs #### Custom ReportPortal Properties ###### diff --git a/src/main/resources/image/defaultAvatar.png b/src/main/resources/image/defaultAvatar.png index b40402d891..58ccf2b47c 100644 Binary files a/src/main/resources/image/defaultAvatar.png and b/src/main/resources/image/defaultAvatar.png differ diff --git a/src/main/resources/image/defaultUserPhoto.jpg b/src/main/resources/image/defaultUserPhoto.jpg deleted file mode 100644 index eae64e3087..0000000000 Binary files a/src/main/resources/image/defaultUserPhoto.jpg and /dev/null differ diff --git a/src/test/java/com/epam/ta/reportportal/core/activityevent/impl/ActivityEventHandlerTest.java b/src/test/java/com/epam/ta/reportportal/core/activityevent/impl/ActivityEventHandlerTest.java index 3817f4c265..0f232f313b 100644 --- a/src/test/java/com/epam/ta/reportportal/core/activityevent/impl/ActivityEventHandlerTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/activityevent/impl/ActivityEventHandlerTest.java @@ -28,8 +28,8 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.ActivityEventResource; -import com.epam.ta.reportportal.ws.model.PagedResponse; +import com.epam.ta.reportportal.model.ActivityEventResource; +import com.epam.ta.reportportal.model.PagedResponse; import java.time.LocalDateTime; import java.util.List; import org.junit.jupiter.api.Test; @@ -47,7 +47,6 @@ @ExtendWith(MockitoExtension.class) class ActivityEventHandlerTest { - @Mock private ActivityRepository activityRepository; diff --git a/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerServiceServiceTest.java b/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerServiceServiceTest.java index ac87b36b49..945064603f 100644 --- a/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerServiceServiceTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerServiceServiceTest.java @@ -42,7 +42,7 @@ import com.epam.ta.reportportal.entity.item.issue.IssueType; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.entity.project.Project; -import com.epam.ta.reportportal.ws.model.analyzer.AnalyzedItemRs; +import com.epam.ta.reportportal.model.analyzer.AnalyzedItemRs; import com.epam.ta.reportportal.ws.model.analyzer.IndexLaunch; import com.epam.ta.reportportal.ws.model.analyzer.IndexLog; import com.epam.ta.reportportal.ws.model.analyzer.IndexTestItem; @@ -76,14 +76,10 @@ class AnalyzerServiceServiceTest { private AnalyzerStatusCache analyzerStatusCache = mock(AnalyzerStatusCache.class); - private AnalyzerServiceImpl issuesAnalyzer = new AnalyzerServiceImpl(100, analyzerStatusCache, - launchPreparerService, - analyzerServiceClient, - issueTypeHandler, - testItemRepository, - messageBus, - launchRepository - ); + private AnalyzerServiceImpl issuesAnalyzer = + new AnalyzerServiceImpl(100, analyzerStatusCache, launchPreparerService, + analyzerServiceClient, issueTypeHandler, testItemRepository, messageBus, launchRepository + ); @Test void hasAnalyzers() { @@ -106,14 +102,16 @@ void analyze() { indexLaunch.setLaunchId(launch.getId()); indexLaunch.setAnalyzerConfig(analyzerConfig); - final List indexTestItems = items.stream().map(AnalyzerUtils::fromTestItem) - .peek(item -> item.setLogs(errorLogs(2))).collect(Collectors.toList()); + final List indexTestItems = + items.stream().map(AnalyzerUtils::fromTestItem).peek(item -> item.setLogs(errorLogs(2))) + .collect(Collectors.toList()); indexLaunch.setTestItems(indexTestItems); when(testItemRepository.findAllById(anyList())).thenReturn(items); when(launchPreparerService.prepare(any(Launch.class), anyList(), - any(AnalyzerConfig.class))).thenReturn(Optional.of(indexLaunch)); + any(AnalyzerConfig.class) + )).thenReturn(Optional.of(indexLaunch)); when(analyzerServiceClient.analyze(any())).thenReturn(analyzedItems(itemsCount)); @@ -121,7 +119,8 @@ void analyze() { issueProductBug().getIssueType()); issuesAnalyzer.runAnalyzers(launch, - items.stream().map(TestItem::getItemId).collect(Collectors.toList()), analyzerConfig); + items.stream().map(TestItem::getItemId).collect(Collectors.toList()), analyzerConfig + ); verify(analyzerServiceClient, times(1)).analyze(any()); verify(testItemRepository, times(itemsCount)).save(any()); diff --git a/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerUtilsTest.java b/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerUtilsTest.java index 79b91877e8..3d5353068a 100644 --- a/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerUtilsTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/AnalyzerUtilsTest.java @@ -31,11 +31,11 @@ import com.epam.ta.reportportal.entity.log.LogFull; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectUtils; +import com.epam.ta.reportportal.model.analyzer.RelevantItemInfo; +import com.epam.ta.reportportal.model.project.UniqueErrorConfig; import com.epam.ta.reportportal.ws.model.analyzer.IndexLog; import com.epam.ta.reportportal.ws.model.analyzer.IndexTestItem; -import com.epam.ta.reportportal.ws.model.analyzer.RelevantItemInfo; import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; -import com.epam.ta.reportportal.ws.model.project.UniqueErrorConfig; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.Arrays; @@ -61,7 +61,8 @@ void testConverting() { assertEquals(testItem.getUniqueId(), indexTestItem.getUniqueId()); assertEquals(testItem.getStartTime(), indexTestItem.getStartTime()); assertEquals(testItem.getItemResults().getIssue().getIssueType().getLocator(), - indexTestItem.getIssueTypeLocator()); + indexTestItem.getIssueTypeLocator() + ); assertEquals(1, indexTestItem.getLogs().size()); assertFalse(indexTestItem.isAutoAnalyzed()); } @@ -79,30 +80,39 @@ void testConvertingAnalyzed() { void testAnalyzerConfig() { AnalyzerConfig config = AnalyzerUtils.getAnalyzerConfig(project()); assertEquals(String.valueOf(config.getIsAutoAnalyzerEnabled()), - ProjectAttributeEnum.AUTO_ANALYZER_ENABLED.getDefaultValue()); + ProjectAttributeEnum.AUTO_ANALYZER_ENABLED.getDefaultValue() + ); assertEquals(String.valueOf(config.getNumberOfLogLines()), - ProjectAttributeEnum.NUMBER_OF_LOG_LINES.getDefaultValue()); + ProjectAttributeEnum.NUMBER_OF_LOG_LINES.getDefaultValue() + ); assertEquals(config.getAnalyzerMode(), - ProjectAttributeEnum.AUTO_ANALYZER_MODE.getDefaultValue()); + ProjectAttributeEnum.AUTO_ANALYZER_MODE.getDefaultValue() + ); assertEquals(String.valueOf(config.getMinShouldMatch()), - ProjectAttributeEnum.MIN_SHOULD_MATCH.getDefaultValue()); + ProjectAttributeEnum.MIN_SHOULD_MATCH.getDefaultValue() + ); assertEquals(String.valueOf(config.getSearchLogsMinShouldMatch()), - ProjectAttributeEnum.SEARCH_LOGS_MIN_SHOULD_MATCH.getDefaultValue()); + ProjectAttributeEnum.SEARCH_LOGS_MIN_SHOULD_MATCH.getDefaultValue() + ); assertEquals(String.valueOf(config.isIndexingRunning()), - ProjectAttributeEnum.INDEXING_RUNNING.getDefaultValue()); + ProjectAttributeEnum.INDEXING_RUNNING.getDefaultValue() + ); assertEquals(String.valueOf(config.isAllMessagesShouldMatch()), - ProjectAttributeEnum.ALL_MESSAGES_SHOULD_MATCH.getDefaultValue()); + ProjectAttributeEnum.ALL_MESSAGES_SHOULD_MATCH.getDefaultValue() + ); } @Test void testUniqueErrorConfig() { - final Map configParameters = ProjectUtils.getConfigParameters( - project().getProjectAttributes()); + final Map configParameters = + ProjectUtils.getConfigParameters(project().getProjectAttributes()); final UniqueErrorConfig config = AnalyzerUtils.getUniqueErrorConfig(configParameters); assertEquals(ProjectAttributeEnum.AUTO_UNIQUE_ERROR_ANALYZER_ENABLED.getDefaultValue(), - String.valueOf(config.isEnabled())); + String.valueOf(config.isEnabled()) + ); assertEquals(ProjectAttributeEnum.UNIQUE_ERROR_ANALYZER_REMOVE_NUMBERS.getDefaultValue(), - String.valueOf(config.isRemoveNumbers())); + String.valueOf(config.isRemoveNumbers()) + ); } @Test @@ -171,7 +181,8 @@ public static Project project() { Attribute attribute = new Attribute(); attribute.setName(it.getAttribute()); return attribute; - }).collect(Collectors.toSet()))); + }).collect(Collectors.toSet()) + )); return project; } diff --git a/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/LogIndexerServiceTest.java b/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/LogIndexerServiceTest.java index 13439ad2e1..0e2df48050 100644 --- a/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/LogIndexerServiceTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/LogIndexerServiceTest.java @@ -42,10 +42,10 @@ import com.epam.ta.reportportal.entity.item.issue.IssueType; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.entity.log.Log; +import com.epam.ta.reportportal.model.analyzer.IndexRs; +import com.epam.ta.reportportal.model.analyzer.IndexRsIndex; +import com.epam.ta.reportportal.model.analyzer.IndexRsItem; import com.epam.ta.reportportal.ws.model.analyzer.IndexLaunch; -import com.epam.ta.reportportal.ws.model.analyzer.IndexRs; -import com.epam.ta.reportportal.ws.model.analyzer.IndexRsIndex; -import com.epam.ta.reportportal.ws.model.analyzer.IndexRsItem; import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; import java.util.ArrayList; import java.util.Collections; @@ -80,14 +80,10 @@ class LogIndexerServiceTest { private LaunchPreparerService launchPreparerService = mock(LaunchPreparerService.class); - private LogIndexerService logIndexerService = new LogIndexerService(batchLogIndexer, - taskExecutor, - launchRepository, - testItemRepository, - indexerServiceClient, - launchPreparerService, - indexerStatusCache - ); + private LogIndexerService logIndexerService = + new LogIndexerService(batchLogIndexer, taskExecutor, launchRepository, testItemRepository, + indexerServiceClient, launchPreparerService, indexerStatusCache + ); @Test void testIndexWithZeroCount() { @@ -104,9 +100,7 @@ void testIndexWithZeroCount() { void testIndexDefectsUpdate() { final Map toUpdate = Maps.newHashMap(1L, "pb001"); when(indexerServiceClient.indexDefectsUpdate(1L, toUpdate)).thenReturn(Collections.emptyList()); - logIndexerService.indexDefectsUpdate( - 1L, - new AnalyzerConfig(), + logIndexerService.indexDefectsUpdate(1L, new AnalyzerConfig(), Lists.newArrayList(createTestItem(1L, TestItemIssueGroup.PRODUCT_BUG)) ); verify(indexerServiceClient, times(1)).indexDefectsUpdate(1L, toUpdate); diff --git a/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SearchLogServiceImplTest.java b/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SearchLogServiceImplTest.java index 6472fb5151..a5499d564f 100644 --- a/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SearchLogServiceImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SearchLogServiceImplTest.java @@ -42,10 +42,10 @@ import com.epam.ta.reportportal.entity.log.LogFull; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectRole; -import com.epam.ta.reportportal.ws.model.analyzer.SearchRq; -import com.epam.ta.reportportal.ws.model.analyzer.SearchRs; -import com.epam.ta.reportportal.ws.model.log.SearchLogRq; -import com.epam.ta.reportportal.ws.model.log.SearchLogRs; +import com.epam.ta.reportportal.model.analyzer.SearchRq; +import com.epam.ta.reportportal.model.analyzer.SearchRs; +import com.epam.ta.reportportal.model.log.SearchLogRq; +import com.epam.ta.reportportal.model.log.SearchLogRs; import com.google.common.collect.Lists; import java.util.Collections; import java.util.Optional; @@ -80,18 +80,16 @@ class SearchLogServiceImplTest { private CurrentLaunchCollector currentLaunchCollector = mock(CurrentLaunchCollector.class); - private final SearchLogServiceImpl searchLogService = new SearchLogServiceImpl(projectRepository, - launchRepository, - testItemRepository, - logService, analyzerServiceClient, - searchCollectorFactory - ); + private final SearchLogServiceImpl searchLogService = + new SearchLogServiceImpl(projectRepository, launchRepository, testItemRepository, logService, + analyzerServiceClient, searchCollectorFactory + ); @Test void searchTest() { - ReportPortalUser.ProjectDetails projectDetails = new ReportPortalUser.ProjectDetails(1L, - "project", ProjectRole.PROJECT_MANAGER); + ReportPortalUser.ProjectDetails projectDetails = + new ReportPortalUser.ProjectDetails(1L, "project", ProjectRole.PROJECT_MANAGER); when(projectRepository.findById(projectDetails.getProjectId())).thenReturn( Optional.of(project)); @@ -122,9 +120,7 @@ void searchTest() { when(userFilter.getFilterCondition()).thenReturn(Collections.emptySet()); when(logService.findMessagesByLaunchIdAndItemIdAndPathAndLevelGte(launch.getId(), - testItem.getItemId(), - testItem.getPath(), - LogLevel.ERROR_INT + testItem.getItemId(), testItem.getPath(), LogLevel.ERROR_INT )).thenReturn(Lists.newArrayList("message")); SearchRs searchRs = new SearchRs(); searchRs.setLogId(1L); diff --git a/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SuggestItemServiceTest.java b/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SuggestItemServiceTest.java index 59919308c1..137c4072d1 100644 --- a/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SuggestItemServiceTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/analyzer/auto/impl/SuggestItemServiceTest.java @@ -29,7 +29,7 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; diff --git a/src/test/java/com/epam/ta/reportportal/core/analyzer/config/AnalyzerTypeTest.java b/src/test/java/com/epam/ta/reportportal/core/analyzer/config/AnalyzerTypeTest.java index a2cc3ffd12..51934db5c5 100644 --- a/src/test/java/com/epam/ta/reportportal/core/analyzer/config/AnalyzerTypeTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/analyzer/config/AnalyzerTypeTest.java @@ -21,7 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchAutoAnalysisStrategyTest.java b/src/test/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchAutoAnalysisStrategyTest.java index 1e7c6134e5..cd41b945f3 100644 --- a/src/test/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchAutoAnalysisStrategyTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchAutoAnalysisStrategyTest.java @@ -33,7 +33,7 @@ import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; -import com.epam.ta.reportportal.ws.model.launch.AnalyzeLaunchRQ; +import com.epam.ta.reportportal.model.launch.AnalyzeLaunchRQ; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.Optional; @@ -52,13 +52,10 @@ class LaunchAutoAnalysisStrategyTest { private final ProjectRepository projectRepository = mock(ProjectRepository.class); private final LaunchRepository launchRepository = mock(LaunchRepository.class); - private final LaunchAutoAnalysisStarter autoAnalysisStarter = mock( - LaunchAutoAnalysisStarter.class); - private final LaunchAutoAnalysisStrategy launchAutoAnalysisStrategy = new LaunchAutoAnalysisStrategy( - projectRepository, - launchRepository, - autoAnalysisStarter - ); + private final LaunchAutoAnalysisStarter autoAnalysisStarter = + mock(LaunchAutoAnalysisStarter.class); + private final LaunchAutoAnalysisStrategy launchAutoAnalysisStrategy = + new LaunchAutoAnalysisStrategy(projectRepository, launchRepository, autoAnalysisStarter); @Test void analyzeTest() { @@ -73,8 +70,8 @@ void analyzeTest() { when(project.getProjectAttributes()).thenReturn(Sets.newHashSet()); ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, 1L); - ReportPortalUser.ProjectDetails projectDetails = new ReportPortalUser.ProjectDetails(1L, "name", - ProjectRole.PROJECT_MANAGER); + ReportPortalUser.ProjectDetails projectDetails = + new ReportPortalUser.ProjectDetails(1L, "name", ProjectRole.PROJECT_MANAGER); AnalyzeLaunchRQ analyzeLaunchRQ = new AnalyzeLaunchRQ(); analyzeLaunchRQ.setLaunchId(1L); analyzeLaunchRQ.setAnalyzerHistoryMode("ALL"); @@ -82,8 +79,8 @@ void analyzeTest() { analyzeLaunchRQ.setAnalyzerTypeName("patternAnalyzer"); launchAutoAnalysisStrategy.analyze(analyzeLaunchRQ, projectDetails, user); - final ArgumentCaptor configArgumentCaptor = ArgumentCaptor.forClass( - StartLaunchAutoAnalysisConfig.class); + final ArgumentCaptor configArgumentCaptor = + ArgumentCaptor.forClass(StartLaunchAutoAnalysisConfig.class); verify(autoAnalysisStarter, times(1)).start(configArgumentCaptor.capture()); final StartLaunchAutoAnalysisConfig config = configArgumentCaptor.getValue(); diff --git a/src/test/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchPatternAnalysisStrategyTest.java b/src/test/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchPatternAnalysisStrategyTest.java index 7f9b432aae..632cb83968 100644 --- a/src/test/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchPatternAnalysisStrategyTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/analyzer/strategy/LaunchPatternAnalysisStrategyTest.java @@ -34,7 +34,7 @@ import com.epam.ta.reportportal.entity.project.ProjectAttribute; import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; -import com.epam.ta.reportportal.ws.model.launch.AnalyzeLaunchRQ; +import com.epam.ta.reportportal.model.launch.AnalyzeLaunchRQ; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.Optional; @@ -52,11 +52,8 @@ class LaunchPatternAnalysisStrategyTest { private final LaunchRepository launchRepository = mock(LaunchRepository.class); private final LaunchPatternAnalyzer launchPatternAnalyzer = mock(LaunchPatternAnalyzer.class); - private final LaunchPatternAnalysisStrategy launchPatternAnalysisStrategy = new LaunchPatternAnalysisStrategy( - projectRepository, - launchRepository, - launchPatternAnalyzer - ); + private final LaunchPatternAnalysisStrategy launchPatternAnalysisStrategy = + new LaunchPatternAnalysisStrategy(projectRepository, launchRepository, launchPatternAnalyzer); @Test void analyzeTest() { @@ -74,8 +71,8 @@ void analyzeTest() { when(project.getProjectAttributes()).thenReturn(Sets.newHashSet(projectAttribute)); ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, 1L); - ReportPortalUser.ProjectDetails projectDetails = new ReportPortalUser.ProjectDetails(1L, "name", - ProjectRole.PROJECT_MANAGER); + ReportPortalUser.ProjectDetails projectDetails = + new ReportPortalUser.ProjectDetails(1L, "name", ProjectRole.PROJECT_MANAGER); AnalyzeLaunchRQ analyzeLaunchRQ = new AnalyzeLaunchRQ(); analyzeLaunchRQ.setLaunchId(1L); analyzeLaunchRQ.setAnalyzeItemsModes(Lists.newArrayList("TO_INVESTIGATE")); @@ -83,7 +80,8 @@ void analyzeTest() { launchPatternAnalysisStrategy.analyze(analyzeLaunchRQ, projectDetails, user); verify(launchPatternAnalyzer, times(1)).analyzeLaunch(launch, - Sets.newHashSet(AnalyzeItemsMode.TO_INVESTIGATE)); + Sets.newHashSet(AnalyzeItemsMode.TO_INVESTIGATE) + ); } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/core/dashboard/impl/CreateDashboardHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/dashboard/impl/CreateDashboardHandlerImplTest.java index 398175001f..f15009ac20 100644 --- a/src/test/java/com/epam/ta/reportportal/core/dashboard/impl/CreateDashboardHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/dashboard/impl/CreateDashboardHandlerImplTest.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.dashboard.CreateDashboardRQ; +import com.epam.ta.reportportal.model.dashboard.CreateDashboardRQ; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -55,12 +55,13 @@ void createAlreadyExistDashboard() { when(dashboardRepository.existsByNameAndOwnerAndProjectId("exist", "owner", 1L)).thenReturn( true); - final ReportPortalException exception = assertThrows( - ReportPortalException.class, + final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.createDashboard(extractProjectDetails(rpUser, "test_project"), - createDashboardRQ, rpUser) + createDashboardRQ, rpUser + ) ); assertEquals("Resource 'exist' already exists. You couldn't create the duplicate.", - exception.getMessage()); + exception.getMessage() + ); } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/core/events/activity/DashboardEventsTest.java b/src/test/java/com/epam/ta/reportportal/core/events/activity/DashboardEventsTest.java index 52283792b2..6aa148add8 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/activity/DashboardEventsTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/activity/DashboardEventsTest.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.DashboardActivityResource; +import com.epam.ta.reportportal.model.activity.DashboardActivityResource; import com.google.common.collect.Lists; import java.time.LocalDateTime; import java.util.List; diff --git a/src/test/java/com/epam/ta/reportportal/core/events/activity/DefectTypeEventsTest.java b/src/test/java/com/epam/ta/reportportal/core/events/activity/DefectTypeEventsTest.java index 5cd9fb18b5..c1d540e64c 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/activity/DefectTypeEventsTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/activity/DefectTypeEventsTest.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.IssueTypeActivityResource; +import com.epam.ta.reportportal.model.activity.IssueTypeActivityResource; import java.time.LocalDateTime; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/epam/ta/reportportal/core/events/activity/FilterEventsTest.java b/src/test/java/com/epam/ta/reportportal/core/events/activity/FilterEventsTest.java index 493741d3e1..65f47e4de4 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/activity/FilterEventsTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/activity/FilterEventsTest.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.UserFilterActivityResource; +import com.epam.ta.reportportal.model.activity.UserFilterActivityResource; import com.google.common.collect.Lists; import java.time.LocalDateTime; import java.util.List; @@ -59,8 +59,8 @@ private static Activity getExpectedActivity(EventAction action, String name) { @Test void created() { final String name = "name"; - final Activity actual = new FilterCreatedEvent(getUserFilter(name, true, "description"), 1L, - "user").toActivity(); + final Activity actual = + new FilterCreatedEvent(getUserFilter(name, true, "description"), 1L, "user").toActivity(); final Activity expected = getExpectedActivity(EventAction.CREATE, name); checkActivity(expected, actual); } @@ -68,8 +68,8 @@ void created() { @Test void deleted() { final String name = "name"; - final Activity actual = new FilterDeletedEvent(getUserFilter(name, true, "description"), 1L, - "user").toActivity(); + final Activity actual = + new FilterDeletedEvent(getUserFilter(name, true, "description"), 1L, "user").toActivity(); final Activity expected = getExpectedActivity(EventAction.DELETE, name); checkActivity(expected, actual); } @@ -92,24 +92,20 @@ void updated() { final String newName = "newName"; final boolean newShared = true; final String newDescription = "newDescription"; - final Activity actual = new FilterUpdatedEvent( - getUserFilter(oldName, oldShared, oldDescription), - getUserFilter(newName, newShared, newDescription), - 1L, - "user" - ).toActivity(); + final Activity actual = + new FilterUpdatedEvent(getUserFilter(oldName, oldShared, oldDescription), + getUserFilter(newName, newShared, newDescription), 1L, "user" + ).toActivity(); final Activity expected = getExpectedActivity(EventAction.UPDATE, newName); - expected.getDetails() - .setHistory(getExpectedHistory(Pair.of(oldName, newName), - Pair.of(oldShared, newShared), + expected.getDetails().setHistory( + getExpectedHistory(Pair.of(oldName, newName), Pair.of(oldShared, newShared), Pair.of(oldDescription, newDescription) )); checkActivity(expected, actual); } private static List getExpectedHistory(Pair name, - Pair shared, - Pair description) { + Pair shared, Pair description) { return Lists.newArrayList(HistoryField.of(NAME, name.getLeft(), name.getRight()), HistoryField.of(DESCRIPTION, description.getLeft(), description.getRight()) ); diff --git a/src/test/java/com/epam/ta/reportportal/core/events/activity/IntegrationEventsTest.java b/src/test/java/com/epam/ta/reportportal/core/events/activity/IntegrationEventsTest.java index 046630effa..3204b433f1 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/activity/IntegrationEventsTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/activity/IntegrationEventsTest.java @@ -26,7 +26,7 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.IntegrationActivityResource; +import com.epam.ta.reportportal.model.activity.IntegrationActivityResource; import java.time.LocalDateTime; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/epam/ta/reportportal/core/events/activity/ItemIssueTypeDefinedEventTest.java b/src/test/java/com/epam/ta/reportportal/core/events/activity/ItemIssueTypeDefinedEventTest.java index ba8892aa28..db53da19ef 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/activity/ItemIssueTypeDefinedEventTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/activity/ItemIssueTypeDefinedEventTest.java @@ -28,7 +28,7 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; import com.google.common.collect.Lists; import java.time.LocalDateTime; import java.util.List; @@ -49,16 +49,15 @@ void toActivity() { final String newDescription = "newDescription"; final String newName = "newName"; - final Activity actual = new ItemIssueTypeDefinedEvent( - getTestItem(oldName, oldDescription, oldIgnoreAnalyzer), - getTestItem(newName, newDescription, newIgnoreAnalyzer), 1L, "user" - ).toActivity(); + final Activity actual = + new ItemIssueTypeDefinedEvent(getTestItem(oldName, oldDescription, oldIgnoreAnalyzer), + getTestItem(newName, newDescription, newIgnoreAnalyzer), 1L, "user" + ).toActivity(); final Activity expected = getExpectedActivity(); - expected.getDetails().setHistory(getExpectedHistory( - Pair.of(oldDescription, newDescription), - Pair.of(oldName, newName), - Pair.of(String.valueOf(oldIgnoreAnalyzer), String.valueOf(newIgnoreAnalyzer)) - )); + expected.getDetails().setHistory( + getExpectedHistory(Pair.of(oldDescription, newDescription), Pair.of(oldName, newName), + Pair.of(String.valueOf(oldIgnoreAnalyzer), String.valueOf(newIgnoreAnalyzer)) + )); checkActivity(expected, actual); } @@ -95,8 +94,7 @@ private static Activity getExpectedActivity() { } private static List getExpectedHistory(Pair description, - Pair issueType, - Pair ignoreAnalyzer) { + Pair issueType, Pair ignoreAnalyzer) { return Lists.newArrayList( HistoryField.of(COMMENT, description.getLeft(), description.getRight()), HistoryField.of(ISSUE_TYPE, issueType.getLeft(), issueType.getRight()), diff --git a/src/test/java/com/epam/ta/reportportal/core/events/activity/LaunchEventsTest.java b/src/test/java/com/epam/ta/reportportal/core/events/activity/LaunchEventsTest.java index d64974813b..b30af4e455 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/activity/LaunchEventsTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/activity/LaunchEventsTest.java @@ -26,7 +26,7 @@ import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.enums.LaunchModeEnum; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.activity.LaunchActivityResource; +import com.epam.ta.reportportal.model.activity.LaunchActivityResource; import java.time.LocalDateTime; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/epam/ta/reportportal/core/events/activity/LinkTicketEventTest.java b/src/test/java/com/epam/ta/reportportal/core/events/activity/LinkTicketEventTest.java index de5182454e..a27197bbd6 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/activity/LinkTicketEventTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/activity/LinkTicketEventTest.java @@ -26,7 +26,7 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; import com.google.common.collect.Lists; import java.time.LocalDateTime; import org.junit.jupiter.api.Test; @@ -36,7 +36,8 @@ */ class LinkTicketEventTest { - private static final String EXISTED_TICKETS = "1:http:/example.com/ticket/1,2:http:/example.com/ticket/2"; + private static final String EXISTED_TICKETS = + "1:http:/example.com/ticket/1,2:http:/example.com/ticket/2"; private static final String LINKED_TICKET = "125:http:/example.com/ticket/125"; private static Activity getExpectedActivity() { @@ -73,12 +74,8 @@ private static TestItemActivityResource getTestItem(String tickets) { @Test void toActivity() { - final Activity actual = new LinkTicketEvent( - getTestItem(EXISTED_TICKETS), - getTestItem(EXISTED_TICKETS + "," + LINKED_TICKET), - 1L, - "user", - false + final Activity actual = new LinkTicketEvent(getTestItem(EXISTED_TICKETS), + getTestItem(EXISTED_TICKETS + "," + LINKED_TICKET), 1L, "user", false ).toActivity(); final Activity expected = getExpectedActivity(); checkActivity(expected, actual); diff --git a/src/test/java/com/epam/ta/reportportal/core/events/activity/PatternTemplateEventsTest.java b/src/test/java/com/epam/ta/reportportal/core/events/activity/PatternTemplateEventsTest.java index 2da851a021..d7c0464699 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/activity/PatternTemplateEventsTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/activity/PatternTemplateEventsTest.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.PatternTemplateActivityResource; +import com.epam.ta.reportportal.model.activity.PatternTemplateActivityResource; import com.google.common.collect.Lists; import java.time.LocalDateTime; import java.util.List; diff --git a/src/test/java/com/epam/ta/reportportal/core/events/activity/ProjectConfigEventTest.java b/src/test/java/com/epam/ta/reportportal/core/events/activity/ProjectConfigEventTest.java index 0cbb37c3f9..6afd0f1282 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/activity/ProjectConfigEventTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/activity/ProjectConfigEventTest.java @@ -26,7 +26,7 @@ import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; import com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum; -import com.epam.ta.reportportal.ws.model.activity.ProjectAttributesActivityResource; +import com.epam.ta.reportportal.model.activity.ProjectAttributesActivityResource; import com.google.common.collect.Lists; import java.time.LocalDateTime; import java.util.HashMap; @@ -68,29 +68,19 @@ private static Activity getExpectedActivity(EventAction action) { @Test void analyzerConfigUpdate() { - final Activity actual = new ProjectAnalyzerConfigEvent( - getProjectAttributes(getAnalyzerConfig(ANALYZER_MODE.getLeft(), - MIN_SHOULD_MATCH.getLeft(), - NUMBER_OF_LOG_LINES.getLeft(), - AUTO_ANALYZED_ENABLED.getLeft(), + final Activity actual = new ProjectAnalyzerConfigEvent(getProjectAttributes( + getAnalyzerConfig(ANALYZER_MODE.getLeft(), MIN_SHOULD_MATCH.getLeft(), + NUMBER_OF_LOG_LINES.getLeft(), AUTO_ANALYZED_ENABLED.getLeft(), ALL_MESSAGES_SHOULD_MATCH.getLeft() - )), - getProjectAttributes(getAnalyzerConfig(ANALYZER_MODE.getRight(), - MIN_SHOULD_MATCH.getRight(), - NUMBER_OF_LOG_LINES.getRight(), - AUTO_ANALYZED_ENABLED.getRight(), + )), getProjectAttributes( + getAnalyzerConfig(ANALYZER_MODE.getRight(), MIN_SHOULD_MATCH.getRight(), + NUMBER_OF_LOG_LINES.getRight(), AUTO_ANALYZED_ENABLED.getRight(), ALL_MESSAGES_SHOULD_MATCH.getRight() - )), - 1L, - "user" - ).toActivity(); + )), 1L, "user").toActivity(); final Activity expected = getExpectedActivity(EventAction.UPDATE); - expected.getDetails() - .setHistory(getAnalyzerConfigHistory(ANALYZER_MODE, - MIN_SHOULD_MATCH, - NUMBER_OF_LOG_LINES, - AUTO_ANALYZED_ENABLED, - ALL_MESSAGES_SHOULD_MATCH + expected.getDetails().setHistory( + getAnalyzerConfigHistory(ANALYZER_MODE, MIN_SHOULD_MATCH, NUMBER_OF_LOG_LINES, + AUTO_ANALYZED_ENABLED, ALL_MESSAGES_SHOULD_MATCH )); expected.setEventName("updateAnalyzer"); checkActivity(expected, actual); @@ -106,15 +96,15 @@ private static ProjectAttributesActivityResource getProjectAttributes( } private static Map getAnalyzerConfig(String analyzerMode, String minShouldMatch, - String numberOfLogs, - String autoAnalyzerEnabled, String allMessagesShouldMatch) { + String numberOfLogs, String autoAnalyzerEnabled, String allMessagesShouldMatch) { HashMap result = new HashMap<>(); result.put(ProjectAttributeEnum.AUTO_ANALYZER_MODE.getAttribute(), analyzerMode); result.put(ProjectAttributeEnum.MIN_SHOULD_MATCH.getAttribute(), minShouldMatch); result.put(ProjectAttributeEnum.NUMBER_OF_LOG_LINES.getAttribute(), numberOfLogs); result.put(ProjectAttributeEnum.AUTO_ANALYZER_ENABLED.getAttribute(), autoAnalyzerEnabled); result.put(ProjectAttributeEnum.ALL_MESSAGES_SHOULD_MATCH.getAttribute(), - allMessagesShouldMatch); + allMessagesShouldMatch + ); return result; } @@ -129,16 +119,12 @@ private static Map getProjectConfig(String keepLogs, String keep @Test void projectConfigUpdate() { - final Activity actual = new ProjectUpdatedEvent( - getProjectAttributes(getProjectConfig(KEEP_LOGS.getLeft(), - KEEP_SCREENSHOTS.getLeft(), + final Activity actual = new ProjectUpdatedEvent(getProjectAttributes( + getProjectConfig(KEEP_LOGS.getLeft(), KEEP_SCREENSHOTS.getLeft(), INTERRUPT_JOB_TIME.getLeft() - )), - getProjectAttributes(getProjectConfig(KEEP_LOGS.getRight(), KEEP_SCREENSHOTS.getRight(), - INTERRUPT_JOB_TIME.getRight())), - 1L, - "user" - ).toActivity(); + )), getProjectAttributes(getProjectConfig(KEEP_LOGS.getRight(), KEEP_SCREENSHOTS.getRight(), + INTERRUPT_JOB_TIME.getRight() + )), 1L, "user").toActivity(); final Activity expected = getExpectedActivity(EventAction.UPDATE); expected.setPriority(EventPriority.HIGH); expected.getDetails() @@ -149,44 +135,32 @@ void projectConfigUpdate() { } private static List getAnalyzerConfigHistory(Pair analyzerMode, - Pair minShouldMatch, - Pair numberOfLogsLines, Pair autoAnalyzed, - Pair allMessagesShouldMatch) { + Pair minShouldMatch, Pair numberOfLogsLines, + Pair autoAnalyzed, Pair allMessagesShouldMatch) { return Lists.newArrayList( HistoryField.of(ProjectAttributeEnum.AUTO_ANALYZER_MODE.getAttribute(), - analyzerMode.getLeft(), - analyzerMode.getRight() - ), - HistoryField.of(ProjectAttributeEnum.MIN_SHOULD_MATCH.getAttribute(), - minShouldMatch.getLeft(), minShouldMatch.getRight()), - HistoryField.of(ProjectAttributeEnum.NUMBER_OF_LOG_LINES.getAttribute(), - numberOfLogsLines.getLeft(), - numberOfLogsLines.getRight() - ), - HistoryField.of(ProjectAttributeEnum.AUTO_ANALYZER_ENABLED.getAttribute(), - autoAnalyzed.getLeft(), autoAnalyzed.getRight()), - HistoryField.of(ProjectAttributeEnum.ALL_MESSAGES_SHOULD_MATCH.getAttribute(), - allMessagesShouldMatch.getLeft(), - allMessagesShouldMatch.getRight() - ) - ); + analyzerMode.getLeft(), analyzerMode.getRight() + ), HistoryField.of(ProjectAttributeEnum.MIN_SHOULD_MATCH.getAttribute(), + minShouldMatch.getLeft(), minShouldMatch.getRight() + ), HistoryField.of(ProjectAttributeEnum.NUMBER_OF_LOG_LINES.getAttribute(), + numberOfLogsLines.getLeft(), numberOfLogsLines.getRight() + ), HistoryField.of(ProjectAttributeEnum.AUTO_ANALYZER_ENABLED.getAttribute(), + autoAnalyzed.getLeft(), autoAnalyzed.getRight() + ), HistoryField.of(ProjectAttributeEnum.ALL_MESSAGES_SHOULD_MATCH.getAttribute(), + allMessagesShouldMatch.getLeft(), allMessagesShouldMatch.getRight() + )); } private static List getProjectConfigHistory(Pair keepLogs, - Pair keepScreenshots, - Pair interruptJobTime) { + Pair keepScreenshots, Pair interruptJobTime) { return Lists.newArrayList( HistoryField.of(ProjectAttributeEnum.KEEP_LOGS.getAttribute(), keepLogs.getLeft(), - keepLogs.getRight()), - HistoryField.of(ProjectAttributeEnum.KEEP_SCREENSHOTS.getAttribute(), - keepScreenshots.getLeft(), - keepScreenshots.getRight() - ), - HistoryField.of(ProjectAttributeEnum.INTERRUPT_JOB_TIME.getAttribute(), - interruptJobTime.getLeft(), - interruptJobTime.getRight() - ) - ); + keepLogs.getRight() + ), HistoryField.of(ProjectAttributeEnum.KEEP_SCREENSHOTS.getAttribute(), + keepScreenshots.getLeft(), keepScreenshots.getRight() + ), HistoryField.of(ProjectAttributeEnum.INTERRUPT_JOB_TIME.getAttribute(), + interruptJobTime.getLeft(), interruptJobTime.getRight() + )); } } diff --git a/src/test/java/com/epam/ta/reportportal/core/events/activity/TestItemStatusChangedEventTest.java b/src/test/java/com/epam/ta/reportportal/core/events/activity/TestItemStatusChangedEventTest.java index ee9ce03d43..74f60652f3 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/activity/TestItemStatusChangedEventTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/activity/TestItemStatusChangedEventTest.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; import com.google.common.collect.Lists; import java.time.LocalDateTime; import java.util.List; @@ -75,11 +75,10 @@ void toActivity() { final String beforeStatus = "PASSED"; final String afterStatus = "FAILED"; - final Activity actual = new TestItemStatusChangedEvent(getTestItem(beforeStatus), - getTestItem(afterStatus), - 1L, - "user" - ).toActivity(); + final Activity actual = + new TestItemStatusChangedEvent(getTestItem(beforeStatus), getTestItem(afterStatus), 1L, + "user" + ).toActivity(); final Activity expected = getExpectedActivity(); expected.getDetails().setHistory(getExpectedHistory(Pair.of(beforeStatus, afterStatus))); checkActivity(expected, actual); diff --git a/src/test/java/com/epam/ta/reportportal/core/events/activity/TicketPostedEventTest.java b/src/test/java/com/epam/ta/reportportal/core/events/activity/TicketPostedEventTest.java index fd8522f4c2..0aed1a8461 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/activity/TicketPostedEventTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/activity/TicketPostedEventTest.java @@ -26,7 +26,7 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; import com.epam.ta.reportportal.ws.model.externalsystem.Ticket; import com.google.common.collect.Lists; import java.time.LocalDateTime; @@ -39,7 +39,8 @@ */ class TicketPostedEventTest { - private static final String EXISTED_TICKETS = "1:http:/example.com/ticket/1,2:http:/example.com/ticket/2"; + private static final String EXISTED_TICKETS = + "1:http:/example.com/ticket/1,2:http:/example.com/ticket/2"; private static final String NEW_TICKET_ID = "125"; private static final String NEW_TICKET_URL = "http:/example.com/ticket/125"; @@ -57,9 +58,8 @@ private static Activity getExpectedActivity() { activity.setCreatedAt(LocalDateTime.now()); activity.setObjectName("name"); activity.setDetails(new ActivityDetails()); - activity.getDetails() - .setHistory(getExpectedHistory(Pair.of(EXISTED_TICKETS, - EXISTED_TICKETS + "," + NEW_TICKET_ID + ":" + NEW_TICKET_URL))); + activity.getDetails().setHistory(getExpectedHistory( + Pair.of(EXISTED_TICKETS, EXISTED_TICKETS + "," + NEW_TICKET_ID + ":" + NEW_TICKET_URL))); return activity; } @@ -88,8 +88,8 @@ private static TestItemActivityResource getTestItem() { @Test void toActivity() { - final Activity actual = new TicketPostedEvent(getTicket(), 1L, "user", - getTestItem()).toActivity(); + final Activity actual = + new TicketPostedEvent(getTicket(), 1L, "user", getTestItem()).toActivity(); final Activity expected = getExpectedActivity(); checkActivity(expected, actual); } diff --git a/src/test/java/com/epam/ta/reportportal/core/events/activity/UserCreatedEventTest.java b/src/test/java/com/epam/ta/reportportal/core/events/activity/UserCreatedEventTest.java index 8467597593..0a684f841a 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/activity/UserCreatedEventTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/activity/UserCreatedEventTest.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.entity.activity.EventObject; import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; +import com.epam.ta.reportportal.model.activity.UserActivityResource; import java.time.LocalDateTime; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/epam/ta/reportportal/core/events/activity/WidgetEventsTest.java b/src/test/java/com/epam/ta/reportportal/core/events/activity/WidgetEventsTest.java index d84f9d2bba..b5d117deb0 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/activity/WidgetEventsTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/activity/WidgetEventsTest.java @@ -30,7 +30,7 @@ import com.epam.ta.reportportal.entity.activity.EventPriority; import com.epam.ta.reportportal.entity.activity.EventSubject; import com.epam.ta.reportportal.entity.activity.HistoryField; -import com.epam.ta.reportportal.ws.model.activity.WidgetActivityResource; +import com.epam.ta.reportportal.model.activity.WidgetActivityResource; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.time.LocalDateTime; @@ -62,82 +62,80 @@ private static Activity getExpectedActivity(EventAction action, String name) { } private static List getExpectedHistory(Pair name, - Pair shared, - Pair description, Pair itemsCount, - Pair, Set> contentFields, + Pair shared, Pair description, + Pair itemsCount, Pair, Set> contentFields, Pair options) { return Lists.newArrayList(HistoryField.of(NAME, name.getLeft(), name.getRight()), HistoryField.of(DESCRIPTION, description.getLeft(), description.getRight()), HistoryField.of(ITEMS_COUNT, itemsCount.getLeft().toString(), - itemsCount.getRight().toString()), - HistoryField.of(CONTENT_FIELDS, String.join(", ", contentFields.getLeft()), - String.join(", ", contentFields.getRight())), - HistoryField.of(WIDGET_OPTIONS, options.getLeft(), options.getRight()) + itemsCount.getRight().toString() + ), HistoryField.of(CONTENT_FIELDS, String.join(", ", contentFields.getLeft()), + String.join(", ", contentFields.getRight()) + ), HistoryField.of(WIDGET_OPTIONS, options.getLeft(), options.getRight()) ); - } + } - @Test - void created() { + @Test + void created() { final String name = "name"; final boolean shared = true; final String description = "description"; - final Activity actual = new WidgetCreatedEvent( - getWidget(name, shared, description, 2, getBeforeContentFields()), - 1L, - "user" - ).toActivity(); + final Activity actual = + new WidgetCreatedEvent(getWidget(name, shared, description, 2, getBeforeContentFields()), + 1L, "user" + ).toActivity(); final Activity expected = getExpectedActivity(EventAction.CREATE, name); expected.setEventName("createWidget"); checkActivity(expected, actual); } - private static WidgetActivityResource getWidget(String name, boolean shared, String description, int itemsCount, - Set contentFields) { - WidgetActivityResource widget = new WidgetActivityResource(); - widget.setName(name); - widget.setId(2L); - widget.setDescription(description); - widget.setProjectId(3L); - widget.setItemsCount(itemsCount); - widget.setContentFields(contentFields); - return widget; - } - - private static Set getBeforeContentFields() { - return Sets.newHashSet("field1", "field2", "field3"); - } - - private static Set getAfterContentFields() { - return Sets.newHashSet("field1", "field4", "field5", "field6"); - } - - private static String getBeforeOptions() { - return "{ \"option1\": \"content\", \"option2\": \"enabled\"}"; - } - - private static String getAfterOptions() { - return "{\n" + " \"option1\": \"content\",\n" + " \"option5\": \"disabled\",\n" + " \"superOption\": \"superContent\"\n" + "}"; - } - - @Test - void deleted() { + private static WidgetActivityResource getWidget(String name, boolean shared, String description, + int itemsCount, Set contentFields) { + WidgetActivityResource widget = new WidgetActivityResource(); + widget.setName(name); + widget.setId(2L); + widget.setDescription(description); + widget.setProjectId(3L); + widget.setItemsCount(itemsCount); + widget.setContentFields(contentFields); + return widget; + } + + private static Set getBeforeContentFields() { + return Sets.newHashSet("field1", "field2", "field3"); + } + + private static Set getAfterContentFields() { + return Sets.newHashSet("field1", "field4", "field5", "field6"); + } + + private static String getBeforeOptions() { + return "{ \"option1\": \"content\", \"option2\": \"enabled\"}"; + } + + private static String getAfterOptions() { + return "{\n" + " \"option1\": \"content\",\n" + " \"option5\": \"disabled\",\n" + + " \"superOption\": \"superContent\"\n" + "}"; + } + + @Test + void deleted() { final String name = "name"; final boolean shared = true; final String description = "description"; - final Activity actual = new WidgetDeletedEvent( - getWidget(name, shared, description, 3, getBeforeContentFields()), - 1L, - "user" - ).toActivity(); + final Activity actual = + new WidgetDeletedEvent(getWidget(name, shared, description, 3, getBeforeContentFields()), + 1L, "user" + ).toActivity(); final Activity expected = getExpectedActivity(EventAction.DELETE, name); expected.setEventName("deleteWidget"); checkActivity(expected, actual); } - @Test - void update() { + @Test + void update() { final String oldName = "oldName"; final boolean oldShared = false; final String oldDescription = "oldDescription"; @@ -148,15 +146,12 @@ void update() { final Activity actual = new WidgetUpdatedEvent( getWidget(oldName, oldShared, oldDescription, 2, getBeforeContentFields()), getWidget(newName, newShared, newDescription, 4, getAfterContentFields()), - getBeforeOptions(), - getAfterOptions(), 1L, "user" + getBeforeOptions(), getAfterOptions(), 1L, "user" ).toActivity(); final Activity expected = getExpectedActivity(EventAction.UPDATE, newName); - expected.getDetails() - .setHistory(getExpectedHistory(Pair.of(oldName, newName), - Pair.of(oldShared, newShared), - Pair.of(oldDescription, newDescription), - Pair.of(2, 4), + expected.getDetails().setHistory( + getExpectedHistory(Pair.of(oldName, newName), Pair.of(oldShared, newShared), + Pair.of(oldDescription, newDescription), Pair.of(2, 4), Pair.of(getBeforeContentFields(), getAfterContentFields()), Pair.of(getBeforeOptions(), getAfterOptions()) )); diff --git a/src/test/java/com/epam/ta/reportportal/core/events/handler/DefectTypeDeletedHandlerTest.java b/src/test/java/com/epam/ta/reportportal/core/events/handler/DefectTypeDeletedHandlerTest.java index e8dbcf8f22..3b5e2832da 100644 --- a/src/test/java/com/epam/ta/reportportal/core/events/handler/DefectTypeDeletedHandlerTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/events/handler/DefectTypeDeletedHandlerTest.java @@ -35,7 +35,7 @@ import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectAttribute; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.activity.IssueTypeActivityResource; +import com.epam.ta.reportportal.model.activity.IssueTypeActivityResource; import com.epam.ta.reportportal.ws.model.project.AnalyzerConfig; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; @@ -79,14 +79,13 @@ void deleteSubTypeOnNotExistProject() { when(projectRepository.findById(projectId)).thenReturn(Optional.empty()); - ReportPortalException exception = assertThrows( - ReportPortalException.class, - () -> handler.handleDefectTypeDeleted( - new DefectTypeDeletedEvent(new IssueTypeActivityResource(), 1L, "user", projectId)) - ); + ReportPortalException exception = + assertThrows(ReportPortalException.class, () -> handler.handleDefectTypeDeleted( + new DefectTypeDeletedEvent(new IssueTypeActivityResource(), 1L, "user", projectId))); assertEquals("Project '2' not found. Did you use correct project name?", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -113,13 +112,12 @@ void analysisAlreadyRunningTest() { when(analyzerStatusCache.getAnalyzeStatus(AnalyzerStatusCache.AUTO_ANALYZER_KEY)).thenReturn( Optional.of(cache)); - ReportPortalException exception = assertThrows( - ReportPortalException.class, - () -> handler.handleDefectTypeDeleted( - new DefectTypeDeletedEvent(new IssueTypeActivityResource(), 1L, "user", projectId)) - ); + ReportPortalException exception = + assertThrows(ReportPortalException.class, () -> handler.handleDefectTypeDeleted( + new DefectTypeDeletedEvent(new IssueTypeActivityResource(), 1L, "user", projectId))); assertEquals("Forbidden operation. Index can not be removed until auto-analysis proceeds.", - exception.getMessage()); + exception.getMessage() + ); } @Test diff --git a/src/test/java/com/epam/ta/reportportal/core/filter/impl/SearchCriteriaServiceTest.java b/src/test/java/com/epam/ta/reportportal/core/filter/impl/SearchCriteriaServiceTest.java index f9c68f6424..d3c10c44f1 100644 --- a/src/test/java/com/epam/ta/reportportal/core/filter/impl/SearchCriteriaServiceTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/filter/impl/SearchCriteriaServiceTest.java @@ -29,9 +29,8 @@ import com.epam.ta.reportportal.core.filter.predefined.PredefinedFilterType; import com.epam.ta.reportportal.entity.activity.Activity; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.SearchCriteria; -import com.epam.ta.reportportal.ws.model.SearchCriteriaRQ; -import java.util.List; +import com.epam.ta.reportportal.model.SearchCriteria; +import com.epam.ta.reportportal.model.SearchCriteriaRQ; import java.util.Set; import org.apache.commons.collections4.CollectionUtils; import org.junit.jupiter.api.Assertions; @@ -54,7 +53,8 @@ void setUp() { @Test void testCreateFilterBySearchCriteria_noCriteria() { Queryable filter = searchCriteriaService.createFilterBySearchCriteria(searchCriteriaRQ, target, - PredefinedFilterType.ACTIVITIES); + PredefinedFilterType.ACTIVITIES + ); assertTrue(filter instanceof Filter); assertTrue(CollectionUtils.isEmpty(filter.getFilterConditions())); @@ -63,14 +63,15 @@ void testCreateFilterBySearchCriteria_noCriteria() { @Test void testCreateFilterBySearchCriteria_criteriaWithoutPredefinedFilter() { - Set criteriaList = Set.of( - new SearchCriteria("sampleKey1", "EQ", "sampleValue1"), - new SearchCriteria("sampleKey2", "IN", "sampleValue2") - ); + Set criteriaList = + Set.of(new SearchCriteria("sampleKey1", "EQ", "sampleValue1"), + new SearchCriteria("sampleKey2", "IN", "sampleValue2") + ); searchCriteriaRQ.setCriteriaList(criteriaList); Queryable filter = searchCriteriaService.createFilterBySearchCriteria(searchCriteriaRQ, target, - PredefinedFilterType.ACTIVITIES); + PredefinedFilterType.ACTIVITIES + ); assertTrue(filter instanceof Filter); assertEquals(2, filter.getFilterConditions().size()); @@ -78,14 +79,15 @@ void testCreateFilterBySearchCriteria_criteriaWithoutPredefinedFilter() { @Test void testCreateFilterBySearchCriteria_criteriaWithPredefinedFilter() { - Set criteriaList = Set.of( - new SearchCriteria("predefinedFilter", null, "predefinedValue"), - new SearchCriteria("sampleKey3", "EQ", "sampleValue3") - ); + Set criteriaList = + Set.of(new SearchCriteria("predefinedFilter", null, "predefinedValue"), + new SearchCriteria("sampleKey3", "EQ", "sampleValue3") + ); searchCriteriaRQ.setCriteriaList(criteriaList); Queryable filter = searchCriteriaService.createFilterBySearchCriteria(searchCriteriaRQ, target, - PredefinedFilterType.ACTIVITIES); + PredefinedFilterType.ACTIVITIES + ); assertTrue(filter instanceof CompositeFilter); assertEquals(6, filter.getFilterConditions().size()); @@ -93,26 +95,26 @@ void testCreateFilterBySearchCriteria_criteriaWithPredefinedFilter() { @Test void testCreateFilterBySearchCriteria_wrongOperation_throwException() { - Set criteriaList = Set.of( - new SearchCriteria("sampleKey1", "WRONG", "sampleValue1") - ); + Set criteriaList = + Set.of(new SearchCriteria("sampleKey1", "WRONG", "sampleValue1")); searchCriteriaRQ.setCriteriaList(criteriaList); Assertions.assertThrows(ReportPortalException.class, () -> searchCriteriaService.createFilterBySearchCriteria(searchCriteriaRQ, target, - PredefinedFilterType.ACTIVITIES)); + PredefinedFilterType.ACTIVITIES + ) + ); } @Test void testNormalizeValueSpaces() { - Set criteriaList = Set.of( - new SearchCriteria("predefinedFilter", "CNT", "sample Value1") - ); + Set criteriaList = + Set.of(new SearchCriteria("predefinedFilter", "CNT", "sample Value1")); searchCriteriaRQ.setCriteriaList(criteriaList); - Queryable filter = searchCriteriaService.createFilterBySearchCriteria( - searchCriteriaRQ, target, - PredefinedFilterType.ACTIVITIES); + Queryable filter = searchCriteriaService.createFilterBySearchCriteria(searchCriteriaRQ, target, + PredefinedFilterType.ACTIVITIES + ); filter.getFilterConditions().forEach(cnd -> { FilterCondition condition = (FilterCondition) cnd; diff --git a/src/test/java/com/epam/ta/reportportal/core/filter/impl/UpdateUserFilterHandlerTest.java b/src/test/java/com/epam/ta/reportportal/core/filter/impl/UpdateUserFilterHandlerTest.java index 5be7ec2523..7cb063e0bd 100644 --- a/src/test/java/com/epam/ta/reportportal/core/filter/impl/UpdateUserFilterHandlerTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/filter/impl/UpdateUserFilterHandlerTest.java @@ -16,12 +16,21 @@ package com.epam.ta.reportportal.core.filter.impl; +import static com.epam.ta.reportportal.ReportPortalUserUtil.getRpUser; +import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_NAME; +import static com.epam.ta.reportportal.util.TestProjectExtractor.extractProjectDetails; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.validation.Suppliers; import com.epam.ta.reportportal.core.events.ActivityEvent; import com.epam.ta.reportportal.core.events.MessageBus; import com.epam.ta.reportportal.core.filter.UpdateUserFilterHandler; -import com.epam.ta.reportportal.dao.ProjectRepository; import com.epam.ta.reportportal.dao.ProjectUserRepository; import com.epam.ta.reportportal.dao.UserFilterRepository; import com.epam.ta.reportportal.dao.WidgetRepository; @@ -30,156 +39,152 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.filter.Order; +import com.epam.ta.reportportal.model.filter.UpdateUserFilterRQ; +import com.epam.ta.reportportal.model.filter.UserFilterCondition; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.filter.Order; -import com.epam.ta.reportportal.ws.model.filter.UpdateUserFilterRQ; -import com.epam.ta.reportportal.ws.model.filter.UserFilterCondition; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import org.junit.jupiter.api.Test; - import java.util.Optional; - -import static com.epam.ta.reportportal.ReportPortalUserUtil.getRpUser; -import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_NAME; -import static com.epam.ta.reportportal.util.TestProjectExtractor.extractProjectDetails; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; +import org.junit.jupiter.api.Test; /** * @author Ivan Budayeu */ class UpdateUserFilterHandlerTest { - public static final String SAME_NAME = "name"; - public static final String ANOTHER_NAME = "another name"; + public static final String SAME_NAME = "name"; + public static final String ANOTHER_NAME = "another name"; - private UserFilter userFilter = mock(UserFilter.class); + private UserFilter userFilter = mock(UserFilter.class); - private Project project = mock(Project.class); + private Project project = mock(Project.class); - private ProjectUserRepository projectUserRepository = mock(ProjectUserRepository.class); + private ProjectUserRepository projectUserRepository = mock(ProjectUserRepository.class); - private ProjectExtractor projectExtractor = new ProjectExtractor(projectUserRepository); + private ProjectExtractor projectExtractor = new ProjectExtractor(projectUserRepository); - private UserFilterRepository userFilterRepository = mock(UserFilterRepository.class); + private UserFilterRepository userFilterRepository = mock(UserFilterRepository.class); - private WidgetRepository widgetRepository = mock(WidgetRepository.class); + private WidgetRepository widgetRepository = mock(WidgetRepository.class); - private MessageBus messageBus = mock(MessageBus.class); + private MessageBus messageBus = mock(MessageBus.class); - private UpdateUserFilterHandler updateUserFilterHandler = new UpdateUserFilterHandlerImpl(projectExtractor, - userFilterRepository, - messageBus - ); + private UpdateUserFilterHandler updateUserFilterHandler = + new UpdateUserFilterHandlerImpl(projectExtractor, userFilterRepository, messageBus); - @Test - void updateUserFilterWithTheSameName() { + @Test + void updateUserFilterWithTheSameName() { - final ReportPortalUser rpUser = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, 1L); + final ReportPortalUser rpUser = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, 1L); - UpdateUserFilterRQ updateUserFilterRQ = getUpdateRequest(SAME_NAME); + UpdateUserFilterRQ updateUserFilterRQ = getUpdateRequest(SAME_NAME); - ReportPortalUser.ProjectDetails projectDetails = extractProjectDetails(rpUser, "test_project"); - when(userFilterRepository.findByIdAndProjectId(1L, projectDetails.getProjectId())).thenReturn(Optional.of(userFilter)); + ReportPortalUser.ProjectDetails projectDetails = extractProjectDetails(rpUser, "test_project"); + when(userFilterRepository.findByIdAndProjectId(1L, projectDetails.getProjectId())).thenReturn( + Optional.of(userFilter)); - when(userFilter.getId()).thenReturn(1L); - when(userFilter.getName()).thenReturn(SAME_NAME); - when(userFilter.getProject()).thenReturn(project); - when(project.getId()).thenReturn(1L); + when(userFilter.getId()).thenReturn(1L); + when(userFilter.getName()).thenReturn(SAME_NAME); + when(userFilter.getProject()).thenReturn(project); + when(project.getId()).thenReturn(1L); - doNothing().when(messageBus).publishActivity(any(ActivityEvent.class)); + doNothing().when(messageBus).publishActivity(any(ActivityEvent.class)); - OperationCompletionRS operationCompletionRS = updateUserFilterHandler.updateUserFilter(1L, - updateUserFilterRQ, - projectDetails, - rpUser - ); + OperationCompletionRS operationCompletionRS = + updateUserFilterHandler.updateUserFilter(1L, updateUserFilterRQ, projectDetails, rpUser); - assertEquals("User filter with ID = '" + userFilter.getId() + "' successfully updated.", operationCompletionRS.getResultMessage()); - } + assertEquals( + "User filter with ID = '" + userFilter.getId() + "' successfully updated.", + operationCompletionRS.getResultMessage() + ); + } - @Test - void updateUserFilterWithAnotherNamePositive() { + @Test + void updateUserFilterWithAnotherNamePositive() { - final ReportPortalUser rpUser = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, 1L); + final ReportPortalUser rpUser = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, 1L); - UpdateUserFilterRQ updateUserFilterRQ = getUpdateRequest(ANOTHER_NAME); + UpdateUserFilterRQ updateUserFilterRQ = getUpdateRequest(ANOTHER_NAME); - ReportPortalUser.ProjectDetails projectDetails = extractProjectDetails(rpUser, "test_project"); - when(userFilterRepository.findByIdAndProjectId(1L, projectDetails.getProjectId())).thenReturn(Optional.of(userFilter)); + ReportPortalUser.ProjectDetails projectDetails = extractProjectDetails(rpUser, "test_project"); + when(userFilterRepository.findByIdAndProjectId(1L, projectDetails.getProjectId())).thenReturn( + Optional.of(userFilter)); - when(userFilter.getId()).thenReturn(1L); - when(userFilter.getName()).thenReturn(SAME_NAME); - when(userFilter.getProject()).thenReturn(project); - when(project.getId()).thenReturn(1L); + when(userFilter.getId()).thenReturn(1L); + when(userFilter.getName()).thenReturn(SAME_NAME); + when(userFilter.getProject()).thenReturn(project); + when(project.getId()).thenReturn(1L); - when(userFilterRepository.existsByNameAndOwnerAndProjectId(updateUserFilterRQ.getName(), "user", 1L)).thenReturn(Boolean.FALSE); + when(userFilterRepository.existsByNameAndOwnerAndProjectId(updateUserFilterRQ.getName(), "user", + 1L + )).thenReturn(Boolean.FALSE); - doNothing().when(messageBus).publishActivity(any(ActivityEvent.class)); + doNothing().when(messageBus).publishActivity(any(ActivityEvent.class)); - OperationCompletionRS operationCompletionRS = updateUserFilterHandler.updateUserFilter(1L, - updateUserFilterRQ, - projectDetails, - rpUser - ); + OperationCompletionRS operationCompletionRS = + updateUserFilterHandler.updateUserFilter(1L, updateUserFilterRQ, projectDetails, rpUser); - assertEquals("User filter with ID = '" + userFilter.getId() + "' successfully updated.", operationCompletionRS.getResultMessage()); - } + assertEquals( + "User filter with ID = '" + userFilter.getId() + "' successfully updated.", + operationCompletionRS.getResultMessage() + ); + } - @Test - void updateUserFilterWithAnotherNameNegative() { + @Test + void updateUserFilterWithAnotherNameNegative() { - final ReportPortalUser rpUser = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, 1L); + final ReportPortalUser rpUser = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, 1L); - UpdateUserFilterRQ updateUserFilterRQ = getUpdateRequest(ANOTHER_NAME); + UpdateUserFilterRQ updateUserFilterRQ = getUpdateRequest(ANOTHER_NAME); - ReportPortalUser.ProjectDetails projectDetails = extractProjectDetails(rpUser, "test_project"); - when(userFilterRepository.findByIdAndProjectId(1L, projectDetails.getProjectId())).thenReturn(Optional.of(userFilter)); + ReportPortalUser.ProjectDetails projectDetails = extractProjectDetails(rpUser, "test_project"); + when(userFilterRepository.findByIdAndProjectId(1L, projectDetails.getProjectId())).thenReturn( + Optional.of(userFilter)); - when(userFilter.getId()).thenReturn(1L); - when(userFilter.getName()).thenReturn(SAME_NAME); - when(userFilter.getProject()).thenReturn(project); - when(userFilter.getOwner()).thenReturn("user"); - when(project.getId()).thenReturn(1L); + when(userFilter.getId()).thenReturn(1L); + when(userFilter.getName()).thenReturn(SAME_NAME); + when(userFilter.getProject()).thenReturn(project); + when(userFilter.getOwner()).thenReturn("user"); + when(project.getId()).thenReturn(1L); - when(userFilterRepository.existsByNameAndOwnerAndProjectId(updateUserFilterRQ.getName(), - userFilter.getOwner(), - projectDetails.getProjectId() - )).thenReturn(Boolean.TRUE); + when(userFilterRepository.existsByNameAndOwnerAndProjectId(updateUserFilterRQ.getName(), + userFilter.getOwner(), projectDetails.getProjectId() + )).thenReturn(Boolean.TRUE); - doNothing().when(messageBus).publishActivity(any(ActivityEvent.class)); + doNothing().when(messageBus).publishActivity(any(ActivityEvent.class)); - final ReportPortalException exception = assertThrows(ReportPortalException.class, - () -> updateUserFilterHandler.updateUserFilter(1L, updateUserFilterRQ, projectDetails, rpUser) - ); - assertEquals(Suppliers.formattedSupplier( - "User filter with name '{}' already exists for user '{}' under the project '{}'. You couldn't create the duplicate.", - ANOTHER_NAME, - "user", - projectDetails.getProjectName() - ).get(), exception.getMessage()); - } + final ReportPortalException exception = assertThrows(ReportPortalException.class, + () -> updateUserFilterHandler.updateUserFilter(1L, updateUserFilterRQ, projectDetails, + rpUser + ) + ); + assertEquals(Suppliers.formattedSupplier( + "User filter with name '{}' already exists for user '{}' under the project '{}'. You couldn't create the duplicate.", + ANOTHER_NAME, "user", projectDetails.getProjectName() + ).get(), exception.getMessage()); + } - private UpdateUserFilterRQ getUpdateRequest(String name) { + private UpdateUserFilterRQ getUpdateRequest(String name) { - UpdateUserFilterRQ updateUserFilterRQ = new UpdateUserFilterRQ(); + UpdateUserFilterRQ updateUserFilterRQ = new UpdateUserFilterRQ(); - updateUserFilterRQ.setName(name); - updateUserFilterRQ.setObjectType("Launch"); + updateUserFilterRQ.setName(name); + updateUserFilterRQ.setObjectType("Launch"); - Order order = new Order(); - order.setIsAsc(true); - order.setSortingColumnName(CRITERIA_NAME); - updateUserFilterRQ.setOrders(Lists.newArrayList(order)); + Order order = new Order(); + order.setIsAsc(true); + order.setSortingColumnName(CRITERIA_NAME); + updateUserFilterRQ.setOrders(Lists.newArrayList(order)); - UserFilterCondition condition = new UserFilterCondition(CRITERIA_NAME, "cnt", "we"); - updateUserFilterRQ.setConditions(Sets.newHashSet(condition)); + UserFilterCondition condition = new UserFilterCondition(CRITERIA_NAME, "cnt", "we"); + updateUserFilterRQ.setConditions(Sets.newHashSet(condition)); - return updateUserFilterRQ; - } + return updateUserFilterRQ; + } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/core/imprt/ImportLaunchHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/imprt/ImportLaunchHandlerImplTest.java index d7a2014334..573e748cc5 100644 --- a/src/test/java/com/epam/ta/reportportal/core/imprt/ImportLaunchHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/imprt/ImportLaunchHandlerImplTest.java @@ -16,10 +16,10 @@ import com.epam.ta.reportportal.core.imprt.impl.XmlImportStrategy; import com.epam.ta.reportportal.dao.LaunchRepository; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.LaunchImportCompletionRS; +import com.epam.ta.reportportal.model.launch.LaunchImportRQ; import com.epam.ta.reportportal.util.sample.LaunchSampleUtil; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.LaunchImportCompletionRS; -import com.epam.ta.reportportal.ws.model.launch.LaunchImportRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.io.File; import java.util.Optional; import org.apache.commons.io.FilenameUtils; @@ -154,9 +154,7 @@ public void whenImportLaunch_AndFileIsValid_ThenCallImportLaunch() { when(launchRepository.findByUuid(LAUNCH_ID)).thenReturn(Optional.of(sampleLaunch)); var response = (LaunchImportCompletionRS) importLaunchHandlerImpl.importLaunch(projectDetails, - reportPortalUser, FORMAT, - multipartFile, - BASE_URL, rq + reportPortalUser, FORMAT, multipartFile, BASE_URL, rq ); assertEquals(sampleLaunch.getUuid(), response.getData().getId()); diff --git a/src/test/java/com/epam/ta/reportportal/core/imprt/XmlImportStrategyTest.java b/src/test/java/com/epam/ta/reportportal/core/imprt/XmlImportStrategyTest.java index 8dc2699d08..2816753695 100644 --- a/src/test/java/com/epam/ta/reportportal/core/imprt/XmlImportStrategyTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/imprt/XmlImportStrategyTest.java @@ -16,9 +16,9 @@ import com.epam.ta.reportportal.core.launch.StartLaunchHandler; import com.epam.ta.reportportal.dao.LaunchRepository; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributesRQ; -import com.epam.ta.reportportal.ws.model.launch.LaunchImportRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRS; +import com.epam.ta.reportportal.model.launch.LaunchImportRQ; +import com.epam.ta.reportportal.ws.reporting.ItemAttributesRQ; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRS; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -26,6 +26,7 @@ import java.nio.file.Path; import java.time.Instant; import java.util.Date; +import java.util.HashSet; import java.util.Optional; import java.util.Set; import javax.inject.Provider; @@ -106,7 +107,12 @@ void whenImportLaunch_thenProcessXmlFile(@TempDir Path tempDir) throws Exception void whenImportLaunch_andIsSkippedIssue_thenProcessXmlFileWithSkippedTrue(@TempDir Path tempDir) throws Exception { LaunchImportRQ rq = new LaunchImportRQ(); - rq.setAttributes(Set.of(new ItemAttributesRQ(AbstractImportStrategy.SKIPPED_IS_NOT_ISSUE, "true"))); + ItemAttributesRQ attributesRQ = + new ItemAttributesRQ(AbstractImportStrategy.SKIPPED_IS_NOT_ISSUE, "true"); + attributesRQ.setSystem(true); + Set attributes = new HashSet<>(); + attributes.add(attributesRQ); + rq.setAttributes(attributes); File xmlFile = createFile(tempDir); @@ -136,7 +142,7 @@ void whenImportLaunch_andIsSkippedIssue_thenProcessXmlFileWithSkippedTrue(@TempD verify(xmlParseJobProvider, times(1)).get(); } - private File createFile(Path tempDir) throws Exception{ + private File createFile(Path tempDir) throws Exception { File xmlFile = tempDir.resolve("sample.xml").toFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(xmlFile)); writer.write(""); diff --git a/src/test/java/com/epam/ta/reportportal/core/imprt/impl/junit/XunitImportHandlerTest.java b/src/test/java/com/epam/ta/reportportal/core/imprt/impl/junit/XunitImportHandlerTest.java index 8434eef739..b924c32c7f 100644 --- a/src/test/java/com/epam/ta/reportportal/core/imprt/impl/junit/XunitImportHandlerTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/imprt/impl/junit/XunitImportHandlerTest.java @@ -14,9 +14,9 @@ import com.epam.ta.reportportal.core.log.CreateLogHandler; import com.epam.ta.reportportal.entity.enums.LogLevel; import com.epam.ta.reportportal.entity.enums.TestItemTypeEnum; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.item.ItemCreatedRS; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.ItemCreatedRS; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -99,6 +99,7 @@ public void whenStartElement_andQnameIsTestSuite_andItemUuidsAreEmpty_andStartTi Attributes attributes = mock(Attributes.class); when(attributes.getValue(XunitReportTag.ATTR_NAME.getValue())).thenReturn(ATTR_NAME); when(attributes.getValue(XunitReportTag.TIMESTAMP.getValue())).thenReturn(TIMESTAMP); + when(attributes.getValue(XunitReportTag.START_TIME.getValue())).thenReturn(TIMESTAMP); LocalDateTime startSuiteTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(suiteTimestamp)), @@ -136,6 +137,7 @@ public void whenStartElement_andQnameIsTestSuite_andItemUuidsAreEmpty_andStartTi Attributes attributes = mock(Attributes.class); when(attributes.getValue(XunitReportTag.ATTR_NAME.getValue())).thenReturn(ATTR_NAME); when(attributes.getValue(XunitReportTag.TIMESTAMP.getValue())).thenReturn(ISO_DATE); + when(attributes.getValue(XunitReportTag.START_TIME.getValue())).thenReturn(ISO_DATE); DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendOptional(DateTimeFormatter.RFC_1123_DATE_TIME) @@ -212,6 +214,7 @@ public void whenStartElement_andQnameIsTestCase_thenStartStepItem() { Attributes attributes = mock(Attributes.class); when(attributes.getValue(XunitReportTag.ATTR_NAME.getValue())).thenReturn(ATTR_NAME); when(attributes.getValue(XunitReportTag.START_TIME.getValue())).thenReturn(TIMESTAMP); + when(attributes.getValue(XunitReportTag.TIMESTAMP.getValue())).thenReturn(TIMESTAMP); when(attributes.getValue(XunitReportTag.ATTR_TIME.getValue())).thenReturn(DURATION); LocalDateTime startItemTime = diff --git a/src/test/java/com/epam/ta/reportportal/core/integration/impl/DeleteIntegrationHandlerTest.java b/src/test/java/com/epam/ta/reportportal/core/integration/impl/DeleteIntegrationHandlerTest.java index 37bd0e11a9..80d9e58e2e 100644 --- a/src/test/java/com/epam/ta/reportportal/core/integration/impl/DeleteIntegrationHandlerTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/integration/impl/DeleteIntegrationHandlerTest.java @@ -28,7 +28,7 @@ import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.common.collect.Lists; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/epam/ta/reportportal/core/integration/impl/GetIntegrationHandlerTest.java b/src/test/java/com/epam/ta/reportportal/core/integration/impl/GetIntegrationHandlerTest.java index 0f4dead3bf..0c7669068f 100644 --- a/src/test/java/com/epam/ta/reportportal/core/integration/impl/GetIntegrationHandlerTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/integration/impl/GetIntegrationHandlerTest.java @@ -31,7 +31,7 @@ import com.epam.ta.reportportal.dao.IntegrationTypeRepository; import com.epam.ta.reportportal.dao.ProjectRepository; import com.epam.ta.reportportal.entity.project.Project; -import com.epam.ta.reportportal.ws.model.integration.IntegrationResource; +import com.epam.ta.reportportal.model.integration.IntegrationResource; import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.Test; @@ -44,20 +44,17 @@ class GetIntegrationHandlerTest { private final Map integrationServiceMapming = mock(Map.class); private final IntegrationService basicIntegrationService = mock(IntegrationService.class); private final IntegrationRepository integrationRepository = mock(IntegrationRepository.class); - private final IntegrationTypeRepository integrationTypeRepository = mock( - IntegrationTypeRepository.class); + private final IntegrationTypeRepository integrationTypeRepository = + mock(IntegrationTypeRepository.class); private final ProjectRepository projectRepository = mock(ProjectRepository.class); - private final GetBugTrackingSystemHandler getBugTrackingSystemHandler = mock( - GetBugTrackingSystemHandler.class); - - private final GetIntegrationHandler getIntegrationHandler = new GetIntegrationHandlerImpl( - integrationServiceMapming, - basicIntegrationService, - integrationRepository, - integrationTypeRepository, - projectRepository, - getBugTrackingSystemHandler - ); + private final GetBugTrackingSystemHandler getBugTrackingSystemHandler = + mock(GetBugTrackingSystemHandler.class); + + private final GetIntegrationHandler getIntegrationHandler = + new GetIntegrationHandlerImpl(integrationServiceMapming, basicIntegrationService, + integrationRepository, integrationTypeRepository, projectRepository, + getBugTrackingSystemHandler + ); @Test void getProjectIntegrationById() { @@ -71,15 +68,11 @@ void getProjectIntegrationById() { when(projectRepository.findByName(TEST_PROJECT_NAME)).thenReturn(Optional.of(project)); - when(integrationRepository.findByIdAndProjectId(emailIntegrationId, - projectId - )).thenReturn(Optional.of(IntegrationTestUtil.getProjectEmailIntegration( - emailIntegrationId, - projectId - ))); + when(integrationRepository.findByIdAndProjectId(emailIntegrationId, projectId)).thenReturn( + Optional.of(IntegrationTestUtil.getProjectEmailIntegration(emailIntegrationId, projectId))); - IntegrationResource integrationResource = getIntegrationHandler.getProjectIntegrationById( - emailIntegrationId, TEST_PROJECT_NAME); + IntegrationResource integrationResource = + getIntegrationHandler.getProjectIntegrationById(emailIntegrationId, TEST_PROJECT_NAME); assertNotNull(integrationResource); assertEquals(emailIntegrationId, (long) integrationResource.getId()); @@ -95,11 +88,10 @@ void getGlobalIntegrationById() { final long emailIntegrationId = 1L; when(integrationRepository.findGlobalById(emailIntegrationId)).thenReturn( - Optional.of(IntegrationTestUtil.getGlobalEmailIntegration( - emailIntegrationId))); + Optional.of(IntegrationTestUtil.getGlobalEmailIntegration(emailIntegrationId))); - IntegrationResource integrationResource = getIntegrationHandler.getGlobalIntegrationById( - emailIntegrationId); + IntegrationResource integrationResource = + getIntegrationHandler.getGlobalIntegrationById(emailIntegrationId); assertNotNull(integrationResource); assertEquals("superadmin", integrationResource.getCreator()); diff --git a/src/test/java/com/epam/ta/reportportal/core/integration/plugin/impl/CreatePluginHandlerTest.java b/src/test/java/com/epam/ta/reportportal/core/integration/plugin/impl/CreatePluginHandlerTest.java index 90094643b9..1afa7baed9 100644 --- a/src/test/java/com/epam/ta/reportportal/core/integration/plugin/impl/CreatePluginHandlerTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/integration/plugin/impl/CreatePluginHandlerTest.java @@ -32,7 +32,7 @@ import com.epam.ta.reportportal.core.integration.plugin.CreatePluginHandler; import com.epam.ta.reportportal.core.plugin.Pf4jPluginBox; import com.epam.ta.reportportal.core.plugin.PluginInfo; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.EntryCreatedRS; import java.io.IOException; import java.io.InputStream; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/epam/ta/reportportal/core/integration/plugin/impl/UpdatePluginHandlerTest.java b/src/test/java/com/epam/ta/reportportal/core/integration/plugin/impl/UpdatePluginHandlerTest.java index 40be242554..e4fc36f9e4 100644 --- a/src/test/java/com/epam/ta/reportportal/core/integration/plugin/impl/UpdatePluginHandlerTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/integration/plugin/impl/UpdatePluginHandlerTest.java @@ -38,8 +38,8 @@ import com.epam.ta.reportportal.entity.integration.IntegrationType; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.filesystem.DataStore; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.integration.UpdatePluginStateRQ; +import com.epam.ta.reportportal.model.integration.UpdatePluginStateRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.io.File; import java.io.FileInputStream; import java.io.IOException; diff --git a/src/test/java/com/epam/ta/reportportal/core/item/impl/DeleteTestItemHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/item/impl/DeleteTestItemHandlerImplTest.java index c5ec0b630e..b8297c7f21 100644 --- a/src/test/java/com/epam/ta/reportportal/core/item/impl/DeleteTestItemHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/item/impl/DeleteTestItemHandlerImplTest.java @@ -43,7 +43,7 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.util.Collection; import java.util.Optional; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerAsyncImplTest.java b/src/test/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerAsyncImplTest.java index 33f8e82dc5..d8917387f8 100644 --- a/src/test/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerAsyncImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerAsyncImplTest.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.util.ReportingQueueService; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; import java.util.UUID; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/src/test/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerImplTest.java index 6f7c209483..0a47481a73 100644 --- a/src/test/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerImplTest.java @@ -44,8 +44,8 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.time.LocalDateTime; import java.util.Date; import java.util.Map; diff --git a/src/test/java/com/epam/ta/reportportal/core/item/impl/GetTestItemHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/item/impl/GetTestItemHandlerImplTest.java index f1348bf95a..f24bf5f83f 100644 --- a/src/test/java/com/epam/ta/reportportal/core/item/impl/GetTestItemHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/item/impl/GetTestItemHandlerImplTest.java @@ -31,7 +31,7 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.function.Executable; diff --git a/src/test/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerAsyncImplTest.java b/src/test/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerAsyncImplTest.java index b1264242fb..f12341cfb1 100644 --- a/src/test/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerAsyncImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerAsyncImplTest.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.util.ReportingQueueService; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; diff --git a/src/test/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerImplTest.java index 4db2058cdc..6bbccbe3ab 100644 --- a/src/test/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/item/impl/StartTestItemHandlerImplTest.java @@ -37,8 +37,8 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; diff --git a/src/test/java/com/epam/ta/reportportal/core/item/impl/UpdateTestItemHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/item/impl/UpdateTestItemHandlerImplTest.java index d7b4a69dba..ce15d35af3 100644 --- a/src/test/java/com/epam/ta/reportportal/core/item/impl/UpdateTestItemHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/item/impl/UpdateTestItemHandlerImplTest.java @@ -43,10 +43,10 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.issue.DefineIssueRQ; -import com.epam.ta.reportportal.ws.model.item.UpdateTestItemRQ; +import com.epam.ta.reportportal.model.issue.DefineIssueRQ; +import com.epam.ta.reportportal.model.item.UpdateTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorType; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.common.collect.Sets; import java.util.Map; import java.util.Optional; diff --git a/src/test/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerAsyncImplTest.java b/src/test/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerAsyncImplTest.java index 7a76a64e33..b6cd736103 100644 --- a/src/test/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerAsyncImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerAsyncImplTest.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.util.ReportingQueueService; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; diff --git a/src/test/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerImplTest.java index bc93573082..5ba5ae0975 100644 --- a/src/test/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/launch/impl/FinishLaunchHandlerImplTest.java @@ -38,10 +38,10 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.BulkRQ; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; -import com.epam.ta.reportportal.ws.model.launch.FinishLaunchRS; +import com.epam.ta.reportportal.model.BulkRQ; +import com.epam.ta.reportportal.model.launch.FinishLaunchRS; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; @@ -88,14 +88,16 @@ void finishLaunch() { finishExecutionRQ.setEndTime( Date.from(LocalDateTime.now().atZone(ZoneId.of("UTC")).toInstant())); - ReportPortalUser rpUser = getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, - 1L); + ReportPortalUser rpUser = + getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); when(launchRepository.findByUuid("1")).thenReturn( getLaunch(StatusEnum.IN_PROGRESS, LaunchModeEnum.DEFAULT)); - FinishLaunchRS response = handler.finishLaunch("1", finishExecutionRQ, - extractProjectDetails(rpUser, "test_project"), rpUser, null); + FinishLaunchRS response = + handler.finishLaunch("1", finishExecutionRQ, extractProjectDetails(rpUser, "test_project"), + rpUser, null + ); verify(finishHierarchyHandler, times(1)).finishDescendants(any(), any(), any(), any(), any()); @@ -108,18 +110,16 @@ void finishLaunchWithLink() { finishExecutionRQ.setEndTime( Date.from(LocalDateTime.now().atZone(ZoneId.of("UTC")).toInstant())); - ReportPortalUser rpUser = getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, - 1L); + ReportPortalUser rpUser = + getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); when(launchRepository.findByUuid("1")).thenReturn( getLaunch(StatusEnum.IN_PROGRESS, LaunchModeEnum.DEFAULT)); - final FinishLaunchRS finishLaunchRS = handler.finishLaunch("1", - finishExecutionRQ, - extractProjectDetails(rpUser, "test_project"), - rpUser, - "http://example.com" - ); + final FinishLaunchRS finishLaunchRS = + handler.finishLaunch("1", finishExecutionRQ, extractProjectDetails(rpUser, "test_project"), + rpUser, "http://example.com" + ); verify(finishHierarchyHandler, times(1)).finishDescendants(any(), any(), any(), any(), any()); @@ -133,16 +133,14 @@ void stopLaunch() { finishExecutionRQ.setEndTime( Date.from(LocalDateTime.now().atZone(ZoneId.of("UTC")).toInstant())); - ReportPortalUser rpUser = getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, - 1L); + ReportPortalUser rpUser = + getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); when(launchRepository.findById(1L)).thenReturn( getLaunch(StatusEnum.IN_PROGRESS, LaunchModeEnum.DEFAULT)); - final OperationCompletionRS response = stopLaunchHandler.stopLaunch(1L, - finishExecutionRQ, - extractProjectDetails(rpUser, "test_project"), - rpUser + final OperationCompletionRS response = stopLaunchHandler.stopLaunch(1L, finishExecutionRQ, + extractProjectDetails(rpUser, "test_project"), rpUser ); assertNotNull(response); assertEquals("Launch with ID = '1' successfully stopped.", response.getResultMessage()); @@ -160,16 +158,14 @@ void bulkStopLaunch() { BulkRQ bulkRq = new BulkRQ<>(); bulkRq.setEntities(entities); - ReportPortalUser rpUser = getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, - 1L); + ReportPortalUser rpUser = + getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); when(launchRepository.findById(1L)).thenReturn( getLaunch(StatusEnum.IN_PROGRESS, LaunchModeEnum.DEFAULT)); - final List response = stopLaunchHandler.stopLaunch(bulkRq, - extractProjectDetails(rpUser, "test_project"), - rpUser - ); + final List response = + stopLaunchHandler.stopLaunch(bulkRq, extractProjectDetails(rpUser, "test_project"), rpUser); assertNotNull(response); assertEquals(1, response.size()); } @@ -180,16 +176,15 @@ void finishWithIncorrectStatus() { finishExecutionRQ.setEndTime( Date.from(LocalDateTime.now().atZone(ZoneId.of("UTC")).toInstant())); - final ReportPortalUser rpUser = getRpUser("test", UserRole.ADMINISTRATOR, - ProjectRole.PROJECT_MANAGER, 1L); + final ReportPortalUser rpUser = + getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); when(launchRepository.findByUuid("1")).thenReturn( getLaunch(StatusEnum.PASSED, LaunchModeEnum.DEFAULT)); - assertThrows(ReportPortalException.class, - () -> handler.finishLaunch("1", finishExecutionRQ, - extractProjectDetails(rpUser, "test_project"), rpUser, null) - ); + assertThrows(ReportPortalException.class, () -> handler.finishLaunch("1", finishExecutionRQ, + extractProjectDetails(rpUser, "test_project"), rpUser, null + )); } @Test @@ -198,16 +193,15 @@ void finishWithIncorrectEndTime() { finishExecutionRQ.setEndTime( Date.from(LocalDateTime.now().minusHours(5).atZone(ZoneId.of("UTC")).toInstant())); - final ReportPortalUser rpUser = getRpUser("test", UserRole.ADMINISTRATOR, - ProjectRole.PROJECT_MANAGER, 1L); + final ReportPortalUser rpUser = + getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); when(launchRepository.findByUuid("1")).thenReturn( getLaunch(StatusEnum.IN_PROGRESS, LaunchModeEnum.DEFAULT)); - assertThrows(ReportPortalException.class, - () -> handler.finishLaunch("1", finishExecutionRQ, - extractProjectDetails(rpUser, "test_project"), rpUser, null) - ); + assertThrows(ReportPortalException.class, () -> handler.finishLaunch("1", finishExecutionRQ, + extractProjectDetails(rpUser, "test_project"), rpUser, null + )); } @Test @@ -224,9 +218,11 @@ void finishNotOwnLaunch() { final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.finishLaunch("1", finishExecutionRQ, - extractProjectDetails(rpUser, "test_project"), rpUser, null) + extractProjectDetails(rpUser, "test_project"), rpUser, null + ) ); assertEquals("You do not have enough permissions. You are not launch owner.", - exception.getMessage()); + exception.getMessage() + ); } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/core/launch/impl/GetLaunchHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/launch/impl/GetLaunchHandlerImplTest.java index ecb75b6190..858ae21ae9 100644 --- a/src/test/java/com/epam/ta/reportportal/core/launch/impl/GetLaunchHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/launch/impl/GetLaunchHandlerImplTest.java @@ -44,8 +44,8 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.Page; import com.epam.ta.reportportal.ws.converter.converters.LaunchConverter; -import com.epam.ta.reportportal.ws.model.Page; import com.epam.ta.reportportal.ws.model.launch.cluster.ClusterInfoResource; import java.util.List; import java.util.Optional; @@ -96,8 +96,8 @@ class GetLaunchHandlerImplTest { @Test void getLaunchFromOtherProject() { - final ReportPortalUser rpUser = getRpUser("test", UserRole.ADMINISTRATOR, - ProjectRole.PROJECT_MANAGER, 2L); + final ReportPortalUser rpUser = + getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 2L); when(launchRepository.findById(1L)).thenReturn( getLaunch(StatusEnum.FAILED, LaunchModeEnum.DEFAULT)); @@ -125,7 +125,8 @@ void getLaunchNamesIncorrectInput() { assertThrows(ReportPortalException.class, () -> handler.getLaunchNames(extractProjectDetails(rpUser, "test_project"), - RandomStringUtils.random(257)) + RandomStringUtils.random(257) + ) ); } @@ -150,10 +151,12 @@ void getLaunchByNotExistProjectName() { ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.getLaunchByProjectName(projectName, PageRequest.of(0, 10), getDefaultFilter(), - "user") + "user" + ) ); assertEquals("Project 'not_exist' not found. Did you use correct project name?", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -165,7 +168,8 @@ void getLaunchByProjectNameNotFound() { ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.getLaunchByProjectName(projectName, PageRequest.of(0, 10), getDefaultFilter(), - "user") + "user" + ) ); assertEquals("Launch '' not found. Did you use correct Launch ID?", exception.getMessage()); } @@ -173,64 +177,68 @@ void getLaunchByProjectNameNotFound() { @Test void getLaunchesByNotExistProject() { long projectId = 1L; - ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, - projectId); + ReportPortalUser user = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); when(projectRepository.findById(projectId)).thenReturn(Optional.empty()); ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.getProjectLaunches(extractProjectDetails(user, "test_project"), - getDefaultFilter(), - PageRequest.of(0, 10), - "user" + getDefaultFilter(), PageRequest.of(0, 10), "user" ) ); assertEquals("Project '1' not found. Did you use correct project name?", - exception.getMessage()); + exception.getMessage() + ); } @Test void getLatestLaunchesOnNotExistProject() { long projectId = 1L; - ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, - projectId); + ReportPortalUser user = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); when(projectRepository.findById(projectId)).thenReturn(Optional.empty()); ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.getLatestLaunches(extractProjectDetails(user, "test_project"), - getDefaultFilter(), PageRequest.of(0, 10)) + getDefaultFilter(), PageRequest.of(0, 10) + ) ); assertEquals("Project '1' not found. Did you use correct project name?", - exception.getMessage()); + exception.getMessage() + ); } @Test void getOwnersWrongTerm() { long projectId = 1L; - ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, - projectId); + ReportPortalUser user = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.getOwners(extractProjectDetails(user, "test_project"), "qw", - LaunchModeEnum.DEFAULT.name()) + LaunchModeEnum.DEFAULT.name() + ) ); assertEquals( "Incorrect filtering parameters. Length of the filtering string 'qw' is less than 3 symbols", - exception.getMessage()); + exception.getMessage() + ); } @Test void getOwnersWrongMode() { long projectId = 1L; - ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, - projectId); + ReportPortalUser user = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.getOwners(extractProjectDetails(user, "test_project"), "qwe", "incorrectMode") ); assertEquals("Incorrect filtering parameters. Mode - incorrectMode doesn't exist.", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -292,13 +300,13 @@ void getClusterInfo() { final Pageable pageable = PageRequest.of(1, 2); - final Page expected = new Page<>( - List.of(new ClusterInfoResource(), new ClusterInfoResource()), 2, 1, 10); + final Page expected = + new Page<>(List.of(new ClusterInfoResource(), new ClusterInfoResource()), 2, 1, 10); when(getClusterHandler.getResources(launch, pageable)).thenReturn(expected); - final Iterable result = handler.getClusters(launchId, - extractProjectDetails(user, "test_project"), pageable); + final Iterable result = + handler.getClusters(launchId, extractProjectDetails(user, "test_project"), pageable); final Page castedResult = (Page) result; @@ -314,8 +322,7 @@ void getClusterInfo() { } private Filter getDefaultFilter() { - return Filter.builder() - .withTarget(Launch.class) + return Filter.builder().withTarget(Launch.class) .withCondition(FilterCondition.builder().eq(CRITERIA_LAUNCH_STATUS, "PASSED").build()) .build(); } diff --git a/src/test/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerAsyncImplTest.java b/src/test/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerAsyncImplTest.java index ca463f709d..59312da3ca 100644 --- a/src/test/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerAsyncImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerAsyncImplTest.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.util.ReportingQueueService; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; diff --git a/src/test/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerImplTest.java index 8d074cf6cb..eee25a8920 100644 --- a/src/test/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/launch/impl/StartLaunchHandlerImplTest.java @@ -35,9 +35,9 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.launch.Mode; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRS; +import com.epam.ta.reportportal.ws.reporting.Mode; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRS; import java.util.Date; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/src/test/java/com/epam/ta/reportportal/core/launch/impl/UpdateLaunchHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/launch/impl/UpdateLaunchHandlerImplTest.java index e6ee281289..455773cda8 100644 --- a/src/test/java/com/epam/ta/reportportal/core/launch/impl/UpdateLaunchHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/launch/impl/UpdateLaunchHandlerImplTest.java @@ -44,9 +44,9 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.launch.Mode; -import com.epam.ta.reportportal.ws.model.launch.UpdateLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.cluster.CreateClustersRQ; +import com.epam.ta.reportportal.model.launch.UpdateLaunchRQ; +import com.epam.ta.reportportal.model.launch.cluster.CreateClustersRQ; +import com.epam.ta.reportportal.ws.reporting.Mode; import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -92,7 +92,8 @@ void updateNotOwnLaunch() { getLaunch(StatusEnum.PASSED, LaunchModeEnum.DEFAULT)); final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.updateLaunch(1L, extractProjectDetails(rpUser, "test_project"), rpUser, - new UpdateLaunchRQ()) + new UpdateLaunchRQ() + ) ); assertEquals("You do not have enough permissions.", exception.getMessage()); } @@ -110,7 +111,8 @@ void updateDebugLaunchByCustomer() { final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.updateLaunch(1L, extractProjectDetails(rpUser, "test_project"), rpUser, - updateLaunchRQ) + updateLaunchRQ + ) ); assertEquals("You do not have enough permissions.", exception.getMessage()); } @@ -128,11 +130,13 @@ void createClustersLaunchInProgress() { final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.createClusters(createClustersRQ, - extractProjectDetails(rpUser, "test_project"), rpUser) + extractProjectDetails(rpUser, "test_project"), rpUser + ) ); assertEquals("Incorrect Request. Cannot analyze launch in progress.", exception.getMessage()); verify(launchAccessValidator, times(1)).validate(any(Launch.class), - any(ReportPortalUser.ProjectDetails.class), eq(rpUser)); + any(ReportPortalUser.ProjectDetails.class), eq(rpUser) + ); } @Test @@ -156,10 +160,11 @@ void createClusters() { handler.createClusters(createClustersRQ, extractProjectDetails(rpUser, "test_project"), rpUser); verify(launchAccessValidator, times(1)).validate(any(Launch.class), - any(ReportPortalUser.ProjectDetails.class), eq(rpUser)); + any(ReportPortalUser.ProjectDetails.class), eq(rpUser) + ); - final ArgumentCaptor contextCaptor = ArgumentCaptor.forClass( - ClusterEntityContext.class); + final ArgumentCaptor contextCaptor = + ArgumentCaptor.forClass(ClusterEntityContext.class); final ArgumentCaptor> mapCaptor = ArgumentCaptor.forClass(Map.class); verify(starter, times(1)).start(contextCaptor.capture(), mapCaptor.capture()); diff --git a/src/test/java/com/epam/ta/reportportal/core/launch/rerun/RerunHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/launch/rerun/RerunHandlerImplTest.java index 3baeffaca3..074629a281 100644 --- a/src/test/java/com/epam/ta/reportportal/core/launch/rerun/RerunHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/launch/rerun/RerunHandlerImplTest.java @@ -44,11 +44,11 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributesRQ; -import com.epam.ta.reportportal.ws.model.item.ItemCreatedRS; -import com.epam.ta.reportportal.ws.model.launch.Mode; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.ItemAttributesRQ; +import com.epam.ta.reportportal.ws.reporting.ItemCreatedRS; +import com.epam.ta.reportportal.ws.reporting.Mode; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Optional; diff --git a/src/test/java/com/epam/ta/reportportal/core/launch/util/LaunchValidatorTest.java b/src/test/java/com/epam/ta/reportportal/core/launch/util/LaunchValidatorTest.java index 02ad7ed9e3..9f6bcc60ff 100644 --- a/src/test/java/com/epam/ta/reportportal/core/launch/util/LaunchValidatorTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/launch/util/LaunchValidatorTest.java @@ -18,7 +18,7 @@ import static com.epam.ta.reportportal.commons.EntityUtils.TO_DATE; import static com.epam.ta.reportportal.commons.EntityUtils.TO_LOCAL_DATE_TIME; -import static com.epam.ta.reportportal.ws.model.ErrorType.FINISH_TIME_EARLIER_THAN_START_TIME; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.FINISH_TIME_EARLIER_THAN_START_TIME; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -26,7 +26,7 @@ import com.epam.ta.reportportal.entity.enums.StatusEnum; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; diff --git a/src/test/java/com/epam/ta/reportportal/core/launch/util/MergeLaunchesSerializerTest.java b/src/test/java/com/epam/ta/reportportal/core/launch/util/MergeLaunchesSerializerTest.java new file mode 100644 index 0000000000..938ef02ccb --- /dev/null +++ b/src/test/java/com/epam/ta/reportportal/core/launch/util/MergeLaunchesSerializerTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2019 EPAM Systems + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in 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 com.epam.ta.reportportal.core.launch.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.MergeLaunchesRQ; +import com.epam.ta.reportportal.ws.reporting.Mode; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.Date; +import org.junit.jupiter.api.Test; + +/** + * @author Pavel Bortnik + */ +public class MergeLaunchesSerializerTest { + + private static final String EXPECTED_JSON = "{\"name\":\"name\"," + + "\"description\":\"description\",\"attributes\":[{\"key\":\"key\",\"value\":\"value\"}],\"startTime\":0,\"mode\":\"DEFAULT\"," + + "\"launches\":[1],\"endTime\":1,\"mergeType\":\"BASIC\",\"extendSuitesDescription\":true}"; + + private ObjectMapper om = new ObjectMapper(); + + @Test + public void testSerializer() throws JsonProcessingException { + MergeLaunchesRQ rq = getMergeLaunches(); + String json = om.writeValueAsString(rq); + assertEquals(json, EXPECTED_JSON, "Incorrect serialization result"); + } + + @Test + public void testDeserializer() throws IOException { + MergeLaunchesRQ rq = + om.readValue(EXPECTED_JSON.getBytes(StandardCharsets.UTF_8), MergeLaunchesRQ.class); + assertEquals(getMergeLaunches(), rq, "Incorrect deserialization result"); + } + + private MergeLaunchesRQ getMergeLaunches() { + MergeLaunchesRQ rq = new MergeLaunchesRQ(); + rq.setName("name"); + rq.setDescription("description"); + rq.setMode(Mode.DEFAULT); + rq.setStartTime(new Date(0)); + ItemAttributeResource itemAttributeResource = new ItemAttributeResource("key", "value"); + rq.setAttributes(Collections.singleton(itemAttributeResource)); + rq.setEndTime(new Date(1)); + rq.setExtendSuitesDescription(true); + rq.setLaunches(Collections.singleton(1L)); + rq.setMergeStrategyType("BASIC"); + return rq; + } + +} diff --git a/src/test/java/com/epam/ta/reportportal/core/log/impl/CreateLogHandlerAsyncImplTest.java b/src/test/java/com/epam/ta/reportportal/core/log/impl/CreateLogHandlerAsyncImplTest.java index bcf4eb3512..86f9332ac9 100644 --- a/src/test/java/com/epam/ta/reportportal/core/log/impl/CreateLogHandlerAsyncImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/log/impl/CreateLogHandlerAsyncImplTest.java @@ -26,7 +26,7 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.util.ReportingQueueService; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; import javax.inject.Provider; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/src/test/java/com/epam/ta/reportportal/core/project/impl/CreateProjectHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/project/impl/CreateProjectHandlerImplTest.java index 2dd97504e0..097ad52f90 100644 --- a/src/test/java/com/epam/ta/reportportal/core/project/impl/CreateProjectHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/project/impl/CreateProjectHandlerImplTest.java @@ -27,7 +27,7 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.project.CreateProjectRQ; +import com.epam.ta.reportportal.model.project.CreateProjectRQ; import java.util.Optional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -52,8 +52,8 @@ class CreateProjectHandlerImplTest { @Test void createProjectWithWrongType() { - ReportPortalUser rpUser = getRpUser("user", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, - 1L); + ReportPortalUser rpUser = + getRpUser("user", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); CreateProjectRQ createProjectRQ = new CreateProjectRQ(); String projectName = "projectName"; @@ -64,16 +64,18 @@ void createProjectWithWrongType() { Optional.empty()); ReportPortalException exception = assertThrows(ReportPortalException.class, - () -> handler.createProject(createProjectRQ, rpUser)); + () -> handler.createProject(createProjectRQ, rpUser) + ); assertEquals("Error in handled Request. Please, check specified parameters: 'wrongType'", - exception.getMessage()); + exception.getMessage() + ); } @Test void createProjectByNotExistUser() { - ReportPortalUser rpUser = getRpUser("user", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, - 1L); + ReportPortalUser rpUser = + getRpUser("user", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); CreateProjectRQ createProjectRQ = new CreateProjectRQ(); String projectName = "projectName"; @@ -85,7 +87,8 @@ void createProjectByNotExistUser() { when(userRepository.findRawById(rpUser.getUserId())).thenReturn(Optional.empty()); ReportPortalException exception = assertThrows(ReportPortalException.class, - () -> handler.createProject(createProjectRQ, rpUser)); + () -> handler.createProject(createProjectRQ, rpUser) + ); assertEquals("User 'user' not found.", exception.getMessage()); } diff --git a/src/test/java/com/epam/ta/reportportal/core/project/impl/DeleteProjectHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/project/impl/DeleteProjectHandlerImplTest.java index 54ed8ef79c..25e60c6ae0 100644 --- a/src/test/java/com/epam/ta/reportportal/core/project/impl/DeleteProjectHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/project/impl/DeleteProjectHandlerImplTest.java @@ -44,7 +44,7 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.OperationCompletionRS; +import com.epam.ta.reportportal.ws.reporting.OperationCompletionRS; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.Sets; diff --git a/src/test/java/com/epam/ta/reportportal/core/project/impl/GetProjectHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/project/impl/GetProjectHandlerImplTest.java index 9b371960d5..254b719e85 100644 --- a/src/test/java/com/epam/ta/reportportal/core/project/impl/GetProjectHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/project/impl/GetProjectHandlerImplTest.java @@ -16,6 +16,14 @@ package com.epam.ta.reportportal.core.project.impl; +import static com.epam.ta.reportportal.ReportPortalUserUtil.getRpUser; +import static com.epam.ta.reportportal.commons.querygen.constant.UserCriteriaConstant.CRITERIA_ROLE; +import static com.epam.ta.reportportal.util.TestProjectExtractor.extractProjectDetails; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.commons.querygen.FilterCondition; @@ -25,7 +33,8 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.user.UserResource; +import com.epam.ta.reportportal.model.user.UserResource; +import java.util.Optional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -33,97 +42,99 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.data.domain.PageRequest; -import java.util.Optional; - -import static com.epam.ta.reportportal.ReportPortalUserUtil.getRpUser; -import static com.epam.ta.reportportal.commons.querygen.constant.UserCriteriaConstant.CRITERIA_ROLE; -import static com.epam.ta.reportportal.util.TestProjectExtractor.extractProjectDetails; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.when; - /** * @author Ihar Kahadouski */ @ExtendWith(MockitoExtension.class) class GetProjectHandlerImplTest { - @Mock - private ProjectRepository projectRepository; - - @InjectMocks - private GetProjectHandlerImpl handler; - - @Test - void getUsersOnNotExistProject() { - long projectId = 1L; - - String projectName = "test_project"; - when(projectRepository.findByName(projectName)).thenReturn(Optional.empty()); - - ReportPortalException exception = assertThrows(ReportPortalException.class, () -> { - handler.getProjectUsers(projectName, - Filter.builder() - .withTarget(User.class) - .withCondition(FilterCondition.builder().eq(CRITERIA_ROLE, UserRole.USER.name()).build()) - .build(), - PageRequest.of(0, 10) - ); - } - ); - - assertEquals("Project 'test_project' not found. Did you use correct project name?", exception.getMessage()); - } - - @Test - void getEmptyUserList() { - long projectId = 1L; - - String projectName = "test_project"; - when(projectRepository.findByName(projectName)).thenReturn(Optional.of(new Project())); - - Iterable users = handler.getProjectUsers(projectName, - Filter.builder() - .withTarget(User.class) - .withCondition(FilterCondition.builder().eq(CRITERIA_ROLE, UserRole.USER.name()).build()) - .build(), - PageRequest.of(0, 10) - ); - - assertFalse(users.iterator().hasNext()); - } - - @Test - void getNotExistProject() { - String projectName = "not_exist"; - long projectId = 1L; - ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); - - when(projectRepository.findByName(projectName)).thenReturn(Optional.empty()); - - ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.getResource(projectName, user)); - - assertEquals("Project '" + projectName + "' not found. Did you use correct project name?", exception.getMessage()); - } - - @Test - void getUserNamesByIncorrectTerm() { - long projectId = 1L; - ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); - - ReportPortalException exception = assertThrows(ReportPortalException.class, - () -> handler.getUserNames(extractProjectDetails(user, "test_project"), "") - ); - - assertEquals( - "Incorrect filtering parameters. Length of the filtering string '' is less than 1 symbol", - exception.getMessage()); - } - - @Test - void getUserNamesNegative() { - ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.getUserNames("", - new ReportPortalUser.ProjectDetails(1L, "superadmin_personal", ProjectRole.PROJECT_MANAGER), - PageRequest.of(0, 10))); - assertEquals("Incorrect filtering parameters. Length of the filtering string '' is less than 1 symbol", exception.getMessage()); - } + @Mock + private ProjectRepository projectRepository; + + @InjectMocks + private GetProjectHandlerImpl handler; + + @Test + void getUsersOnNotExistProject() { + long projectId = 1L; + + String projectName = "test_project"; + when(projectRepository.findByName(projectName)).thenReturn(Optional.empty()); + + ReportPortalException exception = assertThrows(ReportPortalException.class, () -> { + handler.getProjectUsers(projectName, Filter.builder().withTarget(User.class).withCondition( + FilterCondition.builder().eq(CRITERIA_ROLE, UserRole.USER.name()).build()).build(), + PageRequest.of(0, 10) + ); + }); + + assertEquals( + "Project 'test_project' not found. Did you use correct project name?", + exception.getMessage() + ); + } + + @Test + void getEmptyUserList() { + long projectId = 1L; + + String projectName = "test_project"; + when(projectRepository.findByName(projectName)).thenReturn(Optional.of(new Project())); + + Iterable users = + handler.getProjectUsers(projectName, Filter.builder().withTarget(User.class).withCondition( + FilterCondition.builder().eq(CRITERIA_ROLE, UserRole.USER.name()).build()).build(), + PageRequest.of(0, 10) + ); + + assertFalse(users.iterator().hasNext()); + } + + @Test + void getNotExistProject() { + String projectName = "not_exist"; + long projectId = 1L; + ReportPortalUser user = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); + + when(projectRepository.findByName(projectName)).thenReturn(Optional.empty()); + + ReportPortalException exception = + assertThrows(ReportPortalException.class, () -> handler.getResource(projectName, user)); + + assertEquals( + "Project '" + projectName + "' not found. Did you use correct project name?", + exception.getMessage() + ); + } + + @Test + void getUserNamesByIncorrectTerm() { + long projectId = 1L; + ReportPortalUser user = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); + + ReportPortalException exception = assertThrows(ReportPortalException.class, + () -> handler.getUserNames(extractProjectDetails(user, "test_project"), "") + ); + + assertEquals( + "Incorrect filtering parameters. Length of the filtering string '' is less than 1 symbol", + exception.getMessage() + ); + } + + @Test + void getUserNamesNegative() { + ReportPortalException exception = assertThrows( + ReportPortalException.class, () -> handler.getUserNames("", + new ReportPortalUser.ProjectDetails(1L, "superadmin_personal", + ProjectRole.PROJECT_MANAGER + ), PageRequest.of(0, 10) + )); + assertEquals( + "Incorrect filtering parameters. Length of the filtering string '' is less than 1 symbol", + exception.getMessage() + ); + } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/core/project/impl/ProjectInfoWidgetDataConverterTest.java b/src/test/java/com/epam/ta/reportportal/core/project/impl/ProjectInfoWidgetDataConverterTest.java index 71e7b91f3b..36ae0fafd0 100644 --- a/src/test/java/com/epam/ta/reportportal/core/project/impl/ProjectInfoWidgetDataConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/project/impl/ProjectInfoWidgetDataConverterTest.java @@ -30,7 +30,7 @@ import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.entity.statistics.Statistics; import com.epam.ta.reportportal.entity.statistics.StatisticsField; -import com.epam.ta.reportportal.ws.model.widget.ChartObject; +import com.epam.ta.reportportal.model.widget.ChartObject; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import java.time.DayOfWeek; @@ -44,6 +44,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Locale; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -65,6 +66,7 @@ class ProjectInfoWidgetDataConverterTest { @BeforeEach void setUp() { + Locale.setDefault(Locale.US); converter = new ProjectInfoWidgetDataConverter( ImmutableMap.builder() .put(InfoInterval.ONE_MONTH, ProjectInfoWidgetDataConverter.ProjectInfoGroup.BY_DAY) @@ -72,11 +74,9 @@ void setUp() { .put(InfoInterval.SIX_MONTHS, ProjectInfoWidgetDataConverter.ProjectInfoGroup.BY_WEEK) .build()); - thisWeekFormattedDate = LocalDate.now(ZoneOffset.UTC) - .format(new DateTimeFormatterBuilder().appendValue(IsoFields.WEEK_BASED_YEAR, 4) - .appendLiteral("-W") - .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2) - .toFormatter()); + thisWeekFormattedDate = LocalDate.now(ZoneOffset.UTC).format( + new DateTimeFormatterBuilder().appendValue(IsoFields.WEEK_BASED_YEAR, 4).appendLiteral("-W") + .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2).toFormatter()); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); @@ -90,20 +90,23 @@ void setUp() { @Test void getInvestigatedProjectInfo() { - Map> investigatedProjectInfo = converter.getInvestigatedProjectInfo( - getTestData(), - InfoInterval.ONE_MONTH - ); + Locale.setDefault(Locale.US); + Map> investigatedProjectInfo = + converter.getInvestigatedProjectInfo(getTestData(), InfoInterval.ONE_MONTH); assertEquals("33.33", - investigatedProjectInfo.get(yesterdayString).get(0).getValues().get("toInvestigate")); + investigatedProjectInfo.get(yesterdayString).get(0).getValues().get("toInvestigate") + ); assertEquals("66.67", - investigatedProjectInfo.get(yesterdayString).get(0).getValues().get("investigated")); + investigatedProjectInfo.get(yesterdayString).get(0).getValues().get("investigated") + ); assertEquals("38.46", - investigatedProjectInfo.get(todayString).get(0).getValues().get("toInvestigate")); + investigatedProjectInfo.get(todayString).get(0).getValues().get("toInvestigate") + ); assertEquals("61.54", - investigatedProjectInfo.get(todayString).get(0).getValues().get("investigated")); + investigatedProjectInfo.get(todayString).get(0).getValues().get("investigated") + ); } @Test @@ -116,34 +119,39 @@ void getInvestigatedProjectInfoWithoutDefectsStatistics() { launch.setStatistics( Sets.newHashSet(getStatistics(EXECUTIONS_TOTAL, 5), getStatistics(EXECUTIONS_PASSED, 5))); - Map> investigatedProjectInfo = converter.getInvestigatedProjectInfo( - Collections.singletonList(launch), - InfoInterval.THREE_MONTHS - ); + Map> investigatedProjectInfo = + converter.getInvestigatedProjectInfo(Collections.singletonList(launch), + InfoInterval.THREE_MONTHS + ); assertEquals("0", - investigatedProjectInfo.get(thisWeekFormattedDate).get(0).getValues().get("toInvestigate")); + investigatedProjectInfo.get(thisWeekFormattedDate).get(0).getValues().get("toInvestigate") + ); assertEquals("0", - investigatedProjectInfo.get(thisWeekFormattedDate).get(0).getValues().get("investigated")); + investigatedProjectInfo.get(thisWeekFormattedDate).get(0).getValues().get("investigated") + ); } @Test void getTestCasesStatisticsProjectInfo() { - Map> testCasesStatisticsProjectInfo = converter.getTestCasesStatisticsProjectInfo( - getTestData()); + Map> testCasesStatisticsProjectInfo = + converter.getTestCasesStatisticsProjectInfo(getTestData()); assertEquals("18.0", - testCasesStatisticsProjectInfo.get("test_launch").get(0).getValues().get("min")); + testCasesStatisticsProjectInfo.get("test_launch").get(0).getValues().get("min") + ); assertEquals("19.5", - testCasesStatisticsProjectInfo.get("test_launch").get(0).getValues().get("avg")); + testCasesStatisticsProjectInfo.get("test_launch").get(0).getValues().get("avg") + ); assertEquals("21.0", - testCasesStatisticsProjectInfo.get("test_launch").get(0).getValues().get("max")); + testCasesStatisticsProjectInfo.get("test_launch").get(0).getValues().get("max") + ); } @Test void getLaunchesQuantity() { - Map> launchesQuantity = converter.getLaunchesQuantity(getTestData(), - InfoInterval.ONE_MONTH); + Map> launchesQuantity = + converter.getLaunchesQuantity(getTestData(), InfoInterval.ONE_MONTH); assertEquals("1", launchesQuantity.get(yesterdayString).get(0).getValues().get("count")); assertEquals("1", launchesQuantity.get(todayString).get(0).getValues().get("count")); @@ -151,16 +159,16 @@ void getLaunchesQuantity() { @Test void getLaunchesQuantityByWeek() { - Map> launchesQuantity = converter.getLaunchesQuantity(getTestData(), - InfoInterval.THREE_MONTHS); + Map> launchesQuantity = + converter.getLaunchesQuantity(getTestData(), InfoInterval.THREE_MONTHS); assertEquals("2", launchesQuantity.get(thisWeekFormattedDate).get(0).getValues().get("count")); } @Test void getLaunchesIssues() { - Map> launchesIssues = converter.getLaunchesIssues(getTestData(), - InfoInterval.ONE_MONTH); + Map> launchesIssues = + converter.getLaunchesIssues(getTestData(), InfoInterval.ONE_MONTH); assertEquals("3", launchesIssues.get(yesterdayString).get(0).getValues().get("systemIssue")); assertEquals("4", launchesIssues.get(yesterdayString).get(0).getValues().get("toInvestigate")); @@ -175,17 +183,21 @@ void getLaunchesIssues() { @Test void getLaunchesIssuesByWeek() { - Map> launchesIssues = converter.getLaunchesIssues(getTestData(), - InfoInterval.THREE_MONTHS); + Map> launchesIssues = + converter.getLaunchesIssues(getTestData(), InfoInterval.THREE_MONTHS); assertEquals("6", - launchesIssues.get(thisWeekFormattedDate).get(0).getValues().get("systemIssue")); + launchesIssues.get(thisWeekFormattedDate).get(0).getValues().get("systemIssue") + ); assertEquals("9", - launchesIssues.get(thisWeekFormattedDate).get(0).getValues().get("toInvestigate")); + launchesIssues.get(thisWeekFormattedDate).get(0).getValues().get("toInvestigate") + ); assertEquals("3", - launchesIssues.get(thisWeekFormattedDate).get(0).getValues().get("productBug")); + launchesIssues.get(thisWeekFormattedDate).get(0).getValues().get("productBug") + ); assertEquals("7", - launchesIssues.get(thisWeekFormattedDate).get(0).getValues().get("automationBug")); + launchesIssues.get(thisWeekFormattedDate).get(0).getValues().get("automationBug") + ); } private List getTestData() { @@ -194,29 +206,27 @@ private List getTestData() { launch1.setId(1L); launch1.setNumber(1L); launch1.setStartTime(LocalDateTime.of(yesterday, LocalTime.now(ZoneOffset.UTC))); - launch1.setStatistics(Sets.newHashSet(getStatistics(EXECUTIONS_TOTAL, 18), - getStatistics(EXECUTIONS_PASSED, 5), - getStatistics(EXECUTIONS_SKIPPED, 1), - getStatistics(EXECUTIONS_FAILED, 12), - getStatistics(DEFECTS_AUTOMATION_BUG_TOTAL, 3), - getStatistics(DEFECTS_PRODUCT_BUG_TOTAL, 2), - getStatistics(DEFECTS_SYSTEM_ISSUE_TOTAL, 3), - getStatistics(DEFECTS_TO_INVESTIGATE_TOTAL, 4) - )); + launch1.setStatistics( + Sets.newHashSet(getStatistics(EXECUTIONS_TOTAL, 18), getStatistics(EXECUTIONS_PASSED, 5), + getStatistics(EXECUTIONS_SKIPPED, 1), getStatistics(EXECUTIONS_FAILED, 12), + getStatistics(DEFECTS_AUTOMATION_BUG_TOTAL, 3), + getStatistics(DEFECTS_PRODUCT_BUG_TOTAL, 2), + getStatistics(DEFECTS_SYSTEM_ISSUE_TOTAL, 3), + getStatistics(DEFECTS_TO_INVESTIGATE_TOTAL, 4) + )); Launch launch2 = new Launch(); launch2.setName("test_launch"); launch2.setId(2L); launch2.setNumber(2L); launch2.setStartTime(LocalDateTime.of(today, LocalTime.now(ZoneOffset.UTC))); - launch2.setStatistics(Sets.newHashSet(getStatistics(EXECUTIONS_TOTAL, 21), - getStatistics(EXECUTIONS_PASSED, 6), - getStatistics(EXECUTIONS_SKIPPED, 2), - getStatistics(EXECUTIONS_FAILED, 13), - getStatistics(DEFECTS_AUTOMATION_BUG_TOTAL, 4), - getStatistics(DEFECTS_PRODUCT_BUG_TOTAL, 1), - getStatistics(DEFECTS_SYSTEM_ISSUE_TOTAL, 3), - getStatistics(DEFECTS_TO_INVESTIGATE_TOTAL, 5) - )); + launch2.setStatistics( + Sets.newHashSet(getStatistics(EXECUTIONS_TOTAL, 21), getStatistics(EXECUTIONS_PASSED, 6), + getStatistics(EXECUTIONS_SKIPPED, 2), getStatistics(EXECUTIONS_FAILED, 13), + getStatistics(DEFECTS_AUTOMATION_BUG_TOTAL, 4), + getStatistics(DEFECTS_PRODUCT_BUG_TOTAL, 1), + getStatistics(DEFECTS_SYSTEM_ISSUE_TOTAL, 3), + getStatistics(DEFECTS_TO_INVESTIGATE_TOTAL, 5) + )); return Arrays.asList(launch1, launch2); } @@ -226,4 +236,4 @@ private Statistics getStatistics(String statisticsFieldName, int counter) { statistics.setCounter(counter); return statistics; } -} \ No newline at end of file +} diff --git a/src/test/java/com/epam/ta/reportportal/core/project/settings/impl/CreateProjectSettingsHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/project/settings/impl/CreateProjectSettingsHandlerImplTest.java index efa9b5b70c..3cd1ed4db7 100644 --- a/src/test/java/com/epam/ta/reportportal/core/project/settings/impl/CreateProjectSettingsHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/project/settings/impl/CreateProjectSettingsHandlerImplTest.java @@ -32,8 +32,8 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.project.config.CreateIssueSubTypeRQ; import com.epam.ta.reportportal.ws.model.ValidationConstraints; -import com.epam.ta.reportportal.ws.model.project.config.CreateIssueSubTypeRQ; import java.util.HashSet; import java.util.Optional; import java.util.Set; @@ -58,8 +58,8 @@ class CreateProjectSettingsHandlerImplTest { @Test void createSubtypeOnNotExistProject() { long projectId = 1L; - ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, - projectId); + ReportPortalUser user = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); when(projectRepository.findByName(TEST_PROJECT_NAME)).thenReturn(Optional.empty()); @@ -68,14 +68,15 @@ void createSubtypeOnNotExistProject() { ); assertEquals("Project 'test_project' not found. Did you use correct project name?", - exception.getMessage()); + exception.getMessage() + ); } @Test void createSubtypeWithWrongGroup() { long projectId = 1L; - ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, - projectId); + ReportPortalUser user = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); when(projectRepository.findByName(TEST_PROJECT_NAME)).thenReturn(Optional.of(new Project())); @@ -87,7 +88,8 @@ void createSubtypeWithWrongGroup() { ); assertEquals("Error in handled Request. Please, check specified parameters: 'wrongType'", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -96,8 +98,8 @@ void maxSubtypesCount() { project.setProjectIssueTypes(getSubTypes()); long projectId = 1L; - ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, - projectId); + ReportPortalUser user = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); when(projectRepository.findByName(TEST_PROJECT_NAME)).thenReturn(Optional.of(project)); @@ -109,7 +111,8 @@ void maxSubtypesCount() { ); assertEquals("Incorrect Request. Sub Issues count is bound of size limit", - exception.getMessage()); + exception.getMessage() + ); } private Set getSubTypes() { diff --git a/src/test/java/com/epam/ta/reportportal/core/project/settings/impl/UpdateProjectSettingsHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/project/settings/impl/UpdateProjectSettingsHandlerImplTest.java index 1fc6cc5d61..08588f7001 100644 --- a/src/test/java/com/epam/ta/reportportal/core/project/settings/impl/UpdateProjectSettingsHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/project/settings/impl/UpdateProjectSettingsHandlerImplTest.java @@ -28,8 +28,8 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.project.config.UpdateIssueSubTypeRQ; -import com.epam.ta.reportportal.ws.model.project.config.UpdateOneIssueSubTypeRQ; +import com.epam.ta.reportportal.model.project.config.UpdateIssueSubTypeRQ; +import com.epam.ta.reportportal.model.project.config.UpdateOneIssueSubTypeRQ; import java.util.Collections; import java.util.Optional; import org.junit.jupiter.api.Test; @@ -61,14 +61,15 @@ void emptyRequest() { () -> handler.updateProjectIssueSubType("test_project", user, updateIssueSubTypeRQ) ); assertEquals("Forbidden operation. Please specify at least one item data for update.", - exception.getMessage()); + exception.getMessage() + ); } @Test void updateSubtypeOnNotExistProject() { long projectId = 1L; - ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, - projectId); + ReportPortalUser user = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); UpdateIssueSubTypeRQ updateIssueSubTypeRQ = new UpdateIssueSubTypeRQ(); updateIssueSubTypeRQ.setIds(Collections.singletonList(new UpdateOneIssueSubTypeRQ())); @@ -79,14 +80,15 @@ void updateSubtypeOnNotExistProject() { () -> handler.updateProjectIssueSubType(TEST_PROJECT_NAME, user, updateIssueSubTypeRQ) ); assertEquals("Project 'test_project' not found. Did you use correct project name?", - exception.getMessage()); + exception.getMessage() + ); } @Test void updateSubtypeWithIncorrectGroup() { long projectId = 1L; - ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, - projectId); + ReportPortalUser user = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); UpdateIssueSubTypeRQ updateIssueSubTypeRQ = new UpdateIssueSubTypeRQ(); UpdateOneIssueSubTypeRQ oneIssueSubTypeRQ = new UpdateOneIssueSubTypeRQ(); @@ -104,8 +106,8 @@ void updateSubtypeWithIncorrectGroup() { @Test void updateNotExistSubtype() { long projectId = 1L; - ReportPortalUser user = getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, - projectId); + ReportPortalUser user = + getRpUser("user", UserRole.USER, ProjectRole.PROJECT_MANAGER, projectId); UpdateIssueSubTypeRQ updateIssueSubTypeRQ = new UpdateIssueSubTypeRQ(); UpdateOneIssueSubTypeRQ oneIssueSubTypeRQ = new UpdateOneIssueSubTypeRQ(); diff --git a/src/test/java/com/epam/ta/reportportal/core/project/settings/notification/CreateProjectNotificationHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/project/settings/notification/CreateProjectNotificationHandlerImplTest.java index d9ef4bc959..1c28130c0b 100644 --- a/src/test/java/com/epam/ta/reportportal/core/project/settings/notification/CreateProjectNotificationHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/project/settings/notification/CreateProjectNotificationHandlerImplTest.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.core.project.settings.notification; import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; -import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR; -import static com.epam.ta.reportportal.ws.model.ErrorType.RESOURCE_ALREADY_EXISTS; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.BAD_REQUEST_ERROR; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.RESOURCE_ALREADY_EXISTS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -35,9 +35,9 @@ import com.epam.ta.reportportal.entity.project.email.LaunchAttributeRule; import com.epam.ta.reportportal.entity.project.email.SenderCase; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; import com.epam.ta.reportportal.ws.converter.converters.ProjectConverter; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; import com.google.common.collect.Sets; import java.util.Collections; import java.util.Optional; @@ -55,12 +55,13 @@ class CreateProjectNotificationHandlerImplTest { private final SenderCaseRepository senderCaseRepository = mock(SenderCaseRepository.class); private final MessageBus messageBus = mock(MessageBus.class); private final ProjectConverter projectConverter = mock(ProjectConverter.class); - private final ProjectNotificationValidator projectNotificationValidator = new ProjectNotificationValidator( - senderCaseRepository); + private final ProjectNotificationValidator projectNotificationValidator = + new ProjectNotificationValidator(senderCaseRepository); - private final CreateProjectNotificationHandlerImpl service = new CreateProjectNotificationHandlerImpl( - senderCaseRepository, messageBus, - projectConverter, projectNotificationValidator); + private final CreateProjectNotificationHandlerImpl service = + new CreateProjectNotificationHandlerImpl(senderCaseRepository, messageBus, projectConverter, + projectNotificationValidator + ); private SenderCaseDTO createNotificationRQ; private Project project; @@ -91,48 +92,40 @@ public void createNotificationWithExistingRuleNameTest() { SenderCase existingSenderCase = mock(SenderCase.class); when(senderCaseRepository.findByProjectIdAndRuleNameIgnoreCase(DEFAULT_PROJECT_ID, - DEFAULT_RULE_NAME)) - .thenReturn(Optional.of(existingSenderCase)); - - assertEquals( - assertThrows(ReportPortalException.class, - () -> service.createNotification(project, createNotificationRQ, rpUser) - ).getMessage(), - formattedSupplier(RESOURCE_ALREADY_EXISTS.getDescription(), - createNotificationRQ.getRuleName()).get() - ); + DEFAULT_RULE_NAME + )).thenReturn(Optional.of(existingSenderCase)); + + assertEquals(assertThrows(ReportPortalException.class, + () -> service.createNotification(project, createNotificationRQ, rpUser) + ).getMessage(), formattedSupplier(RESOURCE_ALREADY_EXISTS.getDescription(), + createNotificationRQ.getRuleName() + ).get()); } @Test public void createNotificationWithNonExistingSendCaseTest() { createNotificationRQ.setSendCase("NonExistingSendCase"); - assertEquals( - assertThrows(ReportPortalException.class, - () -> service.createNotification(project, createNotificationRQ, rpUser) - ).getMessage(), - formattedSupplier(BAD_REQUEST_ERROR.getDescription(), - createNotificationRQ.getSendCase()).get() - ); + assertEquals(assertThrows(ReportPortalException.class, + () -> service.createNotification(project, createNotificationRQ, rpUser) + ).getMessage(), formattedSupplier(BAD_REQUEST_ERROR.getDescription(), + createNotificationRQ.getSendCase() + ).get()); } @Test public void createNotificationWithNullOrEmptyRecipientsTest() { createNotificationRQ.setRecipients(null); - assertTrue( - assertThrows(ReportPortalException.class, - () -> service.createNotification(project, createNotificationRQ, rpUser)) - .getMessage().contains("Recipients list should not be null") - ); + assertTrue(assertThrows(ReportPortalException.class, + () -> service.createNotification(project, createNotificationRQ, rpUser) + ).getMessage().contains("Recipients list should not be null")); createNotificationRQ.setRecipients(Collections.emptyList()); - assertTrue( - assertThrows(ReportPortalException.class, - () -> service.createNotification(project, createNotificationRQ, rpUser)) - .getMessage().contains("Empty recipients list for email case") - ); + assertTrue(assertThrows(ReportPortalException.class, + () -> service.createNotification(project, createNotificationRQ, rpUser) + ).getMessage().contains("Empty recipients list for email case")); } @Test @@ -156,11 +149,9 @@ public void createNotificationWithDuplicateContentButWithDifferentRuleNameTest() when(senderCaseRepository.findAllByProjectId(DEFAULT_PROJECT_ID)).thenReturn( Collections.singletonList(dupeCreateNotificationRQ)); - assertTrue( - assertThrows(ReportPortalException.class, - () -> service.createNotification(project, createNotificationRQ, rpUser)) - .getMessage().contains("Project email settings contain duplicate cases") - ); + assertTrue(assertThrows(ReportPortalException.class, + () -> service.createNotification(project, createNotificationRQ, rpUser) + ).getMessage().contains("Project email settings contain duplicate cases")); } } diff --git a/src/test/java/com/epam/ta/reportportal/core/project/settings/notification/GetProjectNotificationsHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/project/settings/notification/GetProjectNotificationsHandlerImplTest.java index 053a78687a..c9587ae914 100644 --- a/src/test/java/com/epam/ta/reportportal/core/project/settings/notification/GetProjectNotificationsHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/project/settings/notification/GetProjectNotificationsHandlerImplTest.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.dao.SenderCaseRepository; import com.epam.ta.reportportal.entity.enums.LogicalOperator; import com.epam.ta.reportportal.entity.project.email.SenderCase; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; import java.util.List; import org.junit.jupiter.api.Test; @@ -60,8 +60,8 @@ public void getProjectNotificationsTest() { when(senderCaseRepository.findAllByProjectId(DEFAULT_PROJECT_ID)).thenReturn( List.of(senderCase1, senderCase2)); - List result = getProjectNotificationsHandler.getProjectNotifications( - DEFAULT_PROJECT_ID); + List result = + getProjectNotificationsHandler.getProjectNotifications(DEFAULT_PROJECT_ID); assertEquals(2, result.size()); } } diff --git a/src/test/java/com/epam/ta/reportportal/core/project/settings/notification/UpdateProjectNotificationHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/project/settings/notification/UpdateProjectNotificationHandlerImplTest.java index 6dc76d2921..61418dd2b1 100644 --- a/src/test/java/com/epam/ta/reportportal/core/project/settings/notification/UpdateProjectNotificationHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/project/settings/notification/UpdateProjectNotificationHandlerImplTest.java @@ -34,9 +34,9 @@ import com.epam.ta.reportportal.entity.project.email.LaunchAttributeRule; import com.epam.ta.reportportal.entity.project.email.SenderCase; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; import com.epam.ta.reportportal.ws.converter.converters.ProjectConverter; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; import com.google.common.collect.Sets; import java.util.Collections; import java.util.List; @@ -56,12 +56,13 @@ class UpdateProjectNotificationHandlerImplTest { private final SenderCaseRepository senderCaseRepository = mock(SenderCaseRepository.class); private final MessageBus messageBus = mock(MessageBus.class); private final ProjectConverter projectConverter = mock(ProjectConverter.class); - private final ProjectNotificationValidator projectNotificationValidator = new ProjectNotificationValidator( - senderCaseRepository); + private final ProjectNotificationValidator projectNotificationValidator = + new ProjectNotificationValidator(senderCaseRepository); - private final UpdateProjectNotificationHandlerImpl service = new UpdateProjectNotificationHandlerImpl( - senderCaseRepository, messageBus, - projectConverter, projectNotificationValidator); + private final UpdateProjectNotificationHandlerImpl service = + new UpdateProjectNotificationHandlerImpl(senderCaseRepository, messageBus, projectConverter, + projectNotificationValidator + ); private SenderCaseDTO updateNotificationRQ; private Project project; @@ -90,11 +91,9 @@ public void beforeEach() { @Test public void updateNonExistingNotificationTest() { - Assertions.assertTrue( - assertThrows(ReportPortalException.class, - () -> service.updateNotification(project, updateNotificationRQ, rpUser)) - .getMessage().contains("Did you use correct Notification ID?") - ); + Assertions.assertTrue(assertThrows(ReportPortalException.class, + () -> service.updateNotification(project, updateNotificationRQ, rpUser) + ).getMessage().contains("Did you use correct Notification ID?")); } @Test @@ -106,11 +105,9 @@ public void updateNotificationButWithDifferentProjectTest() { when(sc.getProject()).thenReturn(scProject); when(senderCaseRepository.findById(any())).thenReturn(Optional.of(sc)); - Assertions.assertTrue( - assertThrows(ReportPortalException.class, - () -> service.updateNotification(project, updateNotificationRQ, rpUser)) - .getMessage().contains("Did you use correct Notification ID?") - ); + Assertions.assertTrue(assertThrows(ReportPortalException.class, + () -> service.updateNotification(project, updateNotificationRQ, rpUser) + ).getMessage().contains("Did you use correct Notification ID?")); } @Test @@ -123,11 +120,9 @@ public void updateNotificationWithNonExistingSendCaseTest() { when(senderCaseRepository.findById(any())).thenReturn(Optional.of(sc)); updateNotificationRQ.setSendCase("NonExistingSendCase"); - Assertions.assertTrue( - assertThrows(ReportPortalException.class, - () -> service.updateNotification(project, updateNotificationRQ, rpUser)) - .getMessage().contains(updateNotificationRQ.getSendCase()) - ); + Assertions.assertTrue(assertThrows(ReportPortalException.class, + () -> service.updateNotification(project, updateNotificationRQ, rpUser) + ).getMessage().contains(updateNotificationRQ.getSendCase())); } @Test @@ -141,17 +136,15 @@ public void updateNotificationWithNullOrEmptyRecipientsTest() { updateNotificationRQ.setRecipients(null); String s = assertThrows(ReportPortalException.class, - () -> service.updateNotification(project, updateNotificationRQ, rpUser)) - .getMessage(); + () -> service.updateNotification(project, updateNotificationRQ, rpUser) + ).getMessage(); Assertions.assertTrue(s.contains("Recipients list should not be null")); updateNotificationRQ.setRecipients(Collections.emptyList()); - Assertions.assertTrue( - assertThrows(ReportPortalException.class, - () -> service.updateNotification(project, updateNotificationRQ, rpUser)) - .getMessage().contains("Empty recipients list for email case") - ); + Assertions.assertTrue(assertThrows(ReportPortalException.class, + () -> service.updateNotification(project, updateNotificationRQ, rpUser) + ).getMessage().contains("Empty recipients list for email case")); } @Test @@ -192,11 +185,9 @@ public void updateNotificationWithDuplicateContentButWithDifferentRuleNameTest() when(senderCaseRepository.findAllByProjectId(DEFAULT_PROJECT_ID)).thenReturn( List.of(modelForUpdate, dupeUpdateNotification)); - assertTrue( - assertThrows(ReportPortalException.class, - () -> service.updateNotification(project, updateNotificationRQ, rpUser)) - .getMessage().contains("Project email settings contain duplicate cases") - ); + assertTrue(assertThrows(ReportPortalException.class, + () -> service.updateNotification(project, updateNotificationRQ, rpUser) + ).getMessage().contains("Project email settings contain duplicate cases")); } } diff --git a/src/test/java/com/epam/ta/reportportal/core/user/impl/CreateUserHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/user/impl/CreateUserHandlerImplTest.java index 0029766b77..2a688d7952 100644 --- a/src/test/java/com/epam/ta/reportportal/core/user/impl/CreateUserHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/user/impl/CreateUserHandlerImplTest.java @@ -31,7 +31,6 @@ import static org.mockito.Mockito.when; import com.epam.ta.reportportal.commons.ReportPortalUser; -import com.epam.ta.reportportal.core.events.activity.ChangeUserTypeEvent; import com.epam.ta.reportportal.core.events.activity.CreateInvitationLinkEvent; import com.epam.ta.reportportal.core.integration.GetIntegrationHandler; import com.epam.ta.reportportal.core.project.GetProjectHandler; @@ -45,10 +44,10 @@ import com.epam.ta.reportportal.entity.user.UserCreationBid; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQ; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQConfirm; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQFull; +import com.epam.ta.reportportal.model.user.CreateUserRQ; +import com.epam.ta.reportportal.model.user.CreateUserRQConfirm; +import com.epam.ta.reportportal.model.user.CreateUserRQFull; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Optional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -89,8 +88,8 @@ class CreateUserHandlerImplTest { @Test void createByNotExistedAdmin() { - final ReportPortalUser rpUser = getRpUser("admin", UserRole.ADMINISTRATOR, - ProjectRole.PROJECT_MANAGER, 1L); + final ReportPortalUser rpUser = + getRpUser("admin", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); when(userRepository.findRawById(rpUser.getUserId())).thenReturn(Optional.empty()); final ReportPortalException exception = assertThrows(ReportPortalException.class, @@ -101,8 +100,8 @@ void createByNotExistedAdmin() { @Test void createByNotAdmin() { - final ReportPortalUser rpUser = getRpUser("admin", UserRole.ADMINISTRATOR, - ProjectRole.PROJECT_MANAGER, 1L); + final ReportPortalUser rpUser = + getRpUser("admin", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); User user = new User(); user.setRole(UserRole.USER); when(userRepository.findRawById(1L)).thenReturn(Optional.of(user)); @@ -118,8 +117,8 @@ void createByNotAdmin() { @Test void createByAdminUserAlreadyExists() { - final ReportPortalUser rpUser = getRpUser("admin", UserRole.ADMINISTRATOR, - ProjectRole.PROJECT_MANAGER, 1L); + final ReportPortalUser rpUser = + getRpUser("admin", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); User creator = new User(); creator.setRole(UserRole.ADMINISTRATOR); @@ -132,13 +131,14 @@ void createByAdminUserAlreadyExists() { () -> handler.createUserByAdmin(request, rpUser, "url") ); assertEquals("User with 'login='new_user'' already exists. You couldn't create the duplicate.", - exception.getMessage()); + exception.getMessage() + ); } @Test void createByAdminWithIncorrectName() { - final ReportPortalUser rpUser = getRpUser("admin", UserRole.ADMINISTRATOR, - ProjectRole.PROJECT_MANAGER, 1L); + final ReportPortalUser rpUser = + getRpUser("admin", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); User creator = new User(); creator.setRole(UserRole.ADMINISTRATOR); doReturn(Optional.of(creator)).when(userRepository).findRawById(rpUser.getUserId()); @@ -150,13 +150,14 @@ void createByAdminWithIncorrectName() { () -> handler.createUserByAdmin(request, rpUser, "url") ); assertEquals("Incorrect Request. Username '#$$/' consists only of special characters", - exception.getMessage()); + exception.getMessage() + ); } @Test void createByAdminWithIncorrectEmail() { - final ReportPortalUser rpUser = getRpUser("admin", UserRole.ADMINISTRATOR, - ProjectRole.PROJECT_MANAGER, 1L); + final ReportPortalUser rpUser = + getRpUser("admin", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); User creator = new User(); creator.setRole(UserRole.ADMINISTRATOR); doReturn(Optional.of(creator)).when(userRepository).findRawById(rpUser.getUserId()); @@ -170,13 +171,14 @@ void createByAdminWithIncorrectEmail() { ); assertEquals( "Error in handled Request. Please, check specified parameters: 'email='incorrect@email''", - exception.getMessage()); + exception.getMessage() + ); } @Test void createByAdminWithExistedEmail() { - final ReportPortalUser rpUser = getRpUser("admin", UserRole.ADMINISTRATOR, - ProjectRole.PROJECT_MANAGER, 1L); + final ReportPortalUser rpUser = + getRpUser("admin", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); User creator = new User(); creator.setRole(UserRole.ADMINISTRATOR); doReturn(Optional.of(creator)).when(userRepository).findRawById(rpUser.getUserId()); @@ -191,13 +193,14 @@ void createByAdminWithExistedEmail() { ); assertEquals( "User with 'email='correct@domain.com'' already exists. You couldn't create the duplicate.", - exception.getMessage()); + exception.getMessage() + ); } @Test void createByAdminWithExistedEmailUppercase() { - final ReportPortalUser rpUser = getRpUser("admin", UserRole.ADMINISTRATOR, - ProjectRole.PROJECT_MANAGER, 1L); + final ReportPortalUser rpUser = + getRpUser("admin", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); User creator = new User(); creator.setRole(UserRole.ADMINISTRATOR); doReturn(Optional.of(creator)).when(userRepository).findRawById(rpUser.getUserId()); @@ -212,13 +215,14 @@ void createByAdminWithExistedEmailUppercase() { ); assertEquals( "User with 'email='CORRECT@domain.com'' already exists. You couldn't create the duplicate.", - exception.getMessage()); + exception.getMessage() + ); } @Test void createUserBid() { - final ReportPortalUser rpUser = getRpUser("admin", UserRole.ADMINISTRATOR, ProjectRole.MEMBER, - 1L); + final ReportPortalUser rpUser = + getRpUser("admin", UserRole.ADMINISTRATOR, ProjectRole.MEMBER, 1L); final String projectName = "test_project"; final String email = "email@mail.com"; final String role = ProjectRole.MEMBER.name(); @@ -242,8 +246,8 @@ void createUserBid() { handler.createUserBid(request, rpUser, "emailUrl"); - final ArgumentCaptor bidCaptor = ArgumentCaptor.forClass( - UserCreationBid.class); + final ArgumentCaptor bidCaptor = + ArgumentCaptor.forClass(UserCreationBid.class); verify(userCreationBidRepository, times(1)).save(bidCaptor.capture()); final UserCreationBid bid = bidCaptor.getValue(); @@ -270,7 +274,8 @@ void CreateUserBidOnNotExistedProject() { () -> handler.createUserBid(request, rpUser, "emailUrl") ); assertEquals("Project 'not_exists' not found. Did you use correct project name?", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -283,7 +288,8 @@ void createUserWithoutBid() { ); assertEquals( "Incorrect Request. Impossible to register user. UUID expired or already registered.", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -296,10 +302,11 @@ void createAlreadyExistedUser() { final CreateUserRQConfirm request = new CreateUserRQConfirm(); request.setLogin("test"); - final ReportPortalException exception = assertThrows(ReportPortalException.class, - () -> handler.createUser(request, "uuid")); + final ReportPortalException exception = + assertThrows(ReportPortalException.class, () -> handler.createUser(request, "uuid")); assertEquals("User with 'login='test'' already exists. You couldn't create the duplicate.", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -312,10 +319,11 @@ public void createUserWithIncorrectLogin() { final CreateUserRQConfirm request = new CreateUserRQConfirm(); request.setLogin("##$%/"); - final ReportPortalException exception = assertThrows(ReportPortalException.class, - () -> handler.createUser(request, "uuid")); + final ReportPortalException exception = + assertThrows(ReportPortalException.class, () -> handler.createUser(request, "uuid")); assertEquals("Incorrect Request. Username '##$%/' consists only of special characters", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -329,11 +337,12 @@ void createUserWithIncorrectEmail() { final CreateUserRQConfirm request = new CreateUserRQConfirm(); request.setLogin("test"); request.setEmail("incorrect@domain"); - final ReportPortalException exception = assertThrows(ReportPortalException.class, - () -> handler.createUser(request, "uuid")); + final ReportPortalException exception = + assertThrows(ReportPortalException.class, () -> handler.createUser(request, "uuid")); assertEquals( "Error in handled Request. Please, check specified parameters: 'email='incorrect@domain''", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -348,10 +357,11 @@ void createUserWithExistedEmail() { final CreateUserRQConfirm request = new CreateUserRQConfirm(); request.setLogin("test"); request.setEmail("email@domain.com"); - final ReportPortalException exception = assertThrows(ReportPortalException.class, - () -> handler.createUser(request, "uuid")); + final ReportPortalException exception = + assertThrows(ReportPortalException.class, () -> handler.createUser(request, "uuid")); assertEquals( "User with 'email='email@domain.com'' already exists. You couldn't create the duplicate.", - exception.getMessage()); + exception.getMessage() + ); } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/core/user/impl/EditUserHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/user/impl/EditUserHandlerImplTest.java index 06a66b36f1..a3302ad5b8 100644 --- a/src/test/java/com/epam/ta/reportportal/core/user/impl/EditUserHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/user/impl/EditUserHandlerImplTest.java @@ -16,6 +16,15 @@ package com.epam.ta.reportportal.core.user.impl; +import static com.epam.ta.reportportal.ReportPortalUserUtil.getRpUser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.epam.ta.reportportal.core.events.activity.ChangeUserTypeEvent; import com.epam.ta.reportportal.dao.ProjectRepository; import com.epam.ta.reportportal.dao.UserRepository; @@ -24,8 +33,9 @@ import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.entity.user.UserType; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.user.ChangePasswordRQ; -import com.epam.ta.reportportal.ws.model.user.EditUserRQ; +import com.epam.ta.reportportal.model.user.ChangePasswordRQ; +import com.epam.ta.reportportal.model.user.EditUserRQ; +import java.util.Optional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -35,18 +45,6 @@ import org.springframework.mock.web.MockMultipartFile; import org.springframework.security.crypto.password.PasswordEncoder; -import java.util.Optional; - -import static com.epam.ta.reportportal.ReportPortalUserUtil.getRpUser; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - /** * @author Ihar Kahadouski */ @@ -84,18 +82,20 @@ void uploadOversizePhoto() { final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.uploadPhoto("test", - new MockMultipartFile("photo", new byte[1024 * 1024 + 10])) + new MockMultipartFile("photo", new byte[1024 * 1024 + 10]) + ) ); assertEquals("Binary data cannot be saved. Image size should be less than 1 mb", - exception.getMessage()); + exception.getMessage() + ); } @Test void deleteNotExistUserPhoto() { when(userRepository.findByLogin("not_exist")).thenReturn(Optional.empty()); - final ReportPortalException exception = assertThrows(ReportPortalException.class, - () -> handler.deletePhoto("not_exist")); + final ReportPortalException exception = + assertThrows(ReportPortalException.class, () -> handler.deletePhoto("not_exist")); assertEquals("User 'not_exist' not found.", exception.getMessage()); } @@ -106,10 +106,11 @@ void deleteExternalUserPhoto() { user.setUserType(UserType.UPSA); when(userRepository.findByLogin("test")).thenReturn(Optional.of(user)); - final ReportPortalException exception = assertThrows(ReportPortalException.class, - () -> handler.deletePhoto("test")); + final ReportPortalException exception = + assertThrows(ReportPortalException.class, () -> handler.deletePhoto("test")); assertEquals("You do not have enough permissions. Unable to change photo for external user", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -118,7 +119,8 @@ void changeNotExistUserPassword() { final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.changePassword(getRpUser("not_exist", UserRole.USER, ProjectRole.MEMBER, 1L), - new ChangePasswordRQ()) + new ChangePasswordRQ() + ) ); assertEquals("User 'not_exist' not found.", exception.getMessage()); } @@ -132,10 +134,12 @@ void changeExternalUserPassword() { final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.changePassword(getRpUser("test", UserRole.USER, ProjectRole.MEMBER, 1L), - new ChangePasswordRQ()) + new ChangePasswordRQ() + ) ); assertEquals("Forbidden operation. Impossible to change password for external users.", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -151,10 +155,12 @@ void changePasswordWithIncorrectOldPassword() { final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.changePassword(getRpUser("test", UserRole.USER, ProjectRole.MEMBER, 1L), - changePasswordRQ) + changePasswordRQ + ) ); assertEquals("Forbidden operation. Old password not match with stored.", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -163,7 +169,8 @@ void editNotExistUser() { final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.editUser("not_exist", new EditUserRQ(), - getRpUser("not_exist", UserRole.USER, ProjectRole.MEMBER, 1L)) + getRpUser("not_exist", UserRole.USER, ProjectRole.MEMBER, 1L) + ) ); assertEquals("User 'not_exist' not found.", exception.getMessage()); } @@ -178,7 +185,8 @@ void editUserWithIncorrectRole() { final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.editUser("test", editUserRQ, - getRpUser("not_exist", UserRole.ADMINISTRATOR, ProjectRole.MEMBER, 1L)) + getRpUser("not_exist", UserRole.ADMINISTRATOR, ProjectRole.MEMBER, 1L) + ) ); assertEquals( "Error in handled Request. Please, check specified parameters: 'Incorrect specified Account Role parameter.'", @@ -198,7 +206,8 @@ void verifyChangeTypePublishOnEdit() { //when handler.editUser("test", editUserRQ, - getRpUser("admin", UserRole.ADMINISTRATOR, ProjectRole.MEMBER, 1L)); + getRpUser("admin", UserRole.ADMINISTRATOR, ProjectRole.MEMBER, 1L) + ); //then verify(eventPublisher, times(1)).publishEvent(isA(ChangeUserTypeEvent.class)); @@ -214,10 +223,12 @@ void changeExternalUserEmail() { final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.editUser("test", editUserRQ, - getRpUser("not_exist", UserRole.USER, ProjectRole.MEMBER, 1L)) + getRpUser("not_exist", UserRole.USER, ProjectRole.MEMBER, 1L) + ) ); assertEquals("You do not have enough permissions. Unable to change email for external user", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -230,7 +241,8 @@ void editUserWithIncorrectEmail() { final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.editUser("test", editUserRQ, - getRpUser("not_exist", UserRole.USER, ProjectRole.MEMBER, 1L)) + getRpUser("not_exist", UserRole.USER, ProjectRole.MEMBER, 1L) + ) ); assertEquals( "Error in handled Request. Please, check specified parameters: ' wrong email: incorrect#domain.com'", @@ -249,11 +261,13 @@ void editUserWithAlreadyExistedEmail() { final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.editUser("test", editUserRQ, - getRpUser("not_exist", UserRole.USER, ProjectRole.MEMBER, 1L)) + getRpUser("not_exist", UserRole.USER, ProjectRole.MEMBER, 1L) + ) ); assertEquals( "User with 'existed@domain.com' already exists. You couldn't create the duplicate.", - exception.getMessage()); + exception.getMessage() + ); } @Test @@ -266,9 +280,12 @@ void editExternalUserFullName() { final ReportPortalException exception = assertThrows(ReportPortalException.class, () -> handler.editUser("test", editUserRQ, - getRpUser("not_exist", UserRole.USER, ProjectRole.MEMBER, 1L)) + getRpUser("not_exist", UserRole.USER, ProjectRole.MEMBER, 1L) + ) + ); + assertEquals( + "You do not have enough permissions. Unable to change full name for external user", + exception.getMessage() ); - assertEquals("You do not have enough permissions. Unable to change full name for external user", - exception.getMessage()); } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/core/user/impl/GetUserHandlerImplTest.java b/src/test/java/com/epam/ta/reportportal/core/user/impl/GetUserHandlerImplTest.java index ba43a833ee..b385f0c0c3 100644 --- a/src/test/java/com/epam/ta/reportportal/core/user/impl/GetUserHandlerImplTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/user/impl/GetUserHandlerImplTest.java @@ -31,8 +31,8 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.YesNoRS; -import com.epam.ta.reportportal.ws.model.user.UserBidRS; +import com.epam.ta.reportportal.model.YesNoRS; +import com.epam.ta.reportportal.model.user.UserBidRS; import java.util.Optional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -59,7 +59,8 @@ class GetUserHandlerImplTest { void getNotExistedUserByUsername() { when(userRepository.findByLogin("not_exist")).thenReturn(Optional.empty()); - final ReportPortalException exception = assertThrows(ReportPortalException.class, + final ReportPortalException exception = assertThrows( + ReportPortalException.class, () -> handler.getUser("not_exist", getRpUser("test", UserRole.USER, ProjectRole.MEMBER, 1L)) ); assertEquals("User 'not_exist' not found.", exception.getMessage()); @@ -69,7 +70,8 @@ void getNotExistedUserByUsername() { void getNotExistedUserByLoggedInUser() { when(userRepository.findByLogin("not_exist")).thenReturn(Optional.empty()); - final ReportPortalException exception = assertThrows(ReportPortalException.class, + final ReportPortalException exception = assertThrows( + ReportPortalException.class, () -> handler.getUser(getRpUser("not_exist", UserRole.USER, ProjectRole.MEMBER, 1L)) ); assertEquals("User 'not_exist' not found.", exception.getMessage()); diff --git a/src/test/java/com/epam/ta/reportportal/core/widget/content/loader/util/healthcheck/HealthCheckTableReadyContentResolverTest.java b/src/test/java/com/epam/ta/reportportal/core/widget/content/loader/util/healthcheck/HealthCheckTableReadyContentResolverTest.java index 0eededc3c2..b1bbf43c7d 100644 --- a/src/test/java/com/epam/ta/reportportal/core/widget/content/loader/util/healthcheck/HealthCheckTableReadyContentResolverTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/widget/content/loader/util/healthcheck/HealthCheckTableReadyContentResolverTest.java @@ -13,10 +13,10 @@ import com.epam.ta.reportportal.dao.WidgetContentRepository; import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.entity.widget.content.healthcheck.HealthCheckTableContent; +import com.epam.ta.reportportal.model.widget.ContentParameters; +import com.epam.ta.reportportal.model.widget.SortEntry; +import com.epam.ta.reportportal.model.widget.WidgetRQ; import com.epam.ta.reportportal.ws.converter.builders.WidgetBuilder; -import com.epam.ta.reportportal.ws.model.widget.ContentParameters; -import com.epam.ta.reportportal.ws.model.widget.SortEntry; -import com.epam.ta.reportportal.ws.model.widget.WidgetRQ; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import java.util.ArrayList; @@ -33,14 +33,12 @@ */ public class HealthCheckTableReadyContentResolverTest { - private final WidgetContentRepository widgetContentRepository = mock( - WidgetContentRepository.class); + private final WidgetContentRepository widgetContentRepository = + mock(WidgetContentRepository.class); private final ObjectMapper objectMapper = new ObjectMapper(); - private final HealthCheckTableReadyContentLoader contentResolver = new HealthCheckTableReadyContentLoader( - widgetContentRepository, - objectMapper - ); + private final HealthCheckTableReadyContentLoader contentResolver = + new HealthCheckTableReadyContentLoader(widgetContentRepository, objectMapper); @Test void getContentTest() { @@ -62,10 +60,8 @@ void getContentTest() { SortEntry sortEntry = new SortEntry(); sortEntry.setSortingColumn("passingRate"); - Widget widget = new WidgetBuilder().addWidgetRq(widgetRQ) - .addOption("viewName", "name") - .addOption("sort", sortEntry) - .addOption(ATTRIBUTE_KEYS, Lists.newArrayList("k1", "k2")) + Widget widget = new WidgetBuilder().addWidgetRq(widgetRQ).addOption("viewName", "name") + .addOption("sort", sortEntry).addOption(ATTRIBUTE_KEYS, Lists.newArrayList("k1", "k2")) .get(); HealthCheckTableContent content = new HealthCheckTableContent(); diff --git a/src/test/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ComponentHealthCheckContentValidatorTest.java b/src/test/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ComponentHealthCheckContentValidatorTest.java index 6de71ce07f..ed9db4b8b0 100644 --- a/src/test/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ComponentHealthCheckContentValidatorTest.java +++ b/src/test/java/com/epam/ta/reportportal/core/widget/content/updater/validator/ComponentHealthCheckContentValidatorTest.java @@ -1,6 +1,7 @@ package com.epam.ta.reportportal.core.widget.content.updater.validator; import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.ATTRIBUTE_KEYS; +import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.EXCLUDE_SKIPPED; import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.MIN_PASSING_RATE; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -39,7 +40,7 @@ public void testValidateWithException() { ) ); - String expectedMessage = "Current level key should be not blank"; + String expectedMessage = "Unable to load widget content. Widget properties contain errors: Exclude skipped tests option was not specified"; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); @@ -58,6 +59,7 @@ private Map getWidgetOptionsContent() { content.put(ATTRIBUTE_KEYS, Lists.newArrayList("k1", "k2")); content.put(MIN_PASSING_RATE, 50); + content.put(EXCLUDE_SKIPPED, true); return content; diff --git a/src/test/java/com/epam/ta/reportportal/util/ItemInfoUtilsTest.java b/src/test/java/com/epam/ta/reportportal/util/ItemInfoUtilsTest.java index 7efc44eb87..492caa9453 100644 --- a/src/test/java/com/epam/ta/reportportal/util/ItemInfoUtilsTest.java +++ b/src/test/java/com/epam/ta/reportportal/util/ItemInfoUtilsTest.java @@ -20,7 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.epam.ta.reportportal.entity.ItemAttribute; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; diff --git a/src/test/java/com/epam/ta/reportportal/util/TestProjectExtractor.java b/src/test/java/com/epam/ta/reportportal/util/TestProjectExtractor.java index 25e803fdd6..e6dee11f75 100644 --- a/src/test/java/com/epam/ta/reportportal/util/TestProjectExtractor.java +++ b/src/test/java/com/epam/ta/reportportal/util/TestProjectExtractor.java @@ -4,7 +4,7 @@ import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import java.util.Optional; public class TestProjectExtractor { diff --git a/src/test/java/com/epam/ta/reportportal/util/email/EmailRulesValidatorTest.java b/src/test/java/com/epam/ta/reportportal/util/email/EmailRulesValidatorTest.java index 1624df0b57..ed46b6aea5 100644 --- a/src/test/java/com/epam/ta/reportportal/util/email/EmailRulesValidatorTest.java +++ b/src/test/java/com/epam/ta/reportportal/util/email/EmailRulesValidatorTest.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.entity.user.ProjectUser; import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; import com.google.common.collect.Sets; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/BugTrackingSystemControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/BugTrackingSystemControllerTest.java index b10ae1db6c..33e56e71ea 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/BugTrackingSystemControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/BugTrackingSystemControllerTest.java @@ -17,7 +17,7 @@ package com.epam.ta.reportportal.ws.controller; import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.INCORRECT_REQUEST_MESSAGE; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @@ -29,13 +29,13 @@ import com.epam.reportportal.extension.bugtracking.BtsExtension; import com.epam.ta.reportportal.entity.integration.Integration; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.ErrorRS; +import com.epam.ta.reportportal.ws.reporting.ErrorRS; import com.epam.ta.reportportal.ws.model.externalsystem.AllowedValue; -import com.epam.ta.reportportal.ws.model.externalsystem.BtsConnectionTestRQ; +import com.epam.ta.reportportal.model.externalsystem.BtsConnectionTestRQ; import com.epam.ta.reportportal.ws.model.externalsystem.PostFormField; import com.epam.ta.reportportal.ws.model.externalsystem.PostTicketRQ; import com.epam.ta.reportportal.ws.model.externalsystem.Ticket; -import com.epam.ta.reportportal.ws.model.integration.IntegrationRQ; +import com.epam.ta.reportportal.model.integration.IntegrationRQ; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.common.collect.Maps; diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/DashboardControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/DashboardControllerTest.java index ee6cf46e75..c6db107b8a 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/DashboardControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/DashboardControllerTest.java @@ -16,106 +16,117 @@ package com.epam.ta.reportportal.ws.controller; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import com.epam.ta.reportportal.dao.DashboardRepository; import com.epam.ta.reportportal.entity.dashboard.Dashboard; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.Position; +import com.epam.ta.reportportal.model.Size; +import com.epam.ta.reportportal.model.dashboard.AddWidgetRq; +import com.epam.ta.reportportal.model.dashboard.CreateDashboardRQ; +import com.epam.ta.reportportal.model.dashboard.DashboardResource; +import com.epam.ta.reportportal.model.dashboard.UpdateDashboardRQ; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.Position; -import com.epam.ta.reportportal.ws.model.Size; -import com.epam.ta.reportportal.ws.model.dashboard.AddWidgetRq; -import com.epam.ta.reportportal.ws.model.dashboard.CreateDashboardRQ; -import com.epam.ta.reportportal.ws.model.dashboard.DashboardResource; -import com.epam.ta.reportportal.ws.model.dashboard.UpdateDashboardRQ; import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Optional; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.servlet.MvcResult; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; -import static org.springframework.http.MediaType.APPLICATION_JSON; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - /** * @author Ihar Kahadouski */ @Sql("/db/shareable/shareable-fill.sql") class DashboardControllerTest extends BaseMvcTest { - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private DashboardRepository dashboardRepository; - - @Test - void createDashboardPositive() throws Exception { - CreateDashboardRQ createDashboardRQ = new CreateDashboardRQ(); - createDashboardRQ.setName("dashboard"); - createDashboardRQ.setDescription("description"); - final MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/dashboard").with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(createDashboardRQ)) - .contentType(APPLICATION_JSON)).andExpect(status().isCreated()).andReturn(); - final EntryCreatedRS entryCreatedRS = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), EntryCreatedRS.class); - final Optional dashboardOptional = dashboardRepository.findById(entryCreatedRS.getId()); - assertTrue(dashboardOptional.isPresent()); - assertEquals("dashboard", dashboardOptional.get().getName()); - assertEquals("description", dashboardOptional.get().getDescription()); - } - - @Test - void getAllDashboardsPositive() throws Exception { - mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/dashboard").with(token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk()); - } - - @Test - void getDashboardPositive() throws Exception { - mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/dashboard/17").with(token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()); - } - - @Test - void updateDashboardPositive() throws Exception { - final UpdateDashboardRQ rq = new UpdateDashboardRQ(); - rq.setName("updated"); - rq.setDescription("updated"); - mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/dashboard/17").with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(rq)) - .contentType(APPLICATION_JSON)).andExpect(status().isOk()); - final Optional optionalDashboard = dashboardRepository.findById(17L); - assertTrue(optionalDashboard.isPresent()); - assertEquals("updated", optionalDashboard.get().getName()); - assertEquals("updated", optionalDashboard.get().getDescription()); - } - - @Test - void deleteDashboardPositive() throws Exception { - mockMvc.perform(delete(DEFAULT_PROJECT_BASE_URL + "/dashboard/17").with(token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()); - } - - @Test - void getSharedDashboardsNamesPositive() throws Exception { - mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/dashboard/shared").with(token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isBadRequest()); - } - - @Test - void removeWidget() throws Exception { - mockMvc.perform(delete(DEFAULT_PROJECT_BASE_URL + "/dashboard/18/10").with(token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()); - } - - @Test - void addWidget() throws Exception { - AddWidgetRq rq = new AddWidgetRq(); - rq.setAddWidget(new DashboardResource.WidgetObjectModel("kek", 10L, new Size(5, 5), new Position(0, 0))); - - mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/dashboard/17/add").with(token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(rq))).andExpect(status().isOk()); - } + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private DashboardRepository dashboardRepository; + + @Test + void createDashboardPositive() throws Exception { + CreateDashboardRQ createDashboardRQ = new CreateDashboardRQ(); + createDashboardRQ.setName("dashboard"); + createDashboardRQ.setDescription("description"); + final MvcResult mvcResult = mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + "/dashboard").with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(createDashboardRQ)) + .contentType(APPLICATION_JSON)).andExpect(status().isCreated()).andReturn(); + final EntryCreatedRS entryCreatedRS = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), EntryCreatedRS.class); + final Optional dashboardOptional = + dashboardRepository.findById(entryCreatedRS.getId()); + assertTrue(dashboardOptional.isPresent()); + assertEquals("dashboard", dashboardOptional.get().getName()); + assertEquals("description", dashboardOptional.get().getDescription()); + } + + @Test + void getAllDashboardsPositive() throws Exception { + mockMvc.perform( + get(DEFAULT_PROJECT_BASE_URL + "/dashboard").with(token(oAuthHelper.getDefaultToken()))) + .andExpect(status().isOk()); + } + + @Test + void getDashboardPositive() throws Exception { + mockMvc.perform( + get(DEFAULT_PROJECT_BASE_URL + "/dashboard/17").with(token(oAuthHelper.getDefaultToken()))) + .andExpect(status().isOk()); + } + + @Test + void updateDashboardPositive() throws Exception { + final UpdateDashboardRQ rq = new UpdateDashboardRQ(); + rq.setName("updated"); + rq.setDescription("updated"); + mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + "/dashboard/17").with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(rq)).contentType(APPLICATION_JSON)) + .andExpect(status().isOk()); + final Optional optionalDashboard = dashboardRepository.findById(17L); + assertTrue(optionalDashboard.isPresent()); + assertEquals("updated", optionalDashboard.get().getName()); + assertEquals("updated", optionalDashboard.get().getDescription()); + } + + @Test + void deleteDashboardPositive() throws Exception { + mockMvc.perform(delete(DEFAULT_PROJECT_BASE_URL + "/dashboard/17").with( + token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk()); + } + + @Test + void getSharedDashboardsNamesPositive() throws Exception { + mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/dashboard/shared").with( + token(oAuthHelper.getDefaultToken()))).andExpect(status().isBadRequest()); + } + + @Test + void removeWidget() throws Exception { + mockMvc.perform(delete(DEFAULT_PROJECT_BASE_URL + "/dashboard/18/10").with( + token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk()); + } + + @Test + void addWidget() throws Exception { + AddWidgetRq rq = new AddWidgetRq(); + rq.setAddWidget( + new DashboardResource.WidgetObjectModel("kek", 10L, new Size(5, 5), new Position(0, 0))); + + mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/dashboard/17/add").with( + token(oAuthHelper.getDefaultToken())).contentType(APPLICATION_JSON) + .content(objectMapper.writeValueAsBytes(rq))).andExpect(status().isOk()); + } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/DashboardControllerValidationTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/DashboardControllerValidationTest.java index e156cc1915..c4fcab35db 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/DashboardControllerValidationTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/DashboardControllerValidationTest.java @@ -24,7 +24,7 @@ import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.LONG_NAME_VALUE; import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.SHORT_NAME_VALUE; import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.WHITESPACES_NAME_VALUE; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.http.MediaType.APPLICATION_JSON; @@ -33,8 +33,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.ErrorRS; -import com.epam.ta.reportportal.ws.model.dashboard.CreateDashboardRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorRS; +import com.epam.ta.reportportal.model.dashboard.CreateDashboardRQ; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/IntegrationControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/IntegrationControllerTest.java index 29d87b1166..2227dfdf60 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/IntegrationControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/IntegrationControllerTest.java @@ -24,7 +24,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.integration.IntegrationRQ; +import com.epam.ta.reportportal.model.integration.IntegrationRQ; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.HashMap; import java.util.Map; diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/LaunchAsyncControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/LaunchAsyncControllerTest.java index 2ef618bcbd..fb5b7741e8 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/LaunchAsyncControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/LaunchAsyncControllerTest.java @@ -30,9 +30,9 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; -import com.epam.ta.reportportal.ws.model.launch.MergeLaunchesRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; +import com.epam.ta.reportportal.ws.reporting.MergeLaunchesRQ; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; import com.google.common.collect.Lists; import java.util.UUID; import javax.servlet.http.HttpServletRequest; @@ -70,93 +70,97 @@ class LaunchAsyncControllerTest { @Test void startLaunch() { - ReportPortalUser user = getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, - 1L); + ReportPortalUser user = + getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); StartLaunchRQ startLaunchRQ = new StartLaunchRQ(); - ArgumentCaptor userArgumentCaptor = ArgumentCaptor.forClass( - ReportPortalUser.class); - ArgumentCaptor projectDetailsArgumentCaptor = ArgumentCaptor.forClass( - ReportPortalUser.ProjectDetails.class); - ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.forClass( - StartLaunchRQ.class); + ArgumentCaptor userArgumentCaptor = + ArgumentCaptor.forClass(ReportPortalUser.class); + ArgumentCaptor projectDetailsArgumentCaptor = + ArgumentCaptor.forClass(ReportPortalUser.ProjectDetails.class); + ArgumentCaptor requestArgumentCaptor = + ArgumentCaptor.forClass(StartLaunchRQ.class); when(projectExtractor.extractProjectDetails(any(ReportPortalUser.class), - anyString())).thenReturn(user.getProjectDetails() - .get("test_project")); + anyString() + )).thenReturn(user.getProjectDetails().get("test_project")); launchAsyncController.startLaunch("test_project", startLaunchRQ, user); verify(startLaunchHandler).startLaunch(userArgumentCaptor.capture(), - projectDetailsArgumentCaptor.capture(), requestArgumentCaptor.capture()); + projectDetailsArgumentCaptor.capture(), requestArgumentCaptor.capture() + ); assertEquals(user, userArgumentCaptor.getValue()); assertEquals(user.getProjectDetails().get("test_project"), - projectDetailsArgumentCaptor.getValue()); + projectDetailsArgumentCaptor.getValue() + ); assertEquals(startLaunchRQ, requestArgumentCaptor.getValue()); } @Test void finishLaunch() { - ReportPortalUser user = getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, - 1L); + ReportPortalUser user = + getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); FinishExecutionRQ finishExecutionRQ = new FinishExecutionRQ(); String launchId = UUID.randomUUID().toString(); ArgumentCaptor launchIdArgumentCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.forClass( - FinishExecutionRQ.class); - ArgumentCaptor projectDetailsArgumentCaptor = ArgumentCaptor.forClass( - ReportPortalUser.ProjectDetails.class); - ArgumentCaptor userArgumentCaptor = ArgumentCaptor.forClass( - ReportPortalUser.class); + ArgumentCaptor requestArgumentCaptor = + ArgumentCaptor.forClass(FinishExecutionRQ.class); + ArgumentCaptor projectDetailsArgumentCaptor = + ArgumentCaptor.forClass(ReportPortalUser.ProjectDetails.class); + ArgumentCaptor userArgumentCaptor = + ArgumentCaptor.forClass(ReportPortalUser.class); ArgumentCaptor urlArgumentCaptor = ArgumentCaptor.forClass(String.class); when(projectExtractor.extractProjectDetails(any(ReportPortalUser.class), - anyString())).thenReturn(user.getProjectDetails() - .get("test_project")); + anyString() + )).thenReturn(user.getProjectDetails().get("test_project")); when(httpServletRequest.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080")); when(httpServletRequest.getHeaderNames()).thenReturn(new Enumerator<>(Lists.newArrayList())); launchAsyncController.finishLaunch("test_project", launchId, finishExecutionRQ, user, - httpServletRequest); - verify(finishLaunchHandler).finishLaunch( - launchIdArgumentCaptor.capture(), - requestArgumentCaptor.capture(), - projectDetailsArgumentCaptor.capture(), - userArgumentCaptor.capture(), - urlArgumentCaptor.capture()); + httpServletRequest + ); + verify(finishLaunchHandler).finishLaunch(launchIdArgumentCaptor.capture(), + requestArgumentCaptor.capture(), projectDetailsArgumentCaptor.capture(), + userArgumentCaptor.capture(), urlArgumentCaptor.capture() + ); assertEquals(user, userArgumentCaptor.getValue()); assertEquals(user.getProjectDetails().get("test_project"), - projectDetailsArgumentCaptor.getValue()); + projectDetailsArgumentCaptor.getValue() + ); assertEquals(finishExecutionRQ, requestArgumentCaptor.getValue()); } @Test void mergeLaunch() { - ReportPortalUser user = getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, - 1L); + ReportPortalUser user = + getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); MergeLaunchesRQ mergeLaunchesRQ = new MergeLaunchesRQ(); - ArgumentCaptor projectDetailsArgumentCaptor = ArgumentCaptor.forClass( - ReportPortalUser.ProjectDetails.class); - ArgumentCaptor userArgumentCaptor = ArgumentCaptor.forClass( - ReportPortalUser.class); - ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.forClass( - MergeLaunchesRQ.class); + ArgumentCaptor projectDetailsArgumentCaptor = + ArgumentCaptor.forClass(ReportPortalUser.ProjectDetails.class); + ArgumentCaptor userArgumentCaptor = + ArgumentCaptor.forClass(ReportPortalUser.class); + ArgumentCaptor requestArgumentCaptor = + ArgumentCaptor.forClass(MergeLaunchesRQ.class); when(projectExtractor.extractProjectDetails(any(ReportPortalUser.class), - anyString())).thenReturn(user.getProjectDetails() - .get("test_project")); + anyString() + )).thenReturn(user.getProjectDetails().get("test_project")); launchAsyncController.mergeLaunches("test_project", mergeLaunchesRQ, user); verify(mergeLaunchHandler).mergeLaunches(projectDetailsArgumentCaptor.capture(), - userArgumentCaptor.capture(), requestArgumentCaptor.capture()); + userArgumentCaptor.capture(), requestArgumentCaptor.capture() + ); assertEquals(user, userArgumentCaptor.getValue()); assertEquals(user.getProjectDetails().get("test_project"), - projectDetailsArgumentCaptor.getValue()); + projectDetailsArgumentCaptor.getValue() + ); assertEquals(mergeLaunchesRQ, requestArgumentCaptor.getValue()); } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/LaunchControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/LaunchControllerTest.java index 6b71d7fa7c..95ce0a8469 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/LaunchControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/LaunchControllerTest.java @@ -17,8 +17,8 @@ package com.epam.ta.reportportal.ws.controller; import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_PROJECT_ID; -import static com.epam.ta.reportportal.ws.model.launch.Mode.DEBUG; -import static com.epam.ta.reportportal.ws.model.launch.Mode.DEFAULT; +import static com.epam.ta.reportportal.ws.reporting.Mode.DEBUG; +import static com.epam.ta.reportportal.ws.reporting.Mode.DEFAULT; import static java.util.stream.Collectors.toMap; import static org.hamcrest.Matchers.hasSize; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -39,18 +39,18 @@ import com.epam.ta.reportportal.entity.enums.StatusEnum; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.BulkRQ; +import com.epam.ta.reportportal.model.DeleteBulkRQ; +import com.epam.ta.reportportal.model.launch.AnalyzeLaunchRQ; +import com.epam.ta.reportportal.model.launch.UpdateLaunchRQ; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.BulkInfoUpdateRQ; -import com.epam.ta.reportportal.ws.model.BulkRQ; -import com.epam.ta.reportportal.ws.model.DeleteBulkRQ; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributesRQ; -import com.epam.ta.reportportal.ws.model.attribute.UpdateItemAttributeRQ; -import com.epam.ta.reportportal.ws.model.launch.AnalyzeLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.MergeLaunchesRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; -import com.epam.ta.reportportal.ws.model.launch.UpdateLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.BulkInfoUpdateRQ; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributesRQ; +import com.epam.ta.reportportal.ws.reporting.MergeLaunchesRQ; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.UpdateItemAttributeRQ; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.common.collect.Sets; @@ -91,9 +91,9 @@ void happyCreateLaunch() throws Exception { startLaunchRQ.setAttributes(Sets.newHashSet(new ItemAttributesRQ("key", "value"))); mockMvc.perform( - post(DEFAULT_PROJECT_BASE_URL + "/launch/").with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(startLaunchRQ)) - .contentType(APPLICATION_JSON)).andExpect(status().isCreated()); + post(DEFAULT_PROJECT_BASE_URL + "/launch/").with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(startLaunchRQ)).contentType(APPLICATION_JSON)) + .andExpect(status().isCreated()); } @Test @@ -105,8 +105,7 @@ void getSuggestedItemsAnalyzerNotDeployed() throws Exception { analyzeLaunchRQ.setAnalyzerHistoryMode("ALL"); mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/launch/analyze").with( token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(analyzeLaunchRQ)) - .contentType(APPLICATION_JSON)) + .content(objectMapper.writeValueAsBytes(analyzeLaunchRQ)).contentType(APPLICATION_JSON)) .andExpect( result -> assertTrue(result.getResolvedException() instanceof ReportPortalException)) .andExpect(result -> assertEquals( @@ -122,8 +121,7 @@ void updateLaunchPositive() throws Exception { rq.setDescription("description"); rq.setAttributes(Sets.newHashSet(new ItemAttributeResource("test", "test"))); mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/launch/3/update").with( - token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(rq)) + token(oAuthHelper.getDefaultToken())).content(objectMapper.writeValueAsBytes(rq)) .contentType(APPLICATION_JSON)).andExpect(status().is(200)); } @@ -136,32 +134,28 @@ void getLaunchPositive() throws Exception { @Test void getLaunchStringPositive() throws Exception { - mockMvc.perform(get( - DEFAULT_PROJECT_BASE_URL + "/launch/4850a659-ac26-4a65-8ea4-a6756a57fb92").with( - token(oAuthHelper.getDefaultToken()))) - .andExpect(status().is(200)); + mockMvc.perform( + get(DEFAULT_PROJECT_BASE_URL + "/launch/4850a659-ac26-4a65-8ea4-a6756a57fb92").with( + token(oAuthHelper.getDefaultToken()))).andExpect(status().is(200)); } @Test void getLaunchUuidPositive() throws Exception { - mockMvc.perform(get( - DEFAULT_PROJECT_BASE_URL + "/launch/uuid/4850a659-ac26-4a65-8ea4-a6756a57fb92").with( - token(oAuthHelper.getDefaultToken()))) - .andExpect(status().is(200)); + mockMvc.perform( + get(DEFAULT_PROJECT_BASE_URL + "/launch/uuid/4850a659-ac26-4a65-8ea4-a6756a57fb92").with( + token(oAuthHelper.getDefaultToken()))).andExpect(status().is(200)); } @Test void getDebugLaunches() throws Exception { mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/launch/mode").with( - token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().is(200)); + token(oAuthHelper.getSuperadminToken()))).andExpect(status().is(200)); } @Test void compareLaunches() throws Exception { mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/launch/compare?ids=1,2").with( - token(oAuthHelper.getDefaultToken()))) - .andExpect(status().is(200)); + token(oAuthHelper.getDefaultToken()))).andExpect(status().is(200)); } @Test @@ -176,8 +170,8 @@ void mergeLaunchesPositive() throws Exception { rq.setStartTime(new Date()); rq.setEndTime(new Date()); mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/launch/merge").contentType(APPLICATION_JSON) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(rq))).andExpect(status().is(200)); + .with(token(oAuthHelper.getDefaultToken())).content(objectMapper.writeValueAsBytes(rq))) + .andExpect(status().is(200)); } @Test @@ -197,8 +191,7 @@ void deleteLaunchNegative() throws Exception { @Test void getStatus() throws Exception { mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/launch/status?ids=1").with( - token(oAuthHelper.getDefaultToken()))) - .andExpect(status().is(200)); + token(oAuthHelper.getDefaultToken()))).andExpect(status().is(200)); } @Test @@ -235,25 +228,25 @@ void bulkForceFinish() throws Exception { return finishExecutionRQ; }))); mockMvc.perform( - put(DEFAULT_PROJECT_BASE_URL + "/launch/stop").with(token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(bulkRQ))).andExpect(status().isOk()); + put(DEFAULT_PROJECT_BASE_URL + "/launch/stop").with(token(oAuthHelper.getDefaultToken())) + .contentType(APPLICATION_JSON).content(objectMapper.writeValueAsBytes(bulkRQ))) + .andExpect(status().isOk()); } @Test void getAllOwners() throws Exception { mockMvc.perform( - get(DEFAULT_PROJECT_BASE_URL + "/launch/owners?filter.cnt.user=def").contentType( - APPLICATION_JSON) - .with(token(oAuthHelper.getDefaultToken()))).andExpect(status().is(200)); + get(DEFAULT_PROJECT_BASE_URL + "/launch/owners?filter.cnt.user=def").contentType( + APPLICATION_JSON).with(token(oAuthHelper.getDefaultToken()))) + .andExpect(status().is(200)); } @Test void getAllLaunchNames() throws Exception { mockMvc.perform( - get(DEFAULT_PROJECT_BASE_URL + "/launch/names?filter.cnt.name=test").contentType( - APPLICATION_JSON) - .with(token(oAuthHelper.getDefaultToken()))).andExpect(status().is(200)); + get(DEFAULT_PROJECT_BASE_URL + "/launch/names?filter.cnt.name=test").contentType( + APPLICATION_JSON).with(token(oAuthHelper.getDefaultToken()))) + .andExpect(status().is(200)); } @Test @@ -263,18 +256,18 @@ void bulkDeleteLaunches() throws Exception { deleteBulkRQ.setIds(ids); mockMvc.perform(delete(DEFAULT_PROJECT_BASE_URL + "/launch").contentType(APPLICATION_JSON) .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(deleteBulkRQ))).andExpect(status().is(200)); + .param("ids" , "1", "2")) + .andExpect(status().is(200)); List launches = launchRepository.findAllById(ids); assertTrue(launches.isEmpty()); } @Test void bulkMoveToDebug() throws Exception { - final List ids = launchRepository.findByFilter(Filter.builder() - .withTarget(Launch.class) + final List ids = launchRepository.findByFilter(Filter.builder().withTarget(Launch.class) .withCondition( - FilterCondition.builder().eq(CRITERIA_PROJECT_ID, String.valueOf(2L)).build()) - .build()).stream().filter(it -> it.getMode() == LaunchModeEnum.DEFAULT).map(Launch::getId) + FilterCondition.builder().eq(CRITERIA_PROJECT_ID, String.valueOf(2L)).build()).build()) + .stream().filter(it -> it.getMode() == LaunchModeEnum.DEFAULT).map(Launch::getId) .collect(Collectors.toList()); final Map entities = ids.stream().collect(toMap(it -> it, it -> { final UpdateLaunchRQ updateLaunchRQ = new UpdateLaunchRQ(); @@ -284,9 +277,9 @@ void bulkMoveToDebug() throws Exception { final BulkRQ bulkRQ = new BulkRQ<>(); bulkRQ.setEntities(entities); mockMvc.perform( - put(DEFAULT_PROJECT_BASE_URL + "/launch/update").with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(bulkRQ)) - .contentType(APPLICATION_JSON)).andExpect(status().is(200)); + put(DEFAULT_PROJECT_BASE_URL + "/launch/update").with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(bulkRQ)).contentType(APPLICATION_JSON)) + .andExpect(status().is(200)); launchRepository.findAllById(ids).forEach(it -> assertSame(it.getMode(), LaunchModeEnum.DEBUG)); } @@ -294,31 +287,27 @@ void bulkMoveToDebug() throws Exception { void getLaunches() throws Exception { mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/launch?page.page=1&page.size=50&page.sort=statistics$defects$product_bug$total,ASC").contentType( - APPLICATION_JSON) - .with(token(oAuthHelper.getDefaultToken()))).andExpect(status().is(200)); + APPLICATION_JSON).with(token(oAuthHelper.getDefaultToken()))).andExpect(status().is(200)); } @Test void getLatestLaunches() throws Exception { mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL - + "/launch/latest?page.page=1&page.size=10&page.sort=name,ASC").with( - token(oAuthHelper.getDefaultToken()))) - .andExpect(status().is(200)); + + "/launch/latest?page.page=1&page.size=10&page.sort=name,ASC").with( + token(oAuthHelper.getDefaultToken()))).andExpect(status().is(200)); } @Test void getAttributeKeys() throws Exception { mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL - + "/launch/attribute/keys?filter.cnt.attributeKey=browser").with( - token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()); + + "/launch/attribute/keys?filter.cnt.attributeKey=browser").with( + token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk()); } @Test void getAttributeValues() throws Exception { - mockMvc.perform(get( - DEFAULT_PROJECT_BASE_URL - + "/launch/attribute/values?filter.eq.attributeKey=browser&filter.cnt.attributeValue=ch").with( + mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + + "/launch/attribute/values?filter.eq.attributeKey=browser&filter.cnt.attributeValue=ch").with( token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk()); } @@ -326,15 +315,13 @@ void getAttributeValues() throws Exception { void getProjectLaunches() throws Exception { mockMvc.perform( get(DEFAULT_PROJECT_BASE_URL + "/launch").with(token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.content", hasSize(4))); + .andExpect(status().isOk()).andExpect(jsonPath("$.content", hasSize(4))); } @Test void export() throws Exception { mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/launch/1/report").with( - token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()); + token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk()); } @Test @@ -354,23 +341,20 @@ void bulkUpdateItemAttributes() throws Exception { request.setAttributes(Lists.newArrayList(updateItemAttributeRQ)); mockMvc.perform( - put(DEFAULT_PROJECT_BASE_URL + "/launch/info").with(token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(request))).andExpect(status().isOk()); + put(DEFAULT_PROJECT_BASE_URL + "/launch/info").with(token(oAuthHelper.getDefaultToken())) + .contentType(APPLICATION_JSON).content(objectMapper.writeValueAsBytes(request))) + .andExpect(status().isOk()); List launches = launchRepository.findAllById(launchIds); launches.forEach(it -> launchRepository.refresh(it)); launches.forEach(it -> { - assertTrue(it.getAttributes() - .stream() - .noneMatch(attr -> "testKey".equals(attr.getKey()) && attr.getValue().equals("testValue") + assertTrue(it.getAttributes().stream().noneMatch( + attr -> "testKey".equals(attr.getKey()) && attr.getValue().equals("testValue") + && !attr.isSystem())); + assertTrue(it.getAttributes().stream().anyMatch( + attr -> "updatedKey".equals(attr.getKey()) && attr.getValue().equals("updatedValue") && !attr.isSystem())); - assertTrue(it.getAttributes() - .stream() - .anyMatch( - attr -> "updatedKey".equals(attr.getKey()) && attr.getValue().equals("updatedValue") - && !attr.isSystem())); assertEquals(comment, it.getDescription()); }); } @@ -391,19 +375,17 @@ void bulkCreateAttributes() throws Exception { request.setAttributes(Lists.newArrayList(updateItemAttributeRQ)); mockMvc.perform( - put(DEFAULT_PROJECT_BASE_URL + "/launch/info").with(token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(request))).andExpect(status().isOk()); + put(DEFAULT_PROJECT_BASE_URL + "/launch/info").with(token(oAuthHelper.getDefaultToken())) + .contentType(APPLICATION_JSON).content(objectMapper.writeValueAsBytes(request))) + .andExpect(status().isOk()); List launches = launchRepository.findAllById(launchIds); launches.forEach(it -> launchRepository.refresh(it)); launches.forEach(it -> { - assertTrue(it.getAttributes() - .stream() - .anyMatch( - attr -> "createdKey".equals(attr.getKey()) && attr.getValue().equals("createdValue") - && !attr.isSystem())); + assertTrue(it.getAttributes().stream().anyMatch( + attr -> "createdKey".equals(attr.getKey()) && attr.getValue().equals("createdValue") + && !attr.isSystem())); assertTrue( it.getDescription().length() > comment.length() && it.getDescription().contains(comment)); }); @@ -425,19 +407,18 @@ void bulkDeleteAttributes() throws Exception { request.setAttributes(Lists.newArrayList(updateItemAttributeRQ)); mockMvc.perform( - put(DEFAULT_PROJECT_BASE_URL + "/launch/info").with(token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(request))).andExpect(status().isOk()); + put(DEFAULT_PROJECT_BASE_URL + "/launch/info").with(token(oAuthHelper.getDefaultToken())) + .contentType(APPLICATION_JSON).content(objectMapper.writeValueAsBytes(request))) + .andExpect(status().isOk()); List launches = launchRepository.findAllById(launchIds); launches.forEach(it -> launchRepository.refresh(it)); launches.forEach(it -> { - assertTrue(it.getAttributes() - .stream() - .noneMatch(attr -> "testKey".equals(attr.getKey()) && attr.getValue().equals("testValue") + assertTrue(it.getAttributes().stream().noneMatch( + attr -> "testKey".equals(attr.getKey()) && attr.getValue().equals("testValue") && !attr.isSystem())); assertEquals(comment, it.getDescription()); }); } -} \ No newline at end of file +} diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/LaunchControllerValidationTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/LaunchControllerValidationTest.java index 0b3070b83b..cd9a900a40 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/LaunchControllerValidationTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/LaunchControllerValidationTest.java @@ -21,8 +21,8 @@ import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.FIELD_NAME_SIZE_MESSAGE_WITH_FORMAT; import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.INCORRECT_REQUEST_MESSAGE; import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.WHITESPACES_NAME_VALUE; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; -import static com.epam.ta.reportportal.ws.model.launch.Mode.DEFAULT; +import static com.epam.ta.reportportal.ws.reporting.Mode.DEFAULT; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.http.MediaType.APPLICATION_JSON; @@ -30,10 +30,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.ErrorRS; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributesRQ; -import com.epam.ta.reportportal.ws.model.launch.MergeLaunchesRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorRS; +import com.epam.ta.reportportal.ws.reporting.ItemAttributesRQ; +import com.epam.ta.reportportal.ws.reporting.MergeLaunchesRQ; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Sets; import java.util.Date; diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/LogAsyncControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/LogAsyncControllerTest.java index 4edba9ed06..891aef27c3 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/LogAsyncControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/LogAsyncControllerTest.java @@ -29,7 +29,7 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; import javax.servlet.http.HttpServletRequest; import javax.validation.Validator; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/LogControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/LogControllerTest.java index 7076cf8f98..0a3cd57760 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/LogControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/LogControllerTest.java @@ -24,9 +24,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.log.SearchLogRq; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; -import com.epam.ta.reportportal.ws.model.log.SearchLogRq; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; import com.fasterxml.jackson.databind.ObjectMapper; import java.time.LocalDateTime; import java.time.ZoneId; diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/ProjectControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/ProjectControllerTest.java index 7a08a2e65a..a1d8712c50 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/ProjectControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/ProjectControllerTest.java @@ -16,26 +16,49 @@ package com.epam.ta.reportportal.ws.controller; +import static java.util.Collections.singletonList; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import com.epam.ta.reportportal.core.events.activity.ProjectIndexEvent; import com.epam.ta.reportportal.dao.ProjectRepository; import com.epam.ta.reportportal.entity.enums.LogicalOperator; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectAttribute; +import com.epam.ta.reportportal.model.DeleteBulkRQ; +import com.epam.ta.reportportal.model.project.AssignUsersRQ; +import com.epam.ta.reportportal.model.project.CreateProjectRQ; +import com.epam.ta.reportportal.model.project.UnassignUsersRQ; +import com.epam.ta.reportportal.model.project.UpdateProjectRQ; +import com.epam.ta.reportportal.model.project.config.ProjectConfigurationUpdate; +import com.epam.ta.reportportal.model.project.email.ProjectNotificationConfigDTO; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.DeleteBulkRQ; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.project.AssignUsersRQ; -import com.epam.ta.reportportal.ws.model.project.CreateProjectRQ; -import com.epam.ta.reportportal.ws.model.project.UnassignUsersRQ; -import com.epam.ta.reportportal.ws.model.project.UpdateProjectRQ; -import com.epam.ta.reportportal.ws.model.project.config.ProjectConfigurationUpdate; -import com.epam.ta.reportportal.ws.model.project.email.ProjectNotificationConfigDTO; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.rabbitmq.http.client.Client; import com.rabbitmq.http.client.domain.ExchangeInfo; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -48,18 +71,6 @@ import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.servlet.ResultActions; -import java.util.*; - -import static java.util.Collections.singletonList; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; -import static org.springframework.http.MediaType.APPLICATION_JSON; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - /** * @author Ihar Kahadouski */ @@ -300,7 +311,8 @@ void bulkDeleteProjects() throws Exception { bulkRQ.setIds(Lists.newArrayList(2L, 3L)); mockMvc.perform(delete("/v1/project").with(token(oAuthHelper.getSuperadminToken())) .contentType(APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(bulkRQ))).andExpect(status().isOk()); + .param("ids" , "2", "3")) + .andExpect(status().isOk()); } @Test diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/ProjectSettingsControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/ProjectSettingsControllerTest.java index 4ba4c88e86..3e738ba320 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/ProjectSettingsControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/ProjectSettingsControllerTest.java @@ -31,14 +31,14 @@ import com.epam.ta.reportportal.entity.enums.SendCase; import com.epam.ta.reportportal.entity.item.issue.IssueType; import com.epam.ta.reportportal.entity.project.email.SenderCase; +import com.epam.ta.reportportal.model.project.config.CreateIssueSubTypeRQ; +import com.epam.ta.reportportal.model.project.config.ProjectSettingsResource; +import com.epam.ta.reportportal.model.project.config.UpdateIssueSubTypeRQ; +import com.epam.ta.reportportal.model.project.config.UpdateOneIssueSubTypeRQ; +import com.epam.ta.reportportal.model.project.config.pattern.CreatePatternTemplateRQ; +import com.epam.ta.reportportal.model.project.config.pattern.UpdatePatternTemplateRQ; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.project.config.CreateIssueSubTypeRQ; -import com.epam.ta.reportportal.ws.model.project.config.ProjectSettingsResource; -import com.epam.ta.reportportal.ws.model.project.config.UpdateIssueSubTypeRQ; -import com.epam.ta.reportportal.ws.model.project.config.UpdateOneIssueSubTypeRQ; -import com.epam.ta.reportportal.ws.model.project.config.pattern.CreatePatternTemplateRQ; -import com.epam.ta.reportportal.ws.model.project.config.pattern.UpdatePatternTemplateRQ; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Collection; @@ -76,21 +76,20 @@ void createSubType() throws Exception { rq.setLongName("LongName"); rq.setShortName("name"); mockMvc.perform( - post(DEFAULT_PROJECT_BASE_URL + "/settings/sub-type").contentType(APPLICATION_JSON) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(rq))).andExpect(status().isCreated()); + post(DEFAULT_PROJECT_BASE_URL + "/settings/sub-type").contentType(APPLICATION_JSON) + .with(token(oAuthHelper.getDefaultToken())).content(objectMapper.writeValueAsBytes(rq))) + .andExpect(status().isCreated()); } @Test void getProjectSettings() throws Exception { final MvcResult mvcResult = mockMvc.perform( get(DEFAULT_PROJECT_BASE_URL + "/settings").with(token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()) - .andReturn(); - final ProjectSettingsResource projectSettingsResource = objectMapper.readValue( - mvcResult.getResponse().getContentAsString(), - ProjectSettingsResource.class - ); + .andExpect(status().isOk()).andReturn(); + final ProjectSettingsResource projectSettingsResource = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), + ProjectSettingsResource.class + ); assertEquals(8, projectSettingsResource.getSubTypes().values().stream().flatMap(Collection::stream) .collect(Collectors.toList()).size() @@ -100,8 +99,7 @@ void getProjectSettings() throws Exception { @Test void deleteSubType() throws Exception { mockMvc.perform(delete(DEFAULT_PROJECT_BASE_URL + "/settings/sub-type/6").with( - token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()); + token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk()); Optional byId = issueTypeRepository.findById(6L); assertFalse(byId.isPresent()); @@ -119,8 +117,7 @@ void updateSubType() throws Exception { updateOneIssueSubTypeRQ.setTypeRef("TO_INVESTIGATE"); request.setIds(Collections.singletonList(updateOneIssueSubTypeRQ)); mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/settings/sub-type").with( - token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) + token(oAuthHelper.getDefaultToken())).contentType(APPLICATION_JSON) .content(objectMapper.writeValueAsBytes(request))).andExpect(status().isOk()); } @@ -132,8 +129,7 @@ void createPatternTemplate() throws Exception { createPatternTemplateRQ.setType("string"); createPatternTemplateRQ.setValue("qwe"); mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/settings/pattern").with( - token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) + token(oAuthHelper.getDefaultToken())).contentType(APPLICATION_JSON) .content(objectMapper.writeValueAsBytes(createPatternTemplateRQ))) .andExpect(status().isCreated()); } @@ -146,8 +142,7 @@ void createPatternTemplateWithWrongType() throws Exception { createPatternTemplateRQ.setType("dd"); createPatternTemplateRQ.setValue("qwe"); mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/settings/pattern").with( - token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) + token(oAuthHelper.getDefaultToken())).contentType(APPLICATION_JSON) .content(objectMapper.writeValueAsBytes(createPatternTemplateRQ))) .andExpect(status().isBadRequest()); } @@ -161,8 +156,7 @@ void createPatternTemplateWithDuplicateName() throws Exception { createPatternTemplateRQ.setValue("qwe"); mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/settings/pattern").with( - token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) + token(oAuthHelper.getDefaultToken())).contentType(APPLICATION_JSON) .content(objectMapper.writeValueAsBytes(createPatternTemplateRQ))) .andExpect(status().isConflict()); } @@ -175,8 +169,7 @@ void updatePatternTemplate() throws Exception { updatePatternTemplateRQ.setEnabled(true); mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/settings/pattern/1").with( - token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) + token(oAuthHelper.getDefaultToken())).contentType(APPLICATION_JSON) .content(objectMapper.writeValueAsBytes(updatePatternTemplateRQ))) .andExpect(status().isOk()); } @@ -189,8 +182,7 @@ void updatePatternTemplateWithTheSameName() throws Exception { updatePatternTemplateRQ.setEnabled(true); mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/settings/pattern/1").with( - token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) + token(oAuthHelper.getDefaultToken())).contentType(APPLICATION_JSON) .content(objectMapper.writeValueAsBytes(updatePatternTemplateRQ))) .andExpect(status().isOk()); } @@ -203,23 +195,19 @@ void updatePatternTemplateWithDuplicateName() throws Exception { updatePatternTemplateRQ.setEnabled(true); mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/settings/pattern/2").with( - token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) + token(oAuthHelper.getDefaultToken())).contentType(APPLICATION_JSON) .content(objectMapper.writeValueAsBytes(updatePatternTemplateRQ))) .andExpect(status().isConflict()); } @Test void getNotifications() throws Exception { - final MvcResult mvcResult = mockMvc.perform(get( - DEFAULT_PROJECT_BASE_URL + NOTIFICATION_URL).with(token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()) - .andReturn(); - final List senderCaseDTOS = objectMapper.readValue( - mvcResult.getResponse().getContentAsString(), - new TypeReference<>() { - } - ); + final MvcResult mvcResult = mockMvc.perform( + get(DEFAULT_PROJECT_BASE_URL + NOTIFICATION_URL).with(token(oAuthHelper.getDefaultToken()))) + .andExpect(status().isOk()).andReturn(); + final List senderCaseDTOS = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), new TypeReference<>() { + }); assertEquals(4, senderCaseDTOS.size()); } @@ -236,8 +224,7 @@ void createNotification() throws Exception { mockMvc.perform( post(DEFAULT_PROJECT_BASE_URL + NOTIFICATION_URL).with(token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(senderCaseDTO))) + .contentType(APPLICATION_JSON).content(objectMapper.writeValueAsBytes(senderCaseDTO))) .andExpect(status().isCreated()); } @@ -254,8 +241,7 @@ void createNotificationWithDuplicateRuleName() throws Exception { mockMvc.perform( post(DEFAULT_PROJECT_BASE_URL + NOTIFICATION_URL).with(token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(senderCaseDTO))) + .contentType(APPLICATION_JSON).content(objectMapper.writeValueAsBytes(senderCaseDTO))) .andExpect(status().isConflict()); } @@ -271,9 +257,9 @@ void updateNotification() throws Exception { updateRq.setAttributesOperator(LogicalOperator.AND.getOperator()); mockMvc.perform( - put(DEFAULT_PROJECT_BASE_URL + NOTIFICATION_URL).with(token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(updateRq))).andExpect(status().isCreated()); + put(DEFAULT_PROJECT_BASE_URL + NOTIFICATION_URL).with(token(oAuthHelper.getDefaultToken())) + .contentType(APPLICATION_JSON).content(objectMapper.writeValueAsBytes(updateRq))) + .andExpect(status().isCreated()); } @Test @@ -281,8 +267,7 @@ void deleteNotification() throws Exception { Long id = 1L; mockMvc.perform(delete(DEFAULT_PROJECT_BASE_URL + NOTIFICATION_URL + id).with( - token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()); + token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk()); List senderCases = senderCaseRepository.findAll(); diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/SettingsControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/SettingsControllerTest.java index f674aa8b31..e43387bdc1 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/SettingsControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/SettingsControllerTest.java @@ -21,8 +21,8 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import com.epam.ta.reportportal.model.settings.AnalyticsResource; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.settings.AnalyticsResource; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -48,8 +48,8 @@ void updateAnalyticsSettings() throws Exception { resource.setType("server.analytics.all"); resource.setEnabled(true); mockMvc.perform(put("/v1/settings/analytics").with(token(oAuthHelper.getSuperadminToken())) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(resource))).andExpect(status().isOk()); + .contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsBytes(resource))) + .andExpect(status().isOk()); } @Test @@ -58,7 +58,7 @@ void saveAnalyticsSettingsNegative() throws Exception { resource.setEnabled(true); resource.setType(""); mockMvc.perform(put("/v1/settings/analytics").with(token(oAuthHelper.getSuperadminToken())) - .contentType(APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(resource))).andExpect(status().isBadRequest()); + .contentType(APPLICATION_JSON).content(objectMapper.writeValueAsBytes(resource))) + .andExpect(status().isBadRequest()); } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/TestItemAsyncControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/TestItemAsyncControllerTest.java index d0618eabc4..4179ac78eb 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/TestItemAsyncControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/TestItemAsyncControllerTest.java @@ -29,8 +29,8 @@ import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.util.ProjectExtractor; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; import java.util.UUID; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/TestItemControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/TestItemControllerTest.java index 98a4098ce4..d487ac47e0 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/TestItemControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/TestItemControllerTest.java @@ -38,19 +38,19 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.exception.ReportPortalException; +import com.epam.ta.reportportal.model.issue.DefineIssueRQ; +import com.epam.ta.reportportal.model.issue.IssueDefinition; +import com.epam.ta.reportportal.model.item.LinkExternalIssueRQ; +import com.epam.ta.reportportal.model.item.UnlinkExternalIssueRQ; +import com.epam.ta.reportportal.model.item.UpdateTestItemRQ; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.BulkInfoUpdateRQ; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; -import com.epam.ta.reportportal.ws.model.ParameterResource; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.attribute.UpdateItemAttributeRQ; -import com.epam.ta.reportportal.ws.model.issue.DefineIssueRQ; -import com.epam.ta.reportportal.ws.model.issue.Issue; -import com.epam.ta.reportportal.ws.model.issue.IssueDefinition; -import com.epam.ta.reportportal.ws.model.item.LinkExternalIssueRQ; -import com.epam.ta.reportportal.ws.model.item.UnlinkExternalIssueRQ; -import com.epam.ta.reportportal.ws.model.item.UpdateTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.BulkInfoUpdateRQ; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.Issue; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ParameterResource; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.UpdateItemAttributeRQ; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/TestItemControllerValidationTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/TestItemControllerValidationTest.java index ac34e211de..125e402d68 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/TestItemControllerValidationTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/TestItemControllerValidationTest.java @@ -20,7 +20,7 @@ import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.FIELD_NAME_IS_NULL_MESSAGE; import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.INCORRECT_REQUEST_MESSAGE; import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.WHITESPACES_NAME_VALUE; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.http.MediaType.APPLICATION_JSON; @@ -29,13 +29,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.ErrorRS; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.issue.DefineIssueRQ; -import com.epam.ta.reportportal.ws.model.issue.Issue; -import com.epam.ta.reportportal.ws.model.issue.IssueDefinition; -import com.epam.ta.reportportal.ws.model.item.LinkExternalIssueRQ; -import com.epam.ta.reportportal.ws.model.item.UnlinkExternalIssueRQ; +import com.epam.ta.reportportal.ws.reporting.ErrorRS; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; +import com.epam.ta.reportportal.model.issue.DefineIssueRQ; +import com.epam.ta.reportportal.ws.reporting.Issue; +import com.epam.ta.reportportal.model.issue.IssueDefinition; +import com.epam.ta.reportportal.model.item.LinkExternalIssueRQ; +import com.epam.ta.reportportal.model.item.UnlinkExternalIssueRQ; import com.fasterxml.jackson.databind.ObjectMapper; import java.time.LocalDateTime; import java.time.ZoneId; diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/UserControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/UserControllerTest.java index 6a01d0a9cd..d65355dcd6 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/UserControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/UserControllerTest.java @@ -16,6 +16,20 @@ package com.epam.ta.reportportal.ws.controller; +import static com.epam.ta.reportportal.commons.EntityUtils.normalizeId; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import com.epam.ta.reportportal.dao.IssueTypeRepository; import com.epam.ta.reportportal.dao.ProjectRepository; import com.epam.ta.reportportal.dao.UserRepository; @@ -24,34 +38,31 @@ import com.epam.ta.reportportal.entity.item.issue.IssueType; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectIssueType; +import com.epam.ta.reportportal.model.DeleteBulkRQ; +import com.epam.ta.reportportal.model.Page; +import com.epam.ta.reportportal.model.user.ChangePasswordRQ; +import com.epam.ta.reportportal.model.user.CreateUserBidRS; +import com.epam.ta.reportportal.model.user.CreateUserRQ; +import com.epam.ta.reportportal.model.user.CreateUserRQConfirm; +import com.epam.ta.reportportal.model.user.CreateUserRQFull; +import com.epam.ta.reportportal.model.user.CreateUserRS; +import com.epam.ta.reportportal.model.user.EditUserRQ; +import com.epam.ta.reportportal.model.user.ResetPasswordRQ; +import com.epam.ta.reportportal.model.user.RestorePasswordRQ; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.DeleteBulkRQ; -import com.epam.ta.reportportal.ws.model.Page; import com.epam.ta.reportportal.ws.model.ValidationConstraints; -import com.epam.ta.reportportal.ws.model.user.*; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.servlet.MvcResult; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import static com.epam.ta.reportportal.commons.EntityUtils.normalizeId; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; -import static org.springframework.http.MediaType.APPLICATION_JSON; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - /** * @author Ihar Kahadouski */ @@ -189,8 +200,9 @@ void deleteUsers() throws Exception { deleteBulkRQ.setIds(Lists.newArrayList(2L)); mockMvc.perform(delete("/v1/user").with(token(oAuthHelper.getSuperadminToken())) - .contentType(APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(deleteBulkRQ))).andExpect(status().isOk()); + .contentType(APPLICATION_JSON) + .param("ids", "1", "2")) + .andExpect(status().isOk()); } @Test @@ -376,4 +388,4 @@ void exportUsers() throws Exception { mockMvc.perform(get("/v1/user/export").with(token(oAuthHelper.getSuperadminToken()))) .andExpect(status().isOk()); } -} \ No newline at end of file +} diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/UserFilterControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/UserFilterControllerTest.java index 0fbb00a9db..4d2dbd0dc6 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/UserFilterControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/UserFilterControllerTest.java @@ -16,187 +16,205 @@ package com.epam.ta.reportportal.ws.controller; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import com.epam.ta.reportportal.commons.querygen.FilterCondition; import com.epam.ta.reportportal.dao.UserFilterRepository; import com.epam.ta.reportportal.entity.filter.UserFilter; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.filter.Order; +import com.epam.ta.reportportal.model.filter.UpdateUserFilterRQ; +import com.epam.ta.reportportal.model.filter.UserFilterCondition; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; import com.epam.ta.reportportal.ws.model.ValidationConstraints; -import com.epam.ta.reportportal.ws.model.filter.Order; -import com.epam.ta.reportportal.ws.model.filter.UpdateUserFilterRQ; -import com.epam.ta.reportportal.ws.model.filter.UserFilterCondition; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.common.collect.Sets; +import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.servlet.MvcResult; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.springframework.http.MediaType.APPLICATION_JSON; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - /** * @author Ihar Kahadouski */ @Sql("/db/shareable/shareable-fill.sql") class UserFilterControllerTest extends BaseMvcTest { - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private UserFilterRepository repository; - - @Test - void createFilterPositive() throws Exception { - String name = "userFilter"; - String description = "description"; - UpdateUserFilterRQ request = new UpdateUserFilterRQ(); - request.setName(name); - request.setObjectType("Launch"); - - final Order order = new Order(); - order.setIsAsc(false); - order.setSortingColumnName("startTime"); - - request.setOrders(Lists.newArrayList(order)); - request.setDescription(description); - request.setConditions(Sets.newHashSet(new UserFilterCondition("name", "cnt", "test"))); - - MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/filter").with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(request)) - .contentType(APPLICATION_JSON)).andExpect(status().isCreated()).andReturn(); - - EntryCreatedRS response = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), new TypeReference() { - }); - final Optional optionalFilter = repository.findById(response.getId()); - - assertTrue(optionalFilter.isPresent()); - assertEquals(name, optionalFilter.get().getName()); - assertEquals(description, optionalFilter.get().getDescription()); - } - - @Test - void getFilterPositive() throws Exception { - mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/filter/3").with(token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk()); - } - - @Test - void getFilterNegative() throws Exception { - mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/filter/100").with(token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isNotFound()); - } - - @Test - void getFiltersByIds() throws Exception { - mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/filter/filters?ids=3,4").with(token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()); - } - - @Test - void getSharedFiltersPositive() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/filter/shared").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isBadRequest()); - } - - @Test - void getPermittedFilters() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/filter").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()); - } - - @Test - void deleteFilterPositive() throws Exception { - mockMvc.perform(delete(DEFAULT_PROJECT_BASE_URL + "/filter/3").with(token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()); - } - - @Test - void getAllFiltersNamesPositive() throws Exception { - mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/filter/names").with(token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()); - } - - @Test - void getAllSharedFiltersNames() throws Exception { - mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/filter/names?share=true").with(token(oAuthHelper.getDefaultToken()))) - .andExpect(status().isOk()); - } - - @Test - void updateUserFilterPositive() throws Exception { - UpdateUserFilterRQ updateUserFilterRQ = new UpdateUserFilterRQ(); - updateUserFilterRQ.setName("new name"); - updateUserFilterRQ.setObjectType("Launch"); - updateUserFilterRQ.setDescription("new description"); - Order order = new Order(); - order.setIsAsc(true); - order.setSortingColumnName("name"); - updateUserFilterRQ.setOrders(Lists.newArrayList(order)); - updateUserFilterRQ.setConditions(Sets.newHashSet(new UserFilterCondition("name", "eq", "filter"))); - - mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/filter/3").with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(updateUserFilterRQ)) - .contentType(APPLICATION_JSON)).andExpect(status().isOk()); - final Optional optionalUserFilter = repository.findById(3L); - assertTrue(optionalUserFilter.isPresent()); - assertEquals("new description", optionalUserFilter.get().getDescription()); - assertEquals("new name", optionalUserFilter.get().getName()); - } - - @Test - void createUserFiltersLongDescription() throws Exception { - String name = "userFilter"; - UpdateUserFilterRQ request = new UpdateUserFilterRQ(); - request.setName(name); - request.setObjectType("Launch"); - - final Order order = new Order(); - order.setIsAsc(false); - order.setSortingColumnName("startTime"); - - request.setOrders(Lists.newArrayList(order)); - request.setDescription(StringUtils.leftPad("", 1501, "a")); - request.setConditions(Sets.newHashSet(new UserFilterCondition("name", "cnt", "test"))); - - mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/filter").with(token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(request))).andExpect(status().is4xxClientError()); - } - - @Test - void updateUserFilterWithKeyAndValueLongerThan512() throws Exception { - UpdateUserFilterRQ updateUserFilterRQ = new UpdateUserFilterRQ(); - updateUserFilterRQ.setName("new name"); - updateUserFilterRQ.setObjectType("Launch"); - updateUserFilterRQ.setDescription("new description"); - Order order = new Order(); - order.setIsAsc(true); - order.setSortingColumnName("name"); - updateUserFilterRQ.setOrders(Lists.newArrayList(order)); - String key = StringUtils.leftPad("", ValidationConstraints.MAX_ATTRIBUTE_LENGTH + 1, "a"); - String value = key + ":" + key; - updateUserFilterRQ.setConditions(Sets.newHashSet(new UserFilterCondition("name", "eq", value))); - - mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/filter/3").with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(updateUserFilterRQ)) - .contentType(APPLICATION_JSON)).andExpect(status().isOk()); - final Optional optionalUserFilter = repository.findById(3L); - assertTrue(optionalUserFilter.isPresent()); - assertEquals("new description", optionalUserFilter.get().getDescription()); - assertEquals("new name", optionalUserFilter.get().getName()); - FilterCondition filterCondition = (FilterCondition) optionalUserFilter.get().getFilterCondition().toArray()[0]; - String actualKey = filterCondition.getValue().substring(0, filterCondition.getValue().indexOf(":")); - String actualValue = filterCondition.getValue().substring(filterCondition.getValue().indexOf(":") + 1); - assertEquals(ValidationConstraints.MAX_ATTRIBUTE_LENGTH, actualKey.length()); - assertEquals(ValidationConstraints.MAX_ATTRIBUTE_LENGTH, actualValue.length()); - } + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private UserFilterRepository repository; + + @Test + void createFilterPositive() throws Exception { + String name = "userFilter"; + String description = "description"; + UpdateUserFilterRQ request = new UpdateUserFilterRQ(); + request.setName(name); + request.setObjectType("Launch"); + + final Order order = new Order(); + order.setIsAsc(false); + order.setSortingColumnName("startTime"); + + request.setOrders(Lists.newArrayList(order)); + request.setDescription(description); + request.setConditions(Sets.newHashSet(new UserFilterCondition("name", "cnt", "test"))); + + MvcResult mvcResult = mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + "/filter").with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(request)).contentType(APPLICATION_JSON)) + .andExpect(status().isCreated()).andReturn(); + + EntryCreatedRS response = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), + new TypeReference() { + } + ); + final Optional optionalFilter = repository.findById(response.getId()); + + assertTrue(optionalFilter.isPresent()); + assertEquals(name, optionalFilter.get().getName()); + assertEquals(description, optionalFilter.get().getDescription()); + } + + @Test + void getFilterPositive() throws Exception { + mockMvc.perform( + get(DEFAULT_PROJECT_BASE_URL + "/filter/3").with(token(oAuthHelper.getDefaultToken()))) + .andExpect(status().isOk()); + } + + @Test + void getFilterNegative() throws Exception { + mockMvc.perform( + get(DEFAULT_PROJECT_BASE_URL + "/filter/100").with(token(oAuthHelper.getDefaultToken()))) + .andExpect(status().isNotFound()); + } + + @Test + void getFiltersByIds() throws Exception { + mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/filter/filters?ids=3,4").with( + token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk()); + } + + @Test + void getSharedFiltersPositive() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/filter/shared").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isBadRequest()); + } + + @Test + void getPermittedFilters() throws Exception { + mockMvc.perform( + get(SUPERADMIN_PROJECT_BASE_URL + "/filter").with(token(oAuthHelper.getSuperadminToken()))) + .andExpect(status().isOk()); + } + + @Test + void deleteFilterPositive() throws Exception { + mockMvc.perform( + delete(DEFAULT_PROJECT_BASE_URL + "/filter/3").with(token(oAuthHelper.getDefaultToken()))) + .andExpect(status().isOk()); + } + + @Test + void getAllFiltersNamesPositive() throws Exception { + mockMvc.perform( + get(DEFAULT_PROJECT_BASE_URL + "/filter/names").with(token(oAuthHelper.getDefaultToken()))) + .andExpect(status().isOk()); + } + + @Test + void getAllSharedFiltersNames() throws Exception { + mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/filter/names?share=true").with( + token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk()); + } + + @Test + void updateUserFilterPositive() throws Exception { + UpdateUserFilterRQ updateUserFilterRQ = new UpdateUserFilterRQ(); + updateUserFilterRQ.setName("new name"); + updateUserFilterRQ.setObjectType("Launch"); + updateUserFilterRQ.setDescription("new description"); + Order order = new Order(); + order.setIsAsc(true); + order.setSortingColumnName("name"); + updateUserFilterRQ.setOrders(Lists.newArrayList(order)); + updateUserFilterRQ.setConditions( + Sets.newHashSet(new UserFilterCondition("name", "eq", "filter"))); + + mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + "/filter/3").with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(updateUserFilterRQ)) + .contentType(APPLICATION_JSON)).andExpect(status().isOk()); + final Optional optionalUserFilter = repository.findById(3L); + assertTrue(optionalUserFilter.isPresent()); + assertEquals("new description", optionalUserFilter.get().getDescription()); + assertEquals("new name", optionalUserFilter.get().getName()); + } + + @Test + void createUserFiltersLongDescription() throws Exception { + String name = "userFilter"; + UpdateUserFilterRQ request = new UpdateUserFilterRQ(); + request.setName(name); + request.setObjectType("Launch"); + + final Order order = new Order(); + order.setIsAsc(false); + order.setSortingColumnName("startTime"); + + request.setOrders(Lists.newArrayList(order)); + request.setDescription(StringUtils.leftPad("", 1501, "a")); + request.setConditions(Sets.newHashSet(new UserFilterCondition("name", "cnt", "test"))); + + mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + "/filter").with(token(oAuthHelper.getDefaultToken())) + .contentType(APPLICATION_JSON).content(objectMapper.writeValueAsBytes(request))) + .andExpect(status().is4xxClientError()); + } + + @Test + void updateUserFilterWithKeyAndValueLongerThan512() throws Exception { + UpdateUserFilterRQ updateUserFilterRQ = new UpdateUserFilterRQ(); + updateUserFilterRQ.setName("new name"); + updateUserFilterRQ.setObjectType("Launch"); + updateUserFilterRQ.setDescription("new description"); + Order order = new Order(); + order.setIsAsc(true); + order.setSortingColumnName("name"); + updateUserFilterRQ.setOrders(Lists.newArrayList(order)); + String key = StringUtils.leftPad("", ValidationConstraints.MAX_ATTRIBUTE_LENGTH + 1, "a"); + String value = key + ":" + key; + updateUserFilterRQ.setConditions(Sets.newHashSet(new UserFilterCondition("name", "eq", value))); + + mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + "/filter/3").with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(updateUserFilterRQ)) + .contentType(APPLICATION_JSON)).andExpect(status().isOk()); + final Optional optionalUserFilter = repository.findById(3L); + assertTrue(optionalUserFilter.isPresent()); + assertEquals("new description", optionalUserFilter.get().getDescription()); + assertEquals("new name", optionalUserFilter.get().getName()); + FilterCondition filterCondition = + (FilterCondition) optionalUserFilter.get().getFilterCondition().toArray()[0]; + String actualKey = + filterCondition.getValue().substring(0, filterCondition.getValue().indexOf(":")); + String actualValue = + filterCondition.getValue().substring(filterCondition.getValue().indexOf(":") + 1); + assertEquals(ValidationConstraints.MAX_ATTRIBUTE_LENGTH, actualKey.length()); + assertEquals(ValidationConstraints.MAX_ATTRIBUTE_LENGTH, actualValue.length()); + } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/UserFilterControllerValidationTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/UserFilterControllerValidationTest.java index def3e3e20b..73847d968b 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/UserFilterControllerValidationTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/UserFilterControllerValidationTest.java @@ -24,7 +24,7 @@ import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.LONG_NAME_VALUE; import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.SHORT_NAME_VALUE; import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.WHITESPACES_NAME_VALUE; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.http.MediaType.APPLICATION_JSON; @@ -32,11 +32,11 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import com.epam.ta.reportportal.model.filter.Order; +import com.epam.ta.reportportal.model.filter.UpdateUserFilterRQ; +import com.epam.ta.reportportal.model.filter.UserFilterCondition; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.ErrorRS; -import com.epam.ta.reportportal.ws.model.filter.Order; -import com.epam.ta.reportportal.ws.model.filter.UpdateUserFilterRQ; -import com.epam.ta.reportportal.ws.model.filter.UserFilterCondition; +import com.epam.ta.reportportal.ws.reporting.ErrorRS; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.common.collect.Sets; @@ -51,8 +51,8 @@ public class UserFilterControllerValidationTest extends BaseMvcTest { private static final String FILTER_PATH = "/filter"; - private static final String FIELD_NAME_SIZE_MESSAGE = String.format( - FIELD_NAME_SIZE_MESSAGE_WITH_FORMAT, 3, 128); + private static final String FIELD_NAME_SIZE_MESSAGE = + String.format(FIELD_NAME_SIZE_MESSAGE_WITH_FORMAT, 3, 128); @Autowired private ObjectMapper objectMapper; @@ -63,15 +63,14 @@ public void createFilterShouldReturnErrorWhenNameIsNull() throws Exception { UpdateUserFilterRQ userFilterRQ = prepareFilter(); //WHEN - MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + FILTER_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(userFilterRQ)) - .contentType(APPLICATION_JSON)) + MvcResult mvcResult = mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + FILTER_PATH).with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(userFilterRQ)).contentType(APPLICATION_JSON)) .andExpect(status().isBadRequest()).andReturn(); //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), - ErrorRS.class); + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); assertEquals(INCORRECT_REQUEST, error.getErrorType()); assertEquals(INCORRECT_REQUEST_MESSAGE + FIELD_NAME_IS_NULL_MESSAGE, error.getMessage()); } @@ -83,15 +82,14 @@ public void createFilterShouldReturnErrorWhenNameIsEmpty() throws Exception { userFilterRQ.setName(EMPTY); //WHEN - MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + FILTER_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(userFilterRQ)) - .contentType(APPLICATION_JSON)) + MvcResult mvcResult = mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + FILTER_PATH).with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(userFilterRQ)).contentType(APPLICATION_JSON)) .andExpect(status().isBadRequest()).andReturn(); //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), - ErrorRS.class); + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); assertEquals(INCORRECT_REQUEST, error.getErrorType()); assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_IS_BLANK_MESSAGE + " " + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); @@ -104,15 +102,14 @@ public void createFilterShouldReturnErrorWhenNameConsistsOfWhitespaces() throws userFilterRQ.setName(WHITESPACES_NAME_VALUE); //WHEN - MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + FILTER_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(userFilterRQ)) - .contentType(APPLICATION_JSON)) + MvcResult mvcResult = mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + FILTER_PATH).with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(userFilterRQ)).contentType(APPLICATION_JSON)) .andExpect(status().isBadRequest()).andReturn(); //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), - ErrorRS.class); + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); assertEquals(INCORRECT_REQUEST, error.getErrorType()); assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_IS_BLANK_MESSAGE + " " + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); @@ -125,18 +122,18 @@ public void createFilterShouldReturnErrorWhenNameIsLessThanThreeCharacters() thr userFilterRQ.setName(SHORT_NAME_VALUE); //WHEN - MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + FILTER_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(userFilterRQ)) - .contentType(APPLICATION_JSON)) + MvcResult mvcResult = mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + FILTER_PATH).with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(userFilterRQ)).contentType(APPLICATION_JSON)) .andExpect(status().isBadRequest()).andReturn(); //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), - ErrorRS.class); + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); assertEquals(INCORRECT_REQUEST, error.getErrorType()); assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_SIZE_MESSAGE + "] ", - error.getMessage()); + error.getMessage() + ); } @Test @@ -147,18 +144,18 @@ public void createFilterShouldReturnErrorWhenNameIsGreaterThanOneHundredAndTwent userFilterRQ.setName(LONG_NAME_VALUE); //WHEN - MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + FILTER_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(userFilterRQ)) - .contentType(APPLICATION_JSON)) + MvcResult mvcResult = mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + FILTER_PATH).with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(userFilterRQ)).contentType(APPLICATION_JSON)) .andExpect(status().isBadRequest()).andReturn(); //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), - ErrorRS.class); + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); assertEquals(INCORRECT_REQUEST, error.getErrorType()); assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_SIZE_MESSAGE + "] ", - error.getMessage()); + error.getMessage() + ); } @Test @@ -167,15 +164,15 @@ public void updateFilterShouldReturnErrorWhenNameIsNull() throws Exception { UpdateUserFilterRQ userFilterRQ = prepareFilter(); //WHEN - MvcResult mvcResult = mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + FILTER_PATH + ID_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(userFilterRQ)) - .contentType(APPLICATION_JSON)) + MvcResult mvcResult = mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + FILTER_PATH + ID_PATH).with( + token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(userFilterRQ)).contentType(APPLICATION_JSON)) .andExpect(status().isBadRequest()).andReturn(); //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), - ErrorRS.class); + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); assertEquals(INCORRECT_REQUEST, error.getErrorType()); assertEquals(INCORRECT_REQUEST_MESSAGE + FIELD_NAME_IS_NULL_MESSAGE, error.getMessage()); } @@ -187,15 +184,15 @@ public void updateFilterShouldReturnErrorWhenNameIsEmpty() throws Exception { userFilterRQ.setName(EMPTY); //WHEN - MvcResult mvcResult = mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + FILTER_PATH + ID_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(userFilterRQ)) - .contentType(APPLICATION_JSON)) + MvcResult mvcResult = mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + FILTER_PATH + ID_PATH).with( + token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(userFilterRQ)).contentType(APPLICATION_JSON)) .andExpect(status().isBadRequest()).andReturn(); //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), - ErrorRS.class); + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); assertEquals(INCORRECT_REQUEST, error.getErrorType()); assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_IS_BLANK_MESSAGE + " " + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); @@ -208,15 +205,15 @@ public void updateFilterShouldReturnErrorWhenNameConsistsOfWhitespaces() throws userFilterRQ.setName(WHITESPACES_NAME_VALUE); //WHEN - MvcResult mvcResult = mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + FILTER_PATH + ID_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(userFilterRQ)) - .contentType(APPLICATION_JSON)) + MvcResult mvcResult = mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + FILTER_PATH + ID_PATH).with( + token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(userFilterRQ)).contentType(APPLICATION_JSON)) .andExpect(status().isBadRequest()).andReturn(); //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), - ErrorRS.class); + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); assertEquals(INCORRECT_REQUEST, error.getErrorType()); assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_IS_BLANK_MESSAGE + " " + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); @@ -229,18 +226,19 @@ public void updateFilterShouldReturnErrorWhenNameIsLessThanThreeCharacters() thr userFilterRQ.setName(SHORT_NAME_VALUE); //WHEN - MvcResult mvcResult = mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + FILTER_PATH + ID_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(userFilterRQ)) - .contentType(APPLICATION_JSON)) + MvcResult mvcResult = mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + FILTER_PATH + ID_PATH).with( + token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(userFilterRQ)).contentType(APPLICATION_JSON)) .andExpect(status().isBadRequest()).andReturn(); //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), - ErrorRS.class); + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); assertEquals(INCORRECT_REQUEST, error.getErrorType()); assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_SIZE_MESSAGE + "] ", - error.getMessage()); + error.getMessage() + ); } @Test @@ -251,18 +249,19 @@ public void updateFilterShouldReturnErrorWhenNameIsGreaterThanOneHundredAndTwent userFilterRQ.setName(LONG_NAME_VALUE); //WHEN - MvcResult mvcResult = mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + FILTER_PATH + ID_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(userFilterRQ)) - .contentType(APPLICATION_JSON)) + MvcResult mvcResult = mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + FILTER_PATH + ID_PATH).with( + token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(userFilterRQ)).contentType(APPLICATION_JSON)) .andExpect(status().isBadRequest()).andReturn(); //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), - ErrorRS.class); + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); assertEquals(INCORRECT_REQUEST, error.getErrorType()); assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_SIZE_MESSAGE + "] ", - error.getMessage()); + error.getMessage() + ); } private UpdateUserFilterRQ prepareFilter() { diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/WidgetControllerTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/WidgetControllerTest.java index 22a8d60233..f65d3909dd 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/WidgetControllerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/WidgetControllerTest.java @@ -16,835 +16,864 @@ package com.epam.ta.reportportal.ws.controller; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import com.epam.ta.reportportal.dao.WidgetRepository; import com.epam.ta.reportportal.entity.widget.Widget; +import com.epam.ta.reportportal.model.EntryCreatedRS; +import com.epam.ta.reportportal.model.widget.ContentParameters; +import com.epam.ta.reportportal.model.widget.WidgetPreviewRQ; +import com.epam.ta.reportportal.model.widget.WidgetRQ; import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.EntryCreatedRS; -import com.epam.ta.reportportal.ws.model.widget.ContentParameters; -import com.epam.ta.reportportal.ws.model.widget.WidgetPreviewRQ; -import com.epam.ta.reportportal.ws.model.widget.WidgetRQ; import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Optional; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.servlet.MvcResult; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Optional; - -import static org.hamcrest.Matchers.hasSize; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.springframework.http.MediaType.APPLICATION_JSON; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * @author Ihar Kahadouski */ @Sql("/db/shareable/shareable-fill.sql") class WidgetControllerTest extends BaseMvcTest { - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private WidgetRepository widgetRepository; - - @Test - void createWidgetPositive() throws Exception { - WidgetRQ rq = new WidgetRQ(); - rq.setName("widget"); - rq.setDescription("description"); - rq.setWidgetType("oldLineChart"); - ContentParameters contentParameters = new ContentParameters(); - contentParameters.setContentFields(Collections.singletonList("statistics$executions$passed")); - contentParameters.setItemsCount(50); - rq.setFilterIds(Collections.singletonList(3L)); - rq.setContentParameters(contentParameters); - final MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/widget").with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(rq)) - .contentType(APPLICATION_JSON)).andExpect(status().isCreated()).andReturn(); - final EntryCreatedRS entryCreatedRS = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), EntryCreatedRS.class); - final Optional optionalWidget = widgetRepository.findById(entryCreatedRS.getId()); - assertTrue(optionalWidget.isPresent()); - assertEquals("widget", optionalWidget.get().getName()); - assertEquals("description", optionalWidget.get().getDescription()); - } - - @Test - void getWidgetPositive() throws Exception { - mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/widget/10").with(token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk()); - } - - @Test - void updateWidgetPositive() throws Exception { - final WidgetRQ rq = new WidgetRQ(); - rq.setName("updated"); - rq.setDescription("updated"); - rq.setWidgetType("activityStream"); - final ContentParameters contentParameters = new ContentParameters(); - contentParameters.setContentFields(Arrays.asList("number", "start_time", "user")); - contentParameters.setItemsCount(50); - rq.setContentParameters(contentParameters); - mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/widget/12").with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(rq)) - .contentType(APPLICATION_JSON)).andExpect(status().isOk()); - final Optional optionalWidget = widgetRepository.findById(12L); - assertTrue(optionalWidget.isPresent()); - assertEquals("updated", optionalWidget.get().getName()); - assertEquals("updated", optionalWidget.get().getDescription()); - } - - @Test - void updateNonExistingWidget() throws Exception { - WidgetRQ rq = new WidgetRQ(); - rq.setName("name"); - rq.setWidgetType("oldLineChart"); - var contextParams = new ContentParameters(); - contextParams.setItemsCount(1); - contextParams.setContentFields(Collections.singletonList("test")); - rq.setContentParameters(contextParams); - mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/widget/100").with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(rq)) - .contentType(APPLICATION_JSON)).andExpect(status().isNotFound()); - } - - @Test - void updateWidgetWithDuplicatedName() throws Exception { - final WidgetRQ rq = new WidgetRQ(); - rq.setName("LAUNCH STATISTICS"); - rq.setDescription("updated"); - rq.setWidgetType("activityStream"); - final ContentParameters contentParameters = new ContentParameters(); - contentParameters.setContentFields(Arrays.asList("number", "start_time", "user")); - contentParameters.setItemsCount(50); - rq.setContentParameters(contentParameters); - mockMvc.perform(put(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken())) - .content(objectMapper.writeValueAsBytes(rq)) - .contentType(APPLICATION_JSON)).andExpect(status().isConflict()); - } - - @Test - void getSharedWidgetsListPositive() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/shared").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isBadRequest()); - } - - @Test - void searchSharedWidgetsListPositive() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/shared/search?term=ch").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isNotFound()); - } - - @Test - void getWidgetNamesPositive() throws Exception { - mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/widget/names/all").with(token(oAuthHelper.getDefaultToken()))) - .andExpect(status().is(200)); - } - - @Test - void getWidgetPreview() throws Exception { - WidgetPreviewRQ request = new WidgetPreviewRQ(); - request.setWidgetType("launchStatistics"); - final ContentParameters contentParameters = new ContentParameters(); - final HashMap widgetOptions = new HashMap<>(); - widgetOptions.put("timeline", "WEEK"); - contentParameters.setWidgetOptions(widgetOptions); - contentParameters.setItemsCount(20); - contentParameters.setContentFields(Arrays.asList( - "statistics$executions$total", - "statistics$executions$passed", - "statistics$executions$failed", - "statistics$executions$skipped" - )); - request.setContentParameters(contentParameters); - request.setFilterIds(Collections.singletonList(4L)); - - mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/widget/preview").with(token(oAuthHelper.getDefaultToken())) - .contentType(APPLICATION_JSON) - .content(objectMapper.writeValueAsBytes(request))).andExpect(status().isOk()); - } - - @Sql("/db/widget/launch-statistics.sql") - @Test - void getLaunchStatisticsWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("launch stats")) - .andExpect(jsonPath("$.widgetType").value("launchStatistics")) - .andExpect(jsonPath("$.content.result[0].name").value("test launch")) - .andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("1")) - .andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("1")) - .andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value("1")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("2")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5")); - } - - @Sql("/db/widget/not-passed.sql") - @Test - void getNotPassedWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("not passed")) - .andExpect(jsonPath("$.widgetType").value("notPassed")) - .andExpect(jsonPath("$.content.result[0].name").value("test launch")) - .andExpect(jsonPath("$.content.result[0].values.*").value("60.0")); - } - - @Sql("/db/widget/not-passed.sql") - @Test - void getEmptyContentNotPassedWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/launches-comparison-chart.sql") - @Test - void getLaunchesComparisonWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("launch comparison")) - .andExpect(jsonPath("$.widgetType").value("launchesComparisonChart")) - .andExpect(jsonPath("$.content.result[0].name").value("test launch")) - .andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("33.33")) - .andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("33.33")) - .andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value("33.33")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("60.0")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("40.0")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5.0")) - .andExpect(jsonPath("$.content.result[1].name").value("test launch")) - .andExpect(jsonPath("$.content.result[1].values.statistics$defects$product_bug$pb001").value("33.33")) - .andExpect(jsonPath("$.content.result[1].values.statistics$defects$to_investigate$ti001").value("66.67")) - .andExpect(jsonPath("$.content.result[1].values.statistics$executions$failed").value("60.0")) - .andExpect(jsonPath("$.content.result[1].values.statistics$executions$passed").value("20.0")) - .andExpect(jsonPath("$.content.result[1].values.statistics$executions$skipped").value("20.0")) - .andExpect(jsonPath("$.content.result[1].values.statistics$executions$total").value("5.0")); - } - - @Sql("/db/widget/launches-comparison-chart.sql") - @Test - void getEmptyContentLaunchesComparisonWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("launch comparison")) - .andExpect(jsonPath("$.widgetType").value("launchesComparisonChart")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/launches-duration-chart.sql") - @Test - void getLaunchesDurationWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("launches duration")) - .andExpect(jsonPath("$.widgetType").value("launchesDurationChart")) - .andExpect(jsonPath("$.content.result[0].name").value("test launch")) - .andExpect(jsonPath("$.content.result[0].duration").value("540000")) - .andExpect(jsonPath("$.content.result[1].name").value("test launch")) - .andExpect(jsonPath("$.content.result[1].duration").value("660000")); - } - - @Sql("/db/widget/launches-duration-chart.sql") - @Test - void getEmptyContentLaunchesDurationWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("launches duration")) - .andExpect(jsonPath("$.widgetType").value("launchesDurationChart")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/bug-trend.sql") - @Test - void getBugTrendWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("bug trend")) - .andExpect(jsonPath("$.widgetType").value("bugTrend")) - .andExpect(jsonPath("$.content.result[0].name").value("test launch")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3")) - .andExpect(jsonPath("$.content.result[0].values.total").value("3")) - .andExpect(jsonPath("$.content.result[1].name").value("test launch")) - .andExpect(jsonPath("$.content.result[1].values.statistics$executions$failed").value("3")) - .andExpect(jsonPath("$.content.result[1].values.total").value("3")); - } - - @Sql("/db/widget/launches-table.sql") - @Test - void getLaunchesTableWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("launches table")) - .andExpect(jsonPath("$.widgetType").value("launchesTable")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$skipped").value("1")) - .andExpect(jsonPath("$.content.result[0].values.status").value("FAILED")) - .andExpect(jsonPath("$.content.result[0].values.description").value("desc")) - .andExpect(jsonPath("$.content.result[0].values.user").value("superadmin")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("1")) - .andExpect(jsonPath("$..attributes[?(@.value == 'value1')]").exists()) - .andExpect(jsonPath("$..attributes[?(@.value == 'value')]").exists()) - .andReturn(); - } - - @Sql("/db/widget/launches-table.sql") - @Test - void getEmptyContentLaunchesTableWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("launches table")) - .andExpect(jsonPath("$.widgetType").value("launchesTable")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/top-test-cases.sql") - @Test - void getTopTestCasesWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("top test cases")) - .andExpect(jsonPath("$.widgetType").value("topTestCases")) - .andExpect(jsonPath("$.content.latestLaunch.name").value("test launch")) - .andExpect(jsonPath("$.content.result[0].name").value("test item 5")) - .andExpect(jsonPath("$.content.result[0].total").value("1")) - .andExpect(jsonPath("$.content.result[1].name").value("test item 2")) - .andExpect(jsonPath("$.content.result[1].total").value("1")) - .andExpect(jsonPath("$.content.result[2].name").value("test item 3")) - .andExpect(jsonPath("$.content.result[2].total").value("1")); - } - - @Sql("/db/widget/top-test-cases.sql") - @Test - void getEmptyContentTopTestCasesWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("top test cases")) - .andExpect(jsonPath("$.widgetType").value("topTestCases")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/top-test-cases.sql") - @Test - void getTopTestCasesWidgetWithNotExistLaunch() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/top-test-cases.sql") - @Test - void getTopTestCasesIncludeMethodsWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("top test cases")) - .andExpect(jsonPath("$.widgetType").value("topTestCases")) - .andExpect(jsonPath("$.content.latestLaunch.name").value("test launch")) - .andExpect(jsonPath("$.content.result[0].name").value("test item 5")) - .andExpect(jsonPath("$.content.result[0].total").value("1")) - .andExpect(jsonPath("$.content.result[1].name").value("test item 2")) - .andExpect(jsonPath("$.content.result[1].total").value("1")) - .andExpect(jsonPath("$.content.result[2].name").value("test item 3")) - .andExpect(jsonPath("$.content.result[2].total").value("1")); - } - - @Sql("/db/widget/flaky-test-cases.sql") - @Test - void getFlakyTestCasesWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("flaky test cases")) - .andExpect(jsonPath("$.widgetType").value("flakyTestCases")) - .andExpect(jsonPath("$.content.latestLaunch.name").value("test launch")) - .andExpect(jsonPath("$.content.flaky[0].flakyCount").value("1")) - .andExpect(jsonPath("$.content.flaky[0].itemName").value("test item 4")); - } - - @Sql("/db/widget/flaky-test-cases.sql") - @Test - void getFlakyTestCasesWidgetWithNotExistLaunch() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()); - } - - @Sql("/db/widget/flaky-test-cases.sql") - @Test - void getEmptyContentFlakyTestCasesWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("flaky test cases")) - .andExpect(jsonPath("$.widgetType").value("flakyTestCases")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/flaky-test-cases.sql") - @Test - void getFlakyTestCasesWithIncludeMethodsWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("flaky test cases")) - .andExpect(jsonPath("$.widgetType").value("flakyTestCases")) - .andExpect(jsonPath("$.content.latestLaunch.name").value("test launch")) - .andExpect(jsonPath("$.content.flaky[0].flakyCount").value("1")) - .andExpect(jsonPath("$.content.flaky[0].itemName").value("test item 4")); - } - - @Sql("/db/widget/cases-trend.sql") - @Test - void getCasesTrendWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("cases trend")) - .andExpect(jsonPath("$.widgetType").value("casesTrend")) - .andExpect(jsonPath("$.content.result[0].name").value("test launch")) - .andExpect(jsonPath("$.content.result[0].number").value("1")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5")) - .andExpect(jsonPath("$.content.result[1].name").value("test launch")) - .andExpect(jsonPath("$.content.result[1].number").value("2")) - .andExpect(jsonPath("$.content.result[1].values.statistics$executions$total").value("5")); - } - - @Sql("/db/widget/cases-trend.sql") - @Test - void getCasesTrendWidgetWithTimeline() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("cases trend")) - .andExpect(jsonPath("$.widgetType").value("casesTrend")) - .andExpect(jsonPath("$.content.result.*.name").value("test launch")) - .andExpect(jsonPath("$.content.result.*.number").value(2)) - .andExpect(jsonPath("$.content.result.*.values.statistics$executions$total").value("5")); - } - - @Sql("/db/widget/cases-trend.sql") - @Test - void getEmptyContentCasesTrendWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/6").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("cases trend")) - .andExpect(jsonPath("$.widgetType").value("casesTrend")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/cases-trend.sql") - @Test - void getCasesTrendWidgetWithWrongTimeLineOption() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/7").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("cases trend")) - .andExpect(jsonPath("$.widgetType").value("casesTrend")) - .andExpect(jsonPath("$.content.result[0].name").value("test launch")) - .andExpect(jsonPath("$.content.result[0].number").value("1")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5")) - .andExpect(jsonPath("$.content.result[1].name").value("test launch")) - .andExpect(jsonPath("$.content.result[1].number").value("2")) - .andExpect(jsonPath("$.content.result[1].values.statistics$executions$total").value("5")); - } - - @Sql("/db/widget/cases-trend.sql") - @Test - void getCasesTrendWidgetWithDescOrdering() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/8").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("cases trend")) - .andExpect(jsonPath("$.widgetType").value("casesTrend")) - .andExpect(jsonPath("$.content.result.*.name").value("test launch")) - .andExpect(jsonPath("$.content.result.*.number").value(2)) - .andExpect(jsonPath("$.content.result.*.values.statistics$executions$total").value("5")); - } - - @Sql("/db/widget/passing-rate-per-launch.sql") - @Test - void getPassingRatePerLaunchWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("passing rate per launch")) - .andExpect(jsonPath("$.widgetType").value("passingRatePerLaunch")) - .andExpect(jsonPath("$.content.result.passed").value("1")) - .andExpect(jsonPath("$.content.result.total").value("5")) - .andReturn(); - } - - @Sql("/db/widget/passing-rate-per-launch.sql") - @Test - void getEmptyContentPassingRatePerLaunchWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("passing rate per launch")) - .andExpect(jsonPath("$.widgetType").value("passingRatePerLaunch")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/passing-rate-per-launch.sql") - @Test - void getPassingRatePerLaunchWidgetWithNotExistLaunchName() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()); - } - - @Sql("/db/widget/passing-rate-summary.sql") - @Test - void getPassingRateSummaryWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("passing rate summary")) - .andExpect(jsonPath("$.widgetType").value("passingRateSummary")) - .andExpect(jsonPath("$.content.result.passed").value("3")) - .andExpect(jsonPath("$.content.result.total").value("10")); - } - - @Sql("/db/widget/passing-rate-summary.sql") - @Test - void getEmptyContentPassingRateSummaryWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/old-line-chart.sql") - @Test - void getOldLineChartWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("old line chart")) - .andExpect(jsonPath("$.widgetType").value("oldLineChart")) - .andExpect(jsonPath("$.content.result[0].name").value("test launch")) - .andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("1")) - .andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("1")) - .andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value("1")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("2")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5")); - } - - @Sql("/db/widget/old-line-chart.sql") - @Test - void getEmptyContentOldLineChartWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("old line chart")) - .andExpect(jsonPath("$.widgetType").value("oldLineChart")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/old-line-chart.sql") - @Test - void getOldLineChartWithTimeLineWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("old line chart")) - .andExpect(jsonPath("$.widgetType").value("oldLineChart")) - .andExpect(jsonPath("$.content.result.*.values.statistics$defects$automation_bug$ab001").value("1.0")) - .andExpect(jsonPath("$.content.result.*.values.statistics$defects$product_bug$pb001").value("1.0")) - .andExpect(jsonPath("$.content.result.*.values.statistics$defects$automation_bug$ab001").value("1.0")) - .andExpect(jsonPath("$.content.result.*.values.statistics$executions$failed").value("3.0")) - .andExpect(jsonPath("$.content.result.*.values.statistics$executions$passed").value("2.0")) - .andExpect(jsonPath("$.content.result.*.values.statistics$executions$total").value("5.0")); - } - - @Sql("/db/widget/old-line-chart.sql") - @Test - void getEmptyContentOldLineChartWithTimeLineWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/6").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("old line chart")) - .andExpect(jsonPath("$.widgetType").value("oldLineChart")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/old-line-chart.sql") - @Test - void getOldLineChartWidgetWithIncorrectTimeLine() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/7").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("old line chart")) - .andExpect(jsonPath("$.widgetType").value("oldLineChart")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/investigated-trend.sql") - @Test - void getInvestigatedTrendWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("investigated trend")) - .andExpect(jsonPath("$.widgetType").value("investigatedTrend")) - .andExpect(jsonPath("$.content.result[0].name").value("test launch")) - .andExpect(jsonPath("$.content.result[0].number").value("1")) - .andExpect(jsonPath("$.content.result[0].values.toInvestigate").value("33.33")) - .andExpect(jsonPath("$.content.result[0].values.investigated").value("66.67")) - .andExpect(jsonPath("$.content.result[1].name").value("test launch")) - .andExpect(jsonPath("$.content.result[1].number").value("2")) - .andExpect(jsonPath("$.content.result[1].values.toInvestigate").value("66.67")) - .andExpect(jsonPath("$.content.result[1].values.investigated").value("33.33")); - } - - //Waiting for fix - @Disabled - @Sql("/db/widget/investigated-trend.sql") - @Test - void getInvestigatedTrendWidgetWithTimeline() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("investigated trend")) - .andExpect(jsonPath("$.widgetType").value("investigatedTrend")); - } - - @Sql("/db/widget/unique-bug-table.sql") - @Test - void getUniqueBugTableWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("unique bug table")) - .andExpect(jsonPath("$.widgetType").value("uniqueBugTable")) - .andExpect(jsonPath("$.content.result.ticket1.submitter").value("superadmin")) - .andExpect(jsonPath("$.content.result.ticket1.url").value("http:/example.com/ticket1")) - .andExpect(jsonPath("$.content.result.ticket1.items[0].launchId").value(1)) - .andExpect(jsonPath("$.content.result.ticket1.items[0].itemName").value("test item 2")) - .andExpect(jsonPath("$.content.result.ticket1.items[0].itemId").value(2)) - .andExpect(jsonPath("$.content.result.ticket1.items[0].attributes", hasSize(2))); - } - - @Sql("/db/widget/unique-bug-table.sql") - @Test - void getEmptyContentUniqueBugTableWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("unique bug table")) - .andExpect(jsonPath("$.widgetType").value("uniqueBugTable")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/most-time-consuming.sql") - @Test - void getMostTimeConsumingWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("most time consuming")) - .andExpect(jsonPath("$.widgetType").value("mostTimeConsuming")) - .andExpect(jsonPath("$.content.result[0].name").value("test item 3")) - .andExpect(jsonPath("$.content.result[0].duration").value("337.0")) - .andExpect(jsonPath("$.content.result[1].name").value("test item 5")) - .andExpect(jsonPath("$.content.result[1].duration").value("251.0")) - .andExpect(jsonPath("$.content.result[2].name").value("test item 2")) - .andExpect(jsonPath("$.content.result[2].duration").value("192.0")) - .andExpect(jsonPath("$.content.result[3].name").value("test item 1")) - .andExpect(jsonPath("$.content.result[3].duration").value("165.0")) - .andExpect(jsonPath("$.content.result[4].name").value("test item 4")) - .andExpect(jsonPath("$.content.result[4].duration").value("87.0")); - } - - @Sql("/db/widget/most-time-consuming.sql") - @Test - void getEmptyContentMostTimeConsumingWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("most time consuming")) - .andExpect(jsonPath("$.widgetType").value("mostTimeConsuming")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/most-time-consuming.sql") - @Test - void getMostTimeConsumingWidgetWithNotExistLaunch() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()); - } - - @Sql("/db/widget/most-time-consuming.sql") - @Test - void getMostTimeConsumingWidgetWithIncludeMethods() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/6").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("most time consuming")) - .andExpect(jsonPath("$.widgetType").value("mostTimeConsuming")) - .andExpect(jsonPath("$.content.result[0].name").value("test item 3")) - .andExpect(jsonPath("$.content.result[0].duration").value("337.0")) - .andExpect(jsonPath("$.content.result[1].name").value("test item 5")) - .andExpect(jsonPath("$.content.result[1].duration").value("251.0")) - .andExpect(jsonPath("$.content.result[2].name").value("test item 2")) - .andExpect(jsonPath("$.content.result[2].duration").value("192.0")) - .andExpect(jsonPath("$.content.result[3].name").value("test item 1")) - .andExpect(jsonPath("$.content.result[3].duration").value("165.0")) - .andExpect(jsonPath("$.content.result[4].name").value("test item 4")) - .andExpect(jsonPath("$.content.result[4].duration").value("87.0")); - } - - @Sql("/db/widget/overall-statistics.sql") - @Test - void getOverallStatisticsWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("overall statistics")) - .andExpect(jsonPath("$.widgetType").value("overallStatistics")) - .andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("1")) - .andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("1")) - .andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value("1")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("2")) - .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5")); - } - - @Sql("/db/widget/overall-statistics.sql") - @Test - void getEmptyContentOverallStatisticsWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("overall statistics")) - .andExpect(jsonPath("$.widgetType").value("overallStatistics")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/activity-stream.sql") - @Test - void getActivityStreamWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("activity stream")) - .andExpect(jsonPath("$.widgetType").value("activityStream")) - .andExpect(jsonPath("$.content.result[0].user").value("superadmin")) - .andExpect(jsonPath("$.content.result[0].actionType").value("startLaunch")) - .andExpect(jsonPath("$.content.result[0].objectType").value("LAUNCH")) - .andExpect(jsonPath("$.content.result[1].user").value("superadmin")) - .andExpect(jsonPath("$.content.result[1].actionType").value("updateItem")) - .andExpect(jsonPath("$.content.result[1].objectType").value("ITEM")) - .andExpect(jsonPath("$.content.result[2].user").value("superadmin")) - .andExpect(jsonPath("$.content.result[2].actionType").value("deleteLaunch")) - .andExpect(jsonPath("$.content.result[2].objectType").value("LAUNCH")); - } - - @Sql("/db/widget/activity-stream.sql") - @Test - void getEmptyContentActivityStreamWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("activity stream")) - .andExpect(jsonPath("$.widgetType").value("activityStream")) - .andExpect(jsonPath("$.content").isEmpty()); - } - - @Sql("/db/widget/activity-stream.sql") - @Test - void getActivityStreamWidgetWithNotExistUser() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isNotFound()); - } - - @Sql("/db/widget/activity-stream.sql") - @Test - void getActivityStreamWidgetWithEmptyUserOption() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("activity stream")) - .andExpect(jsonPath("$.widgetType").value("activityStream")) - .andExpect(jsonPath("$.content.result[0].user").value("superadmin")) - .andExpect(jsonPath("$.content.result[0].actionType").value("startLaunch")) - .andExpect(jsonPath("$.content.result[0].objectType").value("LAUNCH")) - .andExpect(jsonPath("$.content.result[1].user").value("superadmin")) - .andExpect(jsonPath("$.content.result[1].actionType").value("updateItem")) - .andExpect(jsonPath("$.content.result[1].objectType").value("ITEM")) - .andExpect(jsonPath("$.content.result[2].user").value("superadmin")) - .andExpect(jsonPath("$.content.result[2].actionType").value("deleteLaunch")) - .andExpect(jsonPath("$.content.result[2].objectType").value("LAUNCH")); - } - - @Sql("/db/widget/product-status.sql") - @Test - void getProductStatusGroupedByLaunchWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("product status")) - .andExpect(jsonPath("$.widgetType").value("productStatus")) - .andExpect(jsonPath("$.content.result[0].name").value("test launch")) - .andExpect(jsonPath("$.content.result[0].number").value("1")) - .andExpect(jsonPath("$.content.result[0].attributes").isNotEmpty()) - .andExpect(jsonPath("$.content.result[0].passingRate").value("40.0")) - .andExpect(jsonPath("$.content.result[1].name").value("test launch")) - .andExpect(jsonPath("$.content.result[1].number").value("2")) - .andExpect(jsonPath("$.content.result[1].attributes").doesNotExist()) - .andExpect(jsonPath("$.content.result[1].passingRate").value("20.0")) - .andExpect(jsonPath("$.content.result[2].sum.statistics$executions$passed").value("3")) - .andExpect(jsonPath("$.content.result[2].sum.statistics$executions$skipped").value("1")) - .andExpect(jsonPath("$.content.result[2].sum.statistics$defects$to_investigate$ti001").value("3")) - .andExpect(jsonPath("$.content.result[2].sum.statistics$defects$product_bug$pb001").value("2")) - .andExpect(jsonPath("$.content.result[2].sum.statistics$defects$automation_bug$ab001").value("1")) - .andExpect(jsonPath("$.content.result[2].sum.statistics$executions$failed").value("6")) - .andExpect(jsonPath("$.content.result[2].sum.statistics$executions$total").value("10")) - .andExpect(jsonPath("$.content.result[2].averagePassingRate").value("30.0")); - } - - @Sql("/db/widget/component-health-check.sql") - @Test - void getComponentHealthCheckContent() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL - + "/widget/multilevel/2?attributes=3.29.11.0,arch").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("health")) - .andExpect(jsonPath("$.widgetType").value("componentHealthCheck")) - .andExpect(jsonPath("$.content.result[0].attributeValue").value("android")) - .andExpect(jsonPath("$.content.result[0].total").value("1")) - .andExpect(jsonPath("$.content.result[0].passingRate").value("0.0")) - .andExpect(jsonPath("$.content.result[1].attributeValue").value("ios")) - .andExpect(jsonPath("$.content.result[1].total").value("1")) - .andExpect(jsonPath("$.content.result[1].passingRate").value("0.0")); - } - - @Sql("/db/widget/product-status.sql") - @Test - void getEmptyContentProductStatusGroupedByLaunchWidget() throws Exception { - mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken()))) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("product status")) - .andExpect(jsonPath("$.widgetType").value("productStatus")) - .andExpect(jsonPath("$.content").isEmpty()); - } -} \ No newline at end of file + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private WidgetRepository widgetRepository; + + @Test + void createWidgetPositive() throws Exception { + WidgetRQ rq = new WidgetRQ(); + rq.setName("widget"); + rq.setDescription("description"); + rq.setWidgetType("oldLineChart"); + ContentParameters contentParameters = new ContentParameters(); + contentParameters.setContentFields(Collections.singletonList("statistics$executions$passed")); + contentParameters.setItemsCount(50); + rq.setFilterIds(Collections.singletonList(3L)); + rq.setContentParameters(contentParameters); + final MvcResult mvcResult = mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + "/widget").with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(rq)).contentType(APPLICATION_JSON)) + .andExpect(status().isCreated()).andReturn(); + final EntryCreatedRS entryCreatedRS = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), EntryCreatedRS.class); + final Optional optionalWidget = widgetRepository.findById(entryCreatedRS.getId()); + assertTrue(optionalWidget.isPresent()); + assertEquals("widget", optionalWidget.get().getName()); + assertEquals("description", optionalWidget.get().getDescription()); + } + + @Test + void getWidgetPositive() throws Exception { + mockMvc.perform( + get(DEFAULT_PROJECT_BASE_URL + "/widget/10").with(token(oAuthHelper.getDefaultToken()))) + .andExpect(status().isOk()); + } + + @Test + void updateWidgetPositive() throws Exception { + final WidgetRQ rq = new WidgetRQ(); + rq.setName("updated"); + rq.setDescription("updated"); + rq.setWidgetType("activityStream"); + final ContentParameters contentParameters = new ContentParameters(); + contentParameters.setContentFields(Arrays.asList("number", "start_time", "user")); + contentParameters.setItemsCount(50); + rq.setContentParameters(contentParameters); + mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + "/widget/12").with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(rq)).contentType(APPLICATION_JSON)) + .andExpect(status().isOk()); + final Optional optionalWidget = widgetRepository.findById(12L); + assertTrue(optionalWidget.isPresent()); + assertEquals("updated", optionalWidget.get().getName()); + assertEquals("updated", optionalWidget.get().getDescription()); + } + + @Test + void updateNonExistingWidget() throws Exception { + WidgetRQ rq = new WidgetRQ(); + rq.setName("name"); + rq.setWidgetType("oldLineChart"); + var contextParams = new ContentParameters(); + contextParams.setItemsCount(1); + contextParams.setContentFields(Collections.singletonList("test")); + rq.setContentParameters(contextParams); + mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + "/widget/100").with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(rq)).contentType(APPLICATION_JSON)) + .andExpect(status().isNotFound()); + } + + @Test + void updateWidgetWithDuplicatedName() throws Exception { + final WidgetRQ rq = new WidgetRQ(); + rq.setName("LAUNCH STATISTICS"); + rq.setDescription("updated"); + rq.setWidgetType("activityStream"); + final ContentParameters contentParameters = new ContentParameters(); + contentParameters.setContentFields(Arrays.asList("number", "start_time", "user")); + contentParameters.setItemsCount(50); + rq.setContentParameters(contentParameters); + mockMvc.perform( + put(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken())) + .content(objectMapper.writeValueAsBytes(rq)).contentType(APPLICATION_JSON)) + .andExpect(status().isConflict()); + } + + @Test + void getSharedWidgetsListPositive() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/shared").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isBadRequest()); + } + + @Test + void searchSharedWidgetsListPositive() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/shared/search?term=ch").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isNotFound()); + } + + @Test + void getWidgetNamesPositive() throws Exception { + mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/widget/names/all").with( + token(oAuthHelper.getDefaultToken()))).andExpect(status().is(200)); + } + + @Test + void getWidgetPreview() throws Exception { + WidgetPreviewRQ request = new WidgetPreviewRQ(); + request.setWidgetType("launchStatistics"); + final ContentParameters contentParameters = new ContentParameters(); + final HashMap widgetOptions = new HashMap<>(); + widgetOptions.put("timeline", "WEEK"); + contentParameters.setWidgetOptions(widgetOptions); + contentParameters.setItemsCount(20); + contentParameters.setContentFields( + Arrays.asList("statistics$executions$total", "statistics$executions$passed", + "statistics$executions$failed", "statistics$executions$skipped" + )); + request.setContentParameters(contentParameters); + request.setFilterIds(Collections.singletonList(4L)); + + mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/widget/preview").with( + token(oAuthHelper.getDefaultToken())).contentType(APPLICATION_JSON) + .content(objectMapper.writeValueAsBytes(request))).andExpect(status().isOk()); + } + + @Sql("/db/widget/launch-statistics.sql") + @Test + void getLaunchStatisticsWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("launch stats")) + .andExpect(jsonPath("$.widgetType").value("launchStatistics")) + .andExpect(jsonPath("$.content.result[0].name").value("test launch")).andExpect( + jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("1")) + .andExpect( + jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("1")) + .andExpect( + jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value( + "1")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("2")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5")); + } + + @Sql("/db/widget/not-passed.sql") + @Test + void getNotPassedWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("not passed")) + .andExpect(jsonPath("$.widgetType").value("notPassed")) + .andExpect(jsonPath("$.content.result[0].name").value("test launch")) + .andExpect(jsonPath("$.content.result[0].values.*").value("60.0")); + } + + @Sql("/db/widget/not-passed.sql") + @Test + void getEmptyContentNotPassedWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/launches-comparison-chart.sql") + @Test + void getLaunchesComparisonWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("launch comparison")) + .andExpect(jsonPath("$.widgetType").value("launchesComparisonChart")) + .andExpect(jsonPath("$.content.result[0].name").value("test launch")).andExpect( + jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value( + "33.33")).andExpect( + jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("33.33")) + .andExpect( + jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value( + "33.33")).andExpect( + jsonPath("$.content.result[0].values.statistics$executions$failed").value("60.0")) + .andExpect( + jsonPath("$.content.result[0].values.statistics$executions$passed").value("40.0")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5.0")) + .andExpect(jsonPath("$.content.result[1].name").value("test launch")).andExpect( + jsonPath("$.content.result[1].values.statistics$defects$product_bug$pb001").value("33.33")) + .andExpect( + jsonPath("$.content.result[1].values.statistics$defects$to_investigate$ti001").value( + "66.67")).andExpect( + jsonPath("$.content.result[1].values.statistics$executions$failed").value("60.0")) + .andExpect( + jsonPath("$.content.result[1].values.statistics$executions$passed").value("20.0")) + .andExpect( + jsonPath("$.content.result[1].values.statistics$executions$skipped").value("20.0")) + .andExpect(jsonPath("$.content.result[1].values.statistics$executions$total").value("5.0")); + } + + @Sql("/db/widget/launches-comparison-chart.sql") + @Test + void getEmptyContentLaunchesComparisonWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("launch comparison")) + .andExpect(jsonPath("$.widgetType").value("launchesComparisonChart")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/launches-duration-chart.sql") + @Test + void getLaunchesDurationWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("launches duration")) + .andExpect(jsonPath("$.widgetType").value("launchesDurationChart")) + .andExpect(jsonPath("$.content.result[0].name").value("test launch")) + .andExpect(jsonPath("$.content.result[0].duration").value("540000")) + .andExpect(jsonPath("$.content.result[1].name").value("test launch")) + .andExpect(jsonPath("$.content.result[1].duration").value("660000")); + } + + @Sql("/db/widget/launches-duration-chart.sql") + @Test + void getEmptyContentLaunchesDurationWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("launches duration")) + .andExpect(jsonPath("$.widgetType").value("launchesDurationChart")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/bug-trend.sql") + @Test + void getBugTrendWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("bug trend")) + .andExpect(jsonPath("$.widgetType").value("bugTrend")) + .andExpect(jsonPath("$.content.result[0].name").value("test launch")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3")) + .andExpect(jsonPath("$.content.result[0].values.total").value("3")) + .andExpect(jsonPath("$.content.result[1].name").value("test launch")) + .andExpect(jsonPath("$.content.result[1].values.statistics$executions$failed").value("3")) + .andExpect(jsonPath("$.content.result[1].values.total").value("3")); + } + + @Sql("/db/widget/launches-table.sql") + @Test + void getLaunchesTableWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("launches table")) + .andExpect(jsonPath("$.widgetType").value("launchesTable")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$skipped").value("1")) + .andExpect(jsonPath("$.content.result[0].values.status").value("FAILED")) + .andExpect(jsonPath("$.content.result[0].values.description").value("desc")) + .andExpect(jsonPath("$.content.result[0].values.user").value("superadmin")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("1")) + .andExpect(jsonPath("$..attributes[?(@.value == 'value1')]").exists()) + .andExpect(jsonPath("$..attributes[?(@.value == 'value')]").exists()).andReturn(); + } + + @Sql("/db/widget/launches-table.sql") + @Test + void getEmptyContentLaunchesTableWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("launches table")) + .andExpect(jsonPath("$.widgetType").value("launchesTable")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/top-test-cases.sql") + @Test + void getTopTestCasesWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("top test cases")) + .andExpect(jsonPath("$.widgetType").value("topTestCases")) + .andExpect(jsonPath("$.content.latestLaunch.name").value("test launch")) + .andExpect(jsonPath("$.content.result[0].name").value("test item 5")) + .andExpect(jsonPath("$.content.result[0].total").value("1")) + .andExpect(jsonPath("$.content.result[1].name").value("test item 2")) + .andExpect(jsonPath("$.content.result[1].total").value("1")) + .andExpect(jsonPath("$.content.result[2].name").value("test item 3")) + .andExpect(jsonPath("$.content.result[2].total").value("1")); + } + + @Sql("/db/widget/top-test-cases.sql") + @Test + void getEmptyContentTopTestCasesWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("top test cases")) + .andExpect(jsonPath("$.widgetType").value("topTestCases")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/top-test-cases.sql") + @Test + void getTopTestCasesWidgetWithNotExistLaunch() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/top-test-cases.sql") + @Test + void getTopTestCasesIncludeMethodsWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("top test cases")) + .andExpect(jsonPath("$.widgetType").value("topTestCases")) + .andExpect(jsonPath("$.content.latestLaunch.name").value("test launch")) + .andExpect(jsonPath("$.content.result[0].name").value("test item 5")) + .andExpect(jsonPath("$.content.result[0].total").value("1")) + .andExpect(jsonPath("$.content.result[1].name").value("test item 2")) + .andExpect(jsonPath("$.content.result[1].total").value("1")) + .andExpect(jsonPath("$.content.result[2].name").value("test item 3")) + .andExpect(jsonPath("$.content.result[2].total").value("1")); + } + + @Sql("/db/widget/flaky-test-cases.sql") + @Test + void getFlakyTestCasesWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("flaky test cases")) + .andExpect(jsonPath("$.widgetType").value("flakyTestCases")) + .andExpect(jsonPath("$.content.latestLaunch.name").value("test launch")) + .andExpect(jsonPath("$.content.flaky[0].flakyCount").value("1")) + .andExpect(jsonPath("$.content.flaky[0].itemName").value("test item 4")); + } + + @Sql("/db/widget/flaky-test-cases.sql") + @Test + void getFlakyTestCasesWidgetWithNotExistLaunch() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()); + } + + @Sql("/db/widget/flaky-test-cases.sql") + @Test + void getEmptyContentFlakyTestCasesWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("flaky test cases")) + .andExpect(jsonPath("$.widgetType").value("flakyTestCases")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/flaky-test-cases.sql") + @Test + void getFlakyTestCasesWithIncludeMethodsWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("flaky test cases")) + .andExpect(jsonPath("$.widgetType").value("flakyTestCases")) + .andExpect(jsonPath("$.content.latestLaunch.name").value("test launch")) + .andExpect(jsonPath("$.content.flaky[0].flakyCount").value("1")) + .andExpect(jsonPath("$.content.flaky[0].itemName").value("test item 4")); + } + + @Sql("/db/widget/cases-trend.sql") + @Test + void getCasesTrendWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("cases trend")) + .andExpect(jsonPath("$.widgetType").value("casesTrend")) + .andExpect(jsonPath("$.content.result[0].name").value("test launch")) + .andExpect(jsonPath("$.content.result[0].number").value("1")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5")) + .andExpect(jsonPath("$.content.result[1].name").value("test launch")) + .andExpect(jsonPath("$.content.result[1].number").value("2")) + .andExpect(jsonPath("$.content.result[1].values.statistics$executions$total").value("5")); + } + + @Sql("/db/widget/cases-trend.sql") + @Test + void getCasesTrendWidgetWithTimeline() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("cases trend")) + .andExpect(jsonPath("$.widgetType").value("casesTrend")) + .andExpect(jsonPath("$.content.result.*.name").value("test launch")) + .andExpect(jsonPath("$.content.result.*.number").value(2)) + .andExpect(jsonPath("$.content.result.*.values.statistics$executions$total").value("5")); + } + + @Sql("/db/widget/cases-trend.sql") + @Test + void getEmptyContentCasesTrendWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/6").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("cases trend")) + .andExpect(jsonPath("$.widgetType").value("casesTrend")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/cases-trend.sql") + @Test + void getCasesTrendWidgetWithWrongTimeLineOption() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/7").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("cases trend")) + .andExpect(jsonPath("$.widgetType").value("casesTrend")) + .andExpect(jsonPath("$.content.result[0].name").value("test launch")) + .andExpect(jsonPath("$.content.result[0].number").value("1")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5")) + .andExpect(jsonPath("$.content.result[1].name").value("test launch")) + .andExpect(jsonPath("$.content.result[1].number").value("2")) + .andExpect(jsonPath("$.content.result[1].values.statistics$executions$total").value("5")); + } + + @Sql("/db/widget/cases-trend.sql") + @Test + void getCasesTrendWidgetWithDescOrdering() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/8").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("cases trend")) + .andExpect(jsonPath("$.widgetType").value("casesTrend")) + .andExpect(jsonPath("$.content.result.*.name").value("test launch")) + .andExpect(jsonPath("$.content.result.*.number").value(2)) + .andExpect(jsonPath("$.content.result.*.values.statistics$executions$total").value("5")); + } + + @Sql("/db/widget/passing-rate-per-launch.sql") + @Test + void getPassingRatePerLaunchWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("passing rate per launch")) + .andExpect(jsonPath("$.widgetType").value("passingRatePerLaunch")) + .andExpect(jsonPath("$.content.result.passed").value("1")) + .andExpect(jsonPath("$.content.result.total").value("5")).andReturn(); + } + + @Sql("/db/widget/passing-rate-per-launch.sql") + @Test + void getEmptyContentPassingRatePerLaunchWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("passing rate per launch")) + .andExpect(jsonPath("$.widgetType").value("passingRatePerLaunch")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/passing-rate-per-launch.sql") + @Test + void getPassingRatePerLaunchWidgetWithNotExistLaunchName() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()); + } + + @Sql("/db/widget/passing-rate-summary.sql") + @Test + void getPassingRateSummaryWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("passing rate summary")) + .andExpect(jsonPath("$.widgetType").value("passingRateSummary")) + .andExpect(jsonPath("$.content.result.passed").value("3")) + .andExpect(jsonPath("$.content.result.total").value("10")); + } + + @Sql("/db/widget/passing-rate-summary.sql") + @Test + void getEmptyContentPassingRateSummaryWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/old-line-chart.sql") + @Test + void getOldLineChartWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("old line chart")) + .andExpect(jsonPath("$.widgetType").value("oldLineChart")) + .andExpect(jsonPath("$.content.result[0].name").value("test launch")).andExpect( + jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("1")) + .andExpect( + jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("1")) + .andExpect( + jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value( + "1")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("2")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5")); + } + + @Sql("/db/widget/old-line-chart.sql") + @Test + void getEmptyContentOldLineChartWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("old line chart")) + .andExpect(jsonPath("$.widgetType").value("oldLineChart")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/old-line-chart.sql") + @Test + void getOldLineChartWithTimeLineWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("old line chart")) + .andExpect(jsonPath("$.widgetType").value("oldLineChart")).andExpect( + jsonPath("$.content.result.*.values.statistics$defects$automation_bug$ab001").value("1.0")) + .andExpect( + jsonPath("$.content.result.*.values.statistics$defects$product_bug$pb001").value("1.0")) + .andExpect( + jsonPath("$.content.result.*.values.statistics$defects$automation_bug$ab001").value( + "1.0")) + .andExpect(jsonPath("$.content.result.*.values.statistics$executions$failed").value("3.0")) + .andExpect(jsonPath("$.content.result.*.values.statistics$executions$passed").value("2.0")) + .andExpect(jsonPath("$.content.result.*.values.statistics$executions$total").value("5.0")); + } + + @Sql("/db/widget/old-line-chart.sql") + @Test + void getEmptyContentOldLineChartWithTimeLineWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/6").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("old line chart")) + .andExpect(jsonPath("$.widgetType").value("oldLineChart")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/old-line-chart.sql") + @Test + void getOldLineChartWidgetWithIncorrectTimeLine() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/7").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("old line chart")) + .andExpect(jsonPath("$.widgetType").value("oldLineChart")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/investigated-trend.sql") + @Test + void getInvestigatedTrendWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("investigated trend")) + .andExpect(jsonPath("$.widgetType").value("investigatedTrend")) + .andExpect(jsonPath("$.content.result[0].name").value("test launch")) + .andExpect(jsonPath("$.content.result[0].number").value("1")) + .andExpect(jsonPath("$.content.result[0].values.toInvestigate").value("33.33")) + .andExpect(jsonPath("$.content.result[0].values.investigated").value("66.67")) + .andExpect(jsonPath("$.content.result[1].name").value("test launch")) + .andExpect(jsonPath("$.content.result[1].number").value("2")) + .andExpect(jsonPath("$.content.result[1].values.toInvestigate").value("66.67")) + .andExpect(jsonPath("$.content.result[1].values.investigated").value("33.33")); + } + + //Waiting for fix + @Disabled + @Sql("/db/widget/investigated-trend.sql") + @Test + void getInvestigatedTrendWidgetWithTimeline() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("investigated trend")) + .andExpect(jsonPath("$.widgetType").value("investigatedTrend")); + } + + @Sql("/db/widget/unique-bug-table.sql") + @Test + void getUniqueBugTableWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("unique bug table")) + .andExpect(jsonPath("$.widgetType").value("uniqueBugTable")) + .andExpect(jsonPath("$.content.result.ticket1.submitter").value("superadmin")) + .andExpect(jsonPath("$.content.result.ticket1.url").value("http:/example.com/ticket1")) + .andExpect(jsonPath("$.content.result.ticket1.items[0].launchId").value(1)) + .andExpect(jsonPath("$.content.result.ticket1.items[0].itemName").value("test item 2")) + .andExpect(jsonPath("$.content.result.ticket1.items[0].itemId").value(2)) + .andExpect(jsonPath("$.content.result.ticket1.items[0].attributes", hasSize(2))); + } + + @Sql("/db/widget/unique-bug-table.sql") + @Test + void getEmptyContentUniqueBugTableWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("unique bug table")) + .andExpect(jsonPath("$.widgetType").value("uniqueBugTable")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/most-time-consuming.sql") + @Test + void getMostTimeConsumingWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("most time consuming")) + .andExpect(jsonPath("$.widgetType").value("mostTimeConsuming")) + .andExpect(jsonPath("$.content.result[0].name").value("test item 3")) + .andExpect(jsonPath("$.content.result[0].duration").value("337.0")) + .andExpect(jsonPath("$.content.result[1].name").value("test item 5")) + .andExpect(jsonPath("$.content.result[1].duration").value("251.0")) + .andExpect(jsonPath("$.content.result[2].name").value("test item 2")) + .andExpect(jsonPath("$.content.result[2].duration").value("192.0")) + .andExpect(jsonPath("$.content.result[3].name").value("test item 1")) + .andExpect(jsonPath("$.content.result[3].duration").value("165.0")) + .andExpect(jsonPath("$.content.result[4].name").value("test item 4")) + .andExpect(jsonPath("$.content.result[4].duration").value("87.0")); + } + + @Sql("/db/widget/most-time-consuming.sql") + @Test + void getEmptyContentMostTimeConsumingWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("most time consuming")) + .andExpect(jsonPath("$.widgetType").value("mostTimeConsuming")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/most-time-consuming.sql") + @Test + void getMostTimeConsumingWidgetWithNotExistLaunch() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()); + } + + @Sql("/db/widget/most-time-consuming.sql") + @Test + void getMostTimeConsumingWidgetWithIncludeMethods() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/6").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("most time consuming")) + .andExpect(jsonPath("$.widgetType").value("mostTimeConsuming")) + .andExpect(jsonPath("$.content.result[0].name").value("test item 3")) + .andExpect(jsonPath("$.content.result[0].duration").value("337.0")) + .andExpect(jsonPath("$.content.result[1].name").value("test item 5")) + .andExpect(jsonPath("$.content.result[1].duration").value("251.0")) + .andExpect(jsonPath("$.content.result[2].name").value("test item 2")) + .andExpect(jsonPath("$.content.result[2].duration").value("192.0")) + .andExpect(jsonPath("$.content.result[3].name").value("test item 1")) + .andExpect(jsonPath("$.content.result[3].duration").value("165.0")) + .andExpect(jsonPath("$.content.result[4].name").value("test item 4")) + .andExpect(jsonPath("$.content.result[4].duration").value("87.0")); + } + + @Sql("/db/widget/overall-statistics.sql") + @Test + void getOverallStatisticsWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("overall statistics")) + .andExpect(jsonPath("$.widgetType").value("overallStatistics")).andExpect( + jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("1")) + .andExpect( + jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("1")) + .andExpect( + jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value( + "1")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("2")) + .andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5")); + } + + @Sql("/db/widget/overall-statistics.sql") + @Test + void getEmptyContentOverallStatisticsWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("overall statistics")) + .andExpect(jsonPath("$.widgetType").value("overallStatistics")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/activity-stream.sql") + @Test + void getActivityStreamWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("activity stream")) + .andExpect(jsonPath("$.widgetType").value("activityStream")) + .andExpect(jsonPath("$.content.result[0].user").value("superadmin")) + .andExpect(jsonPath("$.content.result[0].actionType").value("startLaunch")) + .andExpect(jsonPath("$.content.result[0].objectType").value("LAUNCH")) + .andExpect(jsonPath("$.content.result[1].user").value("superadmin")) + .andExpect(jsonPath("$.content.result[1].actionType").value("updateItem")) + .andExpect(jsonPath("$.content.result[1].objectType").value("ITEM")) + .andExpect(jsonPath("$.content.result[2].user").value("superadmin")) + .andExpect(jsonPath("$.content.result[2].actionType").value("deleteLaunch")) + .andExpect(jsonPath("$.content.result[2].objectType").value("LAUNCH")); + } + + @Sql("/db/widget/activity-stream.sql") + @Test + void getEmptyContentActivityStreamWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("activity stream")) + .andExpect(jsonPath("$.widgetType").value("activityStream")) + .andExpect(jsonPath("$.content").isEmpty()); + } + + @Sql("/db/widget/activity-stream.sql") + @Test + void getActivityStreamWidgetWithNotExistUser() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isNotFound()); + } + + @Sql("/db/widget/activity-stream.sql") + @Test + void getActivityStreamWidgetWithEmptyUserOption() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("activity stream")) + .andExpect(jsonPath("$.widgetType").value("activityStream")) + .andExpect(jsonPath("$.content.result[0].user").value("superadmin")) + .andExpect(jsonPath("$.content.result[0].actionType").value("startLaunch")) + .andExpect(jsonPath("$.content.result[0].objectType").value("LAUNCH")) + .andExpect(jsonPath("$.content.result[1].user").value("superadmin")) + .andExpect(jsonPath("$.content.result[1].actionType").value("updateItem")) + .andExpect(jsonPath("$.content.result[1].objectType").value("ITEM")) + .andExpect(jsonPath("$.content.result[2].user").value("superadmin")) + .andExpect(jsonPath("$.content.result[2].actionType").value("deleteLaunch")) + .andExpect(jsonPath("$.content.result[2].objectType").value("LAUNCH")); + } + + @Sql("/db/widget/product-status.sql") + @Test + void getProductStatusGroupedByLaunchWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("product status")) + .andExpect(jsonPath("$.widgetType").value("productStatus")) + .andExpect(jsonPath("$.content.result[0].name").value("test launch")) + .andExpect(jsonPath("$.content.result[0].number").value("1")) + .andExpect(jsonPath("$.content.result[0].attributes").isNotEmpty()) + .andExpect(jsonPath("$.content.result[0].passingRate").value("40.0")) + .andExpect(jsonPath("$.content.result[1].name").value("test launch")) + .andExpect(jsonPath("$.content.result[1].number").value("2")) + .andExpect(jsonPath("$.content.result[1].attributes").doesNotExist()) + .andExpect(jsonPath("$.content.result[1].passingRate").value("20.0")) + .andExpect(jsonPath("$.content.result[2].sum.statistics$executions$passed").value("3")) + .andExpect(jsonPath("$.content.result[2].sum.statistics$executions$skipped").value("1")) + .andExpect( + jsonPath("$.content.result[2].sum.statistics$defects$to_investigate$ti001").value("3")) + .andExpect( + jsonPath("$.content.result[2].sum.statistics$defects$product_bug$pb001").value("2")) + .andExpect( + jsonPath("$.content.result[2].sum.statistics$defects$automation_bug$ab001").value("1")) + .andExpect(jsonPath("$.content.result[2].sum.statistics$executions$failed").value("6")) + .andExpect(jsonPath("$.content.result[2].sum.statistics$executions$total").value("10")) + .andExpect(jsonPath("$.content.result[2].averagePassingRate").value("30.0")); + } + + @Sql("/db/widget/component-health-check.sql") + @Test + void getComponentHealthCheckContent() throws Exception { + mockMvc.perform( + get(SUPERADMIN_PROJECT_BASE_URL + "/widget/multilevel/2?attributes=3.29.11.0,arch").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("health")) + .andExpect(jsonPath("$.widgetType").value("componentHealthCheck")) + .andExpect(jsonPath("$.content.result[0].attributeValue").value("android")) + .andExpect(jsonPath("$.content.result[0].total").value("1")) + .andExpect(jsonPath("$.content.result[0].passingRate").value("0.0")) + .andExpect(jsonPath("$.content.result[1].attributeValue").value("ios")) + .andExpect(jsonPath("$.content.result[1].total").value("1")) + .andExpect(jsonPath("$.content.result[1].passingRate").value("0.0")); + } + + @Sql("/db/widget/product-status.sql") + @Test + void getEmptyContentProductStatusGroupedByLaunchWidget() throws Exception { + mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with( + token(oAuthHelper.getSuperadminToken()))).andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.name").value("product status")) + .andExpect(jsonPath("$.widgetType").value("productStatus")) + .andExpect(jsonPath("$.content").isEmpty()); + } +} diff --git a/src/test/java/com/epam/ta/reportportal/ws/controller/WidgetControllerValidationTest.java b/src/test/java/com/epam/ta/reportportal/ws/controller/WidgetControllerValidationTest.java index 2abb2b8ae3..565b59bbac 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/controller/WidgetControllerValidationTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/controller/WidgetControllerValidationTest.java @@ -16,19 +16,15 @@ package com.epam.ta.reportportal.ws.controller; -import com.epam.ta.reportportal.ws.BaseMvcTest; -import com.epam.ta.reportportal.ws.model.ErrorRS; -import com.epam.ta.reportportal.ws.model.widget.ContentParameters; -import com.epam.ta.reportportal.ws.model.widget.WidgetRQ; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.web.servlet.MvcResult; - -import java.util.Arrays; - -import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.*; -import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_REQUEST; +import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.FIELD_NAME_IS_BLANK_MESSAGE; +import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.FIELD_NAME_IS_NULL_MESSAGE; +import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.FIELD_NAME_SIZE_MESSAGE_WITH_FORMAT; +import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.ID_PATH; +import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.INCORRECT_REQUEST_MESSAGE; +import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.LONG_NAME_VALUE; +import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.SHORT_NAME_VALUE; +import static com.epam.ta.reportportal.ws.controller.constants.ValidationTestsConstants.WHITESPACES_NAME_VALUE; +import static com.epam.ta.reportportal.ws.reporting.ErrorType.INCORRECT_REQUEST; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.http.MediaType.APPLICATION_JSON; @@ -36,214 +32,236 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import com.epam.ta.reportportal.model.widget.ContentParameters; +import com.epam.ta.reportportal.model.widget.WidgetRQ; +import com.epam.ta.reportportal.ws.BaseMvcTest; +import com.epam.ta.reportportal.ws.reporting.ErrorRS; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Arrays; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.web.servlet.MvcResult; + /** * @author Tatyana Gladysheva */ class WidgetControllerValidationTest extends BaseMvcTest { - private static final String WIDGET_PATH = "/widget"; - - private static final String FIELD_NAME_SIZE_MESSAGE = String.format(FIELD_NAME_SIZE_MESSAGE_WITH_FORMAT, 3, 128); - - @Autowired - private ObjectMapper objectMapper; - - @Test - public void createWidgetShouldReturnErrorWhenNameIsNull() throws Exception { - //GIVEN - WidgetRQ widgetRQ = prepareWidget(); - - //WHEN - MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(widgetRQ)) - .contentType(APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andReturn(); - - //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); - assertEquals(INCORRECT_REQUEST, error.getErrorType()); - assertEquals(INCORRECT_REQUEST_MESSAGE + FIELD_NAME_IS_NULL_MESSAGE, error.getMessage()); - } - - @Test - public void createWidgetShouldReturnErrorWhenNameIsEmpty() throws Exception { - //GIVEN - WidgetRQ widgetRQ = prepareWidget(); - widgetRQ.setName(EMPTY); - - //WHEN - MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(widgetRQ)) - .contentType(APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andReturn(); - - //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); - assertEquals(INCORRECT_REQUEST, error.getErrorType()); - assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_IS_BLANK_MESSAGE + " " + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); - } - - @Test - public void createWidgetShouldReturnErrorWhenNameConsistsOfWhitespaces() throws Exception { - //GIVEN - WidgetRQ widgetRQ = prepareWidget(); - widgetRQ.setName(WHITESPACES_NAME_VALUE); - - //WHEN - MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(widgetRQ)) - .contentType(APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andReturn(); - - //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); - assertEquals(INCORRECT_REQUEST, error.getErrorType()); - assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_IS_BLANK_MESSAGE + " " + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); - } - - @Test - public void createWidgetShouldReturnErrorWhenNameIsLessThanThreeCharacters() throws Exception { - //GIVEN - WidgetRQ widgetRQ = prepareWidget(); - widgetRQ.setName(SHORT_NAME_VALUE); - - //WHEN - MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(widgetRQ)) - .contentType(APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andReturn(); - - //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); - assertEquals(INCORRECT_REQUEST, error.getErrorType()); - assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); - } - - @Test - public void createWidgetShouldReturnErrorWhenNameIsGreaterThanOneHundredAndTwentyEightCharacters() throws Exception { - //GIVEN - WidgetRQ widgetRQ = prepareWidget(); - widgetRQ.setName(LONG_NAME_VALUE); - - //WHEN - MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(widgetRQ)) - .contentType(APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andReturn(); - - //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); - assertEquals(INCORRECT_REQUEST, error.getErrorType()); - assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); - } - - @Test - public void updateWidgetShouldReturnErrorWhenNameIsNull() throws Exception { - //GIVEN - WidgetRQ widgetRQ = prepareWidget(); - - //WHEN - MvcResult mvcResult = mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH + ID_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(widgetRQ)) - .contentType(APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andReturn(); - - //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); - assertEquals(INCORRECT_REQUEST, error.getErrorType()); - assertEquals(INCORRECT_REQUEST_MESSAGE + FIELD_NAME_IS_NULL_MESSAGE, error.getMessage()); - } - - @Test - public void updateWidgetShouldReturnErrorWhenNameIsEmpty() throws Exception { - //GIVEN - WidgetRQ widgetRQ = prepareWidget(); - widgetRQ.setName(EMPTY); - - //WHEN - MvcResult mvcResult = mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH + ID_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(widgetRQ)) - .contentType(APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andReturn(); - - //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); - assertEquals(INCORRECT_REQUEST, error.getErrorType()); - assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_IS_BLANK_MESSAGE + " " + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); - } - - @Test - public void updateWidgetShouldReturnErrorWhenNameConsistsOfWhitespaces() throws Exception { - //GIVEN - WidgetRQ widgetRQ = prepareWidget(); - widgetRQ.setName(WHITESPACES_NAME_VALUE); - - //WHEN - MvcResult mvcResult = mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH + ID_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(widgetRQ)) - .contentType(APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andReturn(); - - //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); - assertEquals(INCORRECT_REQUEST, error.getErrorType()); - assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_IS_BLANK_MESSAGE + " " + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); - } - - @Test - public void updateWidgetShouldReturnErrorWhenNameIsLessThanThreeCharacters() throws Exception { - //GIVEN - WidgetRQ widgetRQ = prepareWidget(); - widgetRQ.setName(SHORT_NAME_VALUE); - - //WHEN - MvcResult mvcResult = mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH + ID_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(widgetRQ)) - .contentType(APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andReturn(); - - //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); - assertEquals(INCORRECT_REQUEST, error.getErrorType()); - assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); - } - - @Test - public void updateWidgetShouldReturnErrorWhenNameIsGreaterThanOneHundredAndTwentyEightCharacters() throws Exception { - //GIVEN - WidgetRQ widgetRQ = prepareWidget(); - widgetRQ.setName(LONG_NAME_VALUE); - - //WHEN - MvcResult mvcResult = mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH + ID_PATH) - .with(token(oAuthHelper.getDefaultToken())) - .content(objectMapper.writeValueAsBytes(widgetRQ)) - .contentType(APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andReturn(); - - //THEN - ErrorRS error = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); - assertEquals(INCORRECT_REQUEST, error.getErrorType()); - assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); - } - - private WidgetRQ prepareWidget() { - WidgetRQ widgetRQ = new WidgetRQ(); - widgetRQ.setDescription("description"); - widgetRQ.setWidgetType("oldLineChart"); - ContentParameters contentParameters = new ContentParameters(); - contentParameters.setContentFields(Arrays.asList("number", "name", "user", "statistics$defects$automation_bug$AB002")); - contentParameters.setItemsCount(50); - widgetRQ.setContentParameters(contentParameters); - return widgetRQ; - } + private static final String WIDGET_PATH = "/widget"; + + private static final String FIELD_NAME_SIZE_MESSAGE = + String.format(FIELD_NAME_SIZE_MESSAGE_WITH_FORMAT, 3, 128); + + @Autowired + private ObjectMapper objectMapper; + + @Test + public void createWidgetShouldReturnErrorWhenNameIsNull() throws Exception { + //GIVEN + WidgetRQ widgetRQ = prepareWidget(); + + //WHEN + MvcResult mvcResult = mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH).with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(widgetRQ)).contentType(APPLICATION_JSON)) + .andExpect(status().isBadRequest()).andReturn(); + + //THEN + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); + assertEquals(INCORRECT_REQUEST, error.getErrorType()); + assertEquals(INCORRECT_REQUEST_MESSAGE + FIELD_NAME_IS_NULL_MESSAGE, error.getMessage()); + } + + @Test + public void createWidgetShouldReturnErrorWhenNameIsEmpty() throws Exception { + //GIVEN + WidgetRQ widgetRQ = prepareWidget(); + widgetRQ.setName(EMPTY); + + //WHEN + MvcResult mvcResult = mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH).with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(widgetRQ)).contentType(APPLICATION_JSON)) + .andExpect(status().isBadRequest()).andReturn(); + + //THEN + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); + assertEquals(INCORRECT_REQUEST, error.getErrorType()); + assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_IS_BLANK_MESSAGE + " " + + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); + } + + @Test + public void createWidgetShouldReturnErrorWhenNameConsistsOfWhitespaces() throws Exception { + //GIVEN + WidgetRQ widgetRQ = prepareWidget(); + widgetRQ.setName(WHITESPACES_NAME_VALUE); + + //WHEN + MvcResult mvcResult = mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH).with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(widgetRQ)).contentType(APPLICATION_JSON)) + .andExpect(status().isBadRequest()).andReturn(); + + //THEN + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); + assertEquals(INCORRECT_REQUEST, error.getErrorType()); + assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_IS_BLANK_MESSAGE + " " + + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); + } + + @Test + public void createWidgetShouldReturnErrorWhenNameIsLessThanThreeCharacters() throws Exception { + //GIVEN + WidgetRQ widgetRQ = prepareWidget(); + widgetRQ.setName(SHORT_NAME_VALUE); + + //WHEN + MvcResult mvcResult = mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH).with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(widgetRQ)).contentType(APPLICATION_JSON)) + .andExpect(status().isBadRequest()).andReturn(); + + //THEN + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); + assertEquals(INCORRECT_REQUEST, error.getErrorType()); + assertEquals( + INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); + } + + @Test + public void createWidgetShouldReturnErrorWhenNameIsGreaterThanOneHundredAndTwentyEightCharacters() + throws Exception { + //GIVEN + WidgetRQ widgetRQ = prepareWidget(); + widgetRQ.setName(LONG_NAME_VALUE); + + //WHEN + MvcResult mvcResult = mockMvc.perform( + post(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH).with(token(oAuthHelper.getDefaultToken())) + .content(objectMapper.writeValueAsBytes(widgetRQ)).contentType(APPLICATION_JSON)) + .andExpect(status().isBadRequest()).andReturn(); + + //THEN + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); + assertEquals(INCORRECT_REQUEST, error.getErrorType()); + assertEquals( + INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); + } + + @Test + public void updateWidgetShouldReturnErrorWhenNameIsNull() throws Exception { + //GIVEN + WidgetRQ widgetRQ = prepareWidget(); + + //WHEN + MvcResult mvcResult = mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH + ID_PATH).with( + token(oAuthHelper.getDefaultToken())).content(objectMapper.writeValueAsBytes(widgetRQ)) + .contentType(APPLICATION_JSON)).andExpect(status().isBadRequest()).andReturn(); + + //THEN + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); + assertEquals(INCORRECT_REQUEST, error.getErrorType()); + assertEquals(INCORRECT_REQUEST_MESSAGE + FIELD_NAME_IS_NULL_MESSAGE, error.getMessage()); + } + + @Test + public void updateWidgetShouldReturnErrorWhenNameIsEmpty() throws Exception { + //GIVEN + WidgetRQ widgetRQ = prepareWidget(); + widgetRQ.setName(EMPTY); + + //WHEN + MvcResult mvcResult = mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH + ID_PATH).with( + token(oAuthHelper.getDefaultToken())).content(objectMapper.writeValueAsBytes(widgetRQ)) + .contentType(APPLICATION_JSON)).andExpect(status().isBadRequest()).andReturn(); + + //THEN + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); + assertEquals(INCORRECT_REQUEST, error.getErrorType()); + assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_IS_BLANK_MESSAGE + " " + + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); + } + + @Test + public void updateWidgetShouldReturnErrorWhenNameConsistsOfWhitespaces() throws Exception { + //GIVEN + WidgetRQ widgetRQ = prepareWidget(); + widgetRQ.setName(WHITESPACES_NAME_VALUE); + + //WHEN + MvcResult mvcResult = mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH + ID_PATH).with( + token(oAuthHelper.getDefaultToken())).content(objectMapper.writeValueAsBytes(widgetRQ)) + .contentType(APPLICATION_JSON)).andExpect(status().isBadRequest()).andReturn(); + + //THEN + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); + assertEquals(INCORRECT_REQUEST, error.getErrorType()); + assertEquals(INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_IS_BLANK_MESSAGE + " " + + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); + } + + @Test + public void updateWidgetShouldReturnErrorWhenNameIsLessThanThreeCharacters() throws Exception { + //GIVEN + WidgetRQ widgetRQ = prepareWidget(); + widgetRQ.setName(SHORT_NAME_VALUE); + + //WHEN + MvcResult mvcResult = mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH + ID_PATH).with( + token(oAuthHelper.getDefaultToken())).content(objectMapper.writeValueAsBytes(widgetRQ)) + .contentType(APPLICATION_JSON)).andExpect(status().isBadRequest()).andReturn(); + + //THEN + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); + assertEquals(INCORRECT_REQUEST, error.getErrorType()); + assertEquals( + INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); + } + + @Test + public void updateWidgetShouldReturnErrorWhenNameIsGreaterThanOneHundredAndTwentyEightCharacters() + throws Exception { + //GIVEN + WidgetRQ widgetRQ = prepareWidget(); + widgetRQ.setName(LONG_NAME_VALUE); + + //WHEN + MvcResult mvcResult = mockMvc.perform( + put(DEFAULT_PROJECT_BASE_URL + WIDGET_PATH + ID_PATH).with( + token(oAuthHelper.getDefaultToken())).content(objectMapper.writeValueAsBytes(widgetRQ)) + .contentType(APPLICATION_JSON)).andExpect(status().isBadRequest()).andReturn(); + + //THEN + ErrorRS error = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ErrorRS.class); + assertEquals(INCORRECT_REQUEST, error.getErrorType()); + assertEquals( + INCORRECT_REQUEST_MESSAGE + "[" + FIELD_NAME_SIZE_MESSAGE + "] ", error.getMessage()); + } + + private WidgetRQ prepareWidget() { + WidgetRQ widgetRQ = new WidgetRQ(); + widgetRQ.setDescription("description"); + widgetRQ.setWidgetType("oldLineChart"); + ContentParameters contentParameters = new ContentParameters(); + contentParameters.setContentFields( + Arrays.asList("number", "name", "user", "statistics$defects$automation_bug$AB002")); + contentParameters.setItemsCount(50); + widgetRQ.setContentParameters(contentParameters); + return widgetRQ; + } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/LogResourceAssemblerTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/LogResourceAssemblerTest.java index 8c7b6c7598..a10fe570b8 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/LogResourceAssemblerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/LogResourceAssemblerTest.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.entity.enums.LogLevel; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.log.LogFull; -import com.epam.ta.reportportal.ws.model.log.LogResource; +import com.epam.ta.reportportal.model.log.LogResource; import java.time.LocalDateTime; import java.util.Collections; import java.util.List; diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/DashboardBuilderTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/DashboardBuilderTest.java index 4443a04339..3a6f69e5f4 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/DashboardBuilderTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/DashboardBuilderTest.java @@ -16,72 +16,74 @@ package com.epam.ta.reportportal.ws.converter.builders; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.epam.ta.reportportal.entity.dashboard.Dashboard; import com.epam.ta.reportportal.entity.dashboard.DashboardWidget; import com.epam.ta.reportportal.entity.dashboard.DashboardWidgetId; -import com.epam.ta.reportportal.ws.model.Position; -import com.epam.ta.reportportal.ws.model.Size; -import com.epam.ta.reportportal.ws.model.dashboard.CreateDashboardRQ; -import com.epam.ta.reportportal.ws.model.dashboard.DashboardResource; -import com.epam.ta.reportportal.ws.model.dashboard.UpdateDashboardRQ; -import org.junit.jupiter.api.Test; - +import com.epam.ta.reportportal.model.Position; +import com.epam.ta.reportportal.model.Size; +import com.epam.ta.reportportal.model.dashboard.CreateDashboardRQ; +import com.epam.ta.reportportal.model.dashboard.DashboardResource; +import com.epam.ta.reportportal.model.dashboard.UpdateDashboardRQ; import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * @author Ihar Kahadouski */ class DashboardBuilderTest { - @Test - void createDashboard() { - final String name = "name"; - final String description = "description"; - final boolean share = true; - final String owner = "owner"; - final Long projectId = 1L; + @Test + void createDashboard() { + final String name = "name"; + final String description = "description"; + final boolean share = true; + final String owner = "owner"; + final Long projectId = 1L; - CreateDashboardRQ createDashboardRQ = new CreateDashboardRQ(); - createDashboardRQ.setName(name); - createDashboardRQ.setDescription(description); + CreateDashboardRQ createDashboardRQ = new CreateDashboardRQ(); + createDashboardRQ.setName(name); + createDashboardRQ.setDescription(description); - final Dashboard dashboard = new DashboardBuilder().addDashboardRq(createDashboardRQ).addOwner(owner).addProject(projectId).get(); + final Dashboard dashboard = + new DashboardBuilder().addDashboardRq(createDashboardRQ).addOwner(owner) + .addProject(projectId).get(); - assertEquals(name, dashboard.getName()); - assertEquals(description, dashboard.getDescription()); - assertEquals(owner, dashboard.getOwner()); - assertEquals(projectId, dashboard.getProject().getId()); - } + assertEquals(name, dashboard.getName()); + assertEquals(description, dashboard.getDescription()); + assertEquals(owner, dashboard.getOwner()); + assertEquals(projectId, dashboard.getProject().getId()); + } - @Test - void updateDashboard() { - final String name = "name"; - final String description = "description"; - final boolean share = true; + @Test + void updateDashboard() { + final String name = "name"; + final String description = "description"; + final boolean share = true; - UpdateDashboardRQ updateDashboardRQ = new UpdateDashboardRQ(); - updateDashboardRQ.setName(name); - updateDashboardRQ.setDescription(description); - updateDashboardRQ.setWidgets(Collections.singletonList(new DashboardResource.WidgetObjectModel("kek", 1L, - new Size(10, 20), - new Position(30, 40) - ))); + UpdateDashboardRQ updateDashboardRQ = new UpdateDashboardRQ(); + updateDashboardRQ.setName(name); + updateDashboardRQ.setDescription(description); + updateDashboardRQ.setWidgets(Collections.singletonList( + new DashboardResource.WidgetObjectModel("kek", 1L, new Size(10, 20), + new Position(30, 40) + ))); - DashboardWidget dashboardWidget = new DashboardWidget(); - dashboardWidget.setHeight(5); - dashboardWidget.setWidth(10); - dashboardWidget.setPositionX(1); - dashboardWidget.setPositionY(2); - dashboardWidget.setId(new DashboardWidgetId(1L, 1L)); + DashboardWidget dashboardWidget = new DashboardWidget(); + dashboardWidget.setHeight(5); + dashboardWidget.setWidth(10); + dashboardWidget.setPositionX(1); + dashboardWidget.setPositionY(2); + dashboardWidget.setId(new DashboardWidgetId(1L, 1L)); - final Dashboard existDashboard = new Dashboard(); - existDashboard.addWidget(dashboardWidget); + final Dashboard existDashboard = new Dashboard(); + existDashboard.addWidget(dashboardWidget); - final Dashboard dashboard = new DashboardBuilder(existDashboard).addUpdateRq(updateDashboardRQ).get(); + final Dashboard dashboard = + new DashboardBuilder(existDashboard).addUpdateRq(updateDashboardRQ).get(); - assertEquals(name, dashboard.getName()); - assertEquals(description, dashboard.getDescription()); - } + assertEquals(name, dashboard.getName()); + assertEquals(description, dashboard.getDescription()); + } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/LaunchBuilderTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/LaunchBuilderTest.java index 2c2374bab9..720794498e 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/LaunchBuilderTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/LaunchBuilderTest.java @@ -24,10 +24,10 @@ import com.epam.ta.reportportal.entity.ItemAttribute; import com.epam.ta.reportportal.entity.enums.LaunchModeEnum; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributesRQ; -import com.epam.ta.reportportal.ws.model.launch.Mode; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributesRQ; +import com.epam.ta.reportportal.ws.reporting.Mode; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; import com.google.common.collect.Sets; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; @@ -101,7 +101,7 @@ void overwriteAttributes() { Sets.newHashSet(new ItemAttribute("key", "value", false), systemAttribute)); final Launch buildLaunch = new LaunchBuilder(launch).overwriteAttributes( - Sets.newHashSet(new ItemAttributeResource("newKey", + Sets.newHashSet(new com.epam.ta.reportportal.ws.reporting.ItemAttributeResource("newKey", "newVal" ))).get(); diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/LogFullBuilderTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/LogFullBuilderTest.java index 1451a9bd37..c414480142 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/LogFullBuilderTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/LogFullBuilderTest.java @@ -22,7 +22,7 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.log.LogFull; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/PatternTemplateBuilderTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/PatternTemplateBuilderTest.java index bfb72f7c32..6603b03dff 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/PatternTemplateBuilderTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/PatternTemplateBuilderTest.java @@ -19,7 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.epam.ta.reportportal.entity.pattern.PatternTemplate; -import com.epam.ta.reportportal.ws.model.project.config.pattern.CreatePatternTemplateRQ; +import com.epam.ta.reportportal.model.project.config.pattern.CreatePatternTemplateRQ; import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/TestItemBuilderTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/TestItemBuilderTest.java index bcd8e4de3c..62be4a10b6 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/TestItemBuilderTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/TestItemBuilderTest.java @@ -29,10 +29,10 @@ import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.item.TestItemResults; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.ParameterResource; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributesRQ; +import com.epam.ta.reportportal.ws.reporting.ParameterResource; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributesRQ; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.time.LocalDateTime; diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/UserBuilderTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/UserBuilderTest.java index 7cfb8a0fd3..7f70b36fa8 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/UserBuilderTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/UserBuilderTest.java @@ -23,7 +23,7 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.entity.user.UserType; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQConfirm; +import com.epam.ta.reportportal.model.user.CreateUserRQConfirm; import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/UserFilterBuilderTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/UserFilterBuilderTest.java index 4238492102..e838baf3be 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/UserFilterBuilderTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/UserFilterBuilderTest.java @@ -16,56 +16,57 @@ package com.epam.ta.reportportal.ws.converter.builders; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.epam.ta.reportportal.commons.querygen.FilterCondition; import com.epam.ta.reportportal.entity.filter.FilterSort; import com.epam.ta.reportportal.entity.filter.UserFilter; import com.epam.ta.reportportal.entity.launch.Launch; -import com.epam.ta.reportportal.ws.model.filter.Order; -import com.epam.ta.reportportal.ws.model.filter.UpdateUserFilterRQ; -import com.epam.ta.reportportal.ws.model.filter.UserFilterCondition; +import com.epam.ta.reportportal.model.filter.Order; +import com.epam.ta.reportportal.model.filter.UpdateUserFilterRQ; +import com.epam.ta.reportportal.model.filter.UserFilterCondition; import com.google.common.collect.Sets; +import java.util.Collections; import org.junit.jupiter.api.Test; import org.springframework.data.domain.Sort; -import java.util.Collections; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * @author Ihar Kahadouski */ class UserFilterBuilderTest { - @Test - void userFilterBuilder() { - final UpdateUserFilterRQ request = new UpdateUserFilterRQ(); - final String name = "name"; - request.setName(name); - final String objectType = "Launch"; - request.setObjectType(objectType); - request.setConditions(Sets.newHashSet(new UserFilterCondition("name", "eq", "value"))); - final Order order = new Order(); - order.setIsAsc(false); - order.setSortingColumnName("column"); - request.setOrders(Collections.singletonList(order)); - final String description = "description"; - request.setDescription(description); - final boolean share = true; - final String owner = "owner"; - final Long projectId = 1L; + @Test + void userFilterBuilder() { + final UpdateUserFilterRQ request = new UpdateUserFilterRQ(); + final String name = "name"; + request.setName(name); + final String objectType = "Launch"; + request.setObjectType(objectType); + request.setConditions(Sets.newHashSet(new UserFilterCondition("name", "eq", "value"))); + final Order order = new Order(); + order.setIsAsc(false); + order.setSortingColumnName("column"); + request.setOrders(Collections.singletonList(order)); + final String description = "description"; + request.setDescription(description); + final boolean share = true; + final String owner = "owner"; + final Long projectId = 1L; - final UserFilter userFilter = new UserFilterBuilder().addFilterRq(request).addOwner(owner).addProject(projectId).get(); + final UserFilter userFilter = + new UserFilterBuilder().addFilterRq(request).addOwner(owner).addProject(projectId).get(); - assertEquals(name, userFilter.getName()); - assertEquals(description, userFilter.getDescription()); - assertEquals(owner, userFilter.getOwner()); - assertEquals(projectId, userFilter.getProject().getId()); - assertEquals(Launch.class, userFilter.getTargetClass().getClassObject()); - assertThat(userFilter.getFilterCondition()).containsExactlyInAnyOrder(FilterCondition.builder().eq("name", "value").build()); - final FilterSort filterSort = new FilterSort(); - filterSort.setDirection(Sort.Direction.DESC); - filterSort.setField("column"); - assertThat(userFilter.getFilterSorts()).containsExactlyInAnyOrder(filterSort); - } + assertEquals(name, userFilter.getName()); + assertEquals(description, userFilter.getDescription()); + assertEquals(owner, userFilter.getOwner()); + assertEquals(projectId, userFilter.getProject().getId()); + assertEquals(Launch.class, userFilter.getTargetClass().getClassObject()); + assertThat(userFilter.getFilterCondition()).containsExactlyInAnyOrder( + FilterCondition.builder().eq("name", "value").build()); + final FilterSort filterSort = new FilterSort(); + filterSort.setDirection(Sort.Direction.DESC); + filterSort.setField("column"); + assertThat(userFilter.getFilterSorts()).containsExactlyInAnyOrder(filterSort); + } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/WidgetBuilderTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/WidgetBuilderTest.java index 4b5a540c3a..347a0bb953 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/builders/WidgetBuilderTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/builders/WidgetBuilderTest.java @@ -16,74 +16,77 @@ package com.epam.ta.reportportal.ws.converter.builders; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.epam.ta.reportportal.entity.filter.UserFilter; import com.epam.ta.reportportal.entity.widget.Widget; -import com.epam.ta.reportportal.ws.model.widget.ContentParameters; -import com.epam.ta.reportportal.ws.model.widget.WidgetPreviewRQ; -import com.epam.ta.reportportal.ws.model.widget.WidgetRQ; -import org.junit.jupiter.api.Test; - +import com.epam.ta.reportportal.model.widget.ContentParameters; +import com.epam.ta.reportportal.model.widget.WidgetPreviewRQ; +import com.epam.ta.reportportal.model.widget.WidgetRQ; import java.util.AbstractMap; import java.util.Collections; import java.util.HashMap; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * @author Ihar Kahadouski */ class WidgetBuilderTest { - @Test - void widgetBuilderTest() { - final WidgetRQ widgetRQ = new WidgetRQ(); - final String name = "name"; - widgetRQ.setName(name); - final String description = "description"; - widgetRQ.setDescription(description); - final boolean share = true; - final String widgetType = "oldLineChart"; - widgetRQ.setWidgetType(widgetType); - final ContentParameters contentParameters = new ContentParameters(); - contentParameters.setContentFields(Collections.singletonList("contentField")); - contentParameters.setItemsCount(10); - final HashMap widgetOptions = new HashMap<>(); - widgetOptions.put("param", "val"); - contentParameters.setWidgetOptions(widgetOptions); - widgetRQ.setContentParameters(contentParameters); - final String owner = "owner"; - final UserFilter userFilter = new UserFilter(); - userFilter.setId(1L); + @Test + void widgetBuilderTest() { + final WidgetRQ widgetRQ = new WidgetRQ(); + final String name = "name"; + widgetRQ.setName(name); + final String description = "description"; + widgetRQ.setDescription(description); + final boolean share = true; + final String widgetType = "oldLineChart"; + widgetRQ.setWidgetType(widgetType); + final ContentParameters contentParameters = new ContentParameters(); + contentParameters.setContentFields(Collections.singletonList("contentField")); + contentParameters.setItemsCount(10); + final HashMap widgetOptions = new HashMap<>(); + widgetOptions.put("param", "val"); + contentParameters.setWidgetOptions(widgetOptions); + widgetRQ.setContentParameters(contentParameters); + final String owner = "owner"; + final UserFilter userFilter = new UserFilter(); + userFilter.setId(1L); - final Widget widget = new WidgetBuilder().addWidgetRq(widgetRQ).addFilters(Collections.singletonList(userFilter)).addOwner(owner).get(); + final Widget widget = + new WidgetBuilder().addWidgetRq(widgetRQ).addFilters(Collections.singletonList(userFilter)) + .addOwner(owner).get(); - assertEquals(name, widget.getName()); - assertEquals(description, widget.getDescription()); - assertEquals(owner, widget.getOwner()); - assertEquals(widgetType, widget.getWidgetType()); - assertThat(widget.getFilters()).containsExactly(userFilter); - assertThat(widget.getContentFields()).containsExactly("contentField"); - assertThat(widget.getWidgetOptions().getOptions()).containsExactly(new AbstractMap.SimpleEntry<>("param", "val")); - } + assertEquals(name, widget.getName()); + assertEquals(description, widget.getDescription()); + assertEquals(owner, widget.getOwner()); + assertEquals(widgetType, widget.getWidgetType()); + assertThat(widget.getFilters()).containsExactly(userFilter); + assertThat(widget.getContentFields()).containsExactly("contentField"); + assertThat(widget.getWidgetOptions().getOptions()).containsExactly( + new AbstractMap.SimpleEntry<>("param", "val")); + } - @Test - void addWidgetPreviewRqTest() { - final WidgetPreviewRQ previewRQ = new WidgetPreviewRQ(); - final ContentParameters contentParameters = new ContentParameters(); - contentParameters.setContentFields(Collections.singletonList("contentField")); - contentParameters.setItemsCount(10); - final HashMap widgetOptions = new HashMap<>(); - widgetOptions.put("param", "val"); - contentParameters.setWidgetOptions(widgetOptions); - previewRQ.setContentParameters(contentParameters); - final String widgetType = "oldLineChart"; - previewRQ.setWidgetType(widgetType); + @Test + void addWidgetPreviewRqTest() { + final WidgetPreviewRQ previewRQ = new WidgetPreviewRQ(); + final ContentParameters contentParameters = new ContentParameters(); + contentParameters.setContentFields(Collections.singletonList("contentField")); + contentParameters.setItemsCount(10); + final HashMap widgetOptions = new HashMap<>(); + widgetOptions.put("param", "val"); + contentParameters.setWidgetOptions(widgetOptions); + previewRQ.setContentParameters(contentParameters); + final String widgetType = "oldLineChart"; + previewRQ.setWidgetType(widgetType); - final Widget widget = new WidgetBuilder(new Widget()).addWidgetPreviewRq(previewRQ).get(); + final Widget widget = new WidgetBuilder(new Widget()).addWidgetPreviewRq(previewRQ).get(); - assertEquals(widgetType, widget.getWidgetType()); - assertThat(widget.getContentFields()).containsExactly("contentField"); - assertThat(widget.getWidgetOptions().getOptions()).containsExactly(new AbstractMap.SimpleEntry<>("param", "val")); - } + assertEquals(widgetType, widget.getWidgetType()); + assertThat(widget.getContentFields()).containsExactly("contentField"); + assertThat(widget.getWidgetOptions().getOptions()).containsExactly( + new AbstractMap.SimpleEntry<>("param", "val")); + } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/DashboardConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/DashboardConverterTest.java index f013410764..34b38f36d0 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/DashboardConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/DashboardConverterTest.java @@ -16,79 +16,80 @@ package com.epam.ta.reportportal.ws.converter.converters; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + import com.epam.ta.reportportal.entity.dashboard.Dashboard; import com.epam.ta.reportportal.entity.dashboard.DashboardWidget; import com.epam.ta.reportportal.entity.dashboard.DashboardWidgetId; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.widget.Widget; -import com.epam.ta.reportportal.ws.model.activity.DashboardActivityResource; -import com.epam.ta.reportportal.ws.model.dashboard.DashboardResource; -import org.junit.jupiter.api.Test; - +import com.epam.ta.reportportal.model.activity.DashboardActivityResource; +import com.epam.ta.reportportal.model.dashboard.DashboardResource; import java.time.LocalDateTime; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; /** * @author Ihar Kahadouski */ class DashboardConverterTest { - @Test - void toResourceNullTest() { - assertThrows(NullPointerException.class, () -> DashboardConverter.TO_RESOURCE.apply(null)); - } + @Test + void toResourceNullTest() { + assertThrows(NullPointerException.class, () -> DashboardConverter.TO_RESOURCE.apply(null)); + } - @Test - void toActivityResourceNullTest() { - assertThrows(NullPointerException.class, () -> DashboardConverter.TO_ACTIVITY_RESOURCE.apply(null)); - } + @Test + void toActivityResourceNullTest() { + assertThrows( + NullPointerException.class, () -> DashboardConverter.TO_ACTIVITY_RESOURCE.apply(null)); + } - @Test - void toActivityResource() { - final Dashboard dashboard = getDashboard(); - final DashboardActivityResource activityResource = DashboardConverter.TO_ACTIVITY_RESOURCE.apply(dashboard); + @Test + void toActivityResource() { + final Dashboard dashboard = getDashboard(); + final DashboardActivityResource activityResource = + DashboardConverter.TO_ACTIVITY_RESOURCE.apply(dashboard); - assertEquals(activityResource.getId(), dashboard.getId()); - assertEquals(activityResource.getName(), dashboard.getName()); - assertEquals(activityResource.getDescription(), dashboard.getDescription()); - assertEquals(activityResource.getProjectId(), dashboard.getProject().getId()); - } + assertEquals(activityResource.getId(), dashboard.getId()); + assertEquals(activityResource.getName(), dashboard.getName()); + assertEquals(activityResource.getDescription(), dashboard.getDescription()); + assertEquals(activityResource.getProjectId(), dashboard.getProject().getId()); + } - @Test - void toResource() { - final Dashboard dashboard = getDashboard(); - final DashboardResource resource = DashboardConverter.TO_RESOURCE.apply(dashboard); + @Test + void toResource() { + final Dashboard dashboard = getDashboard(); + final DashboardResource resource = DashboardConverter.TO_RESOURCE.apply(dashboard); - assertEquals(resource.getDashboardId(), dashboard.getId()); - assertEquals(resource.getName(), dashboard.getName()); - assertEquals(resource.getDescription(), dashboard.getDescription()); - assertEquals(resource.getOwner(), dashboard.getOwner()); - assertEquals(resource.getWidgets().size(), dashboard.getDashboardWidgets().size()); - } + assertEquals(resource.getDashboardId(), dashboard.getId()); + assertEquals(resource.getName(), dashboard.getName()); + assertEquals(resource.getDescription(), dashboard.getDescription()); + assertEquals(resource.getOwner(), dashboard.getOwner()); + assertEquals(resource.getWidgets().size(), dashboard.getDashboardWidgets().size()); + } - private static Dashboard getDashboard() { - Dashboard dashboard = new Dashboard(); - dashboard.setId(1L); - dashboard.setName("name"); - dashboard.setDescription("description"); - dashboard.setCreationDate(LocalDateTime.now()); - dashboard.setOwner("owner"); - final Project project = new Project(); - project.setId(2L); - dashboard.setProject(project); - final DashboardWidget dashboardWidget = new DashboardWidget(); - dashboardWidget.setId(new DashboardWidgetId(1L, 3L)); - dashboardWidget.setPositionY(2); - dashboardWidget.setPositionX(3); - dashboardWidget.setWidth(5); - dashboardWidget.setHeight(6); - dashboardWidget.setWidgetName("widgetName"); - dashboardWidget.setDashboard(dashboard); - final Widget widget = new Widget(); - dashboardWidget.setWidget(widget); - dashboard.addWidget(dashboardWidget); - return dashboard; - } + private static Dashboard getDashboard() { + Dashboard dashboard = new Dashboard(); + dashboard.setId(1L); + dashboard.setName("name"); + dashboard.setDescription("description"); + dashboard.setCreationDate(LocalDateTime.now()); + dashboard.setOwner("owner"); + final Project project = new Project(); + project.setId(2L); + dashboard.setProject(project); + final DashboardWidget dashboardWidget = new DashboardWidget(); + dashboardWidget.setId(new DashboardWidgetId(1L, 3L)); + dashboardWidget.setPositionY(2); + dashboardWidget.setPositionX(3); + dashboardWidget.setWidth(5); + dashboardWidget.setHeight(6); + dashboardWidget.setWidgetName("widgetName"); + dashboardWidget.setDashboard(dashboard); + final Widget widget = new Widget(); + dashboardWidget.setWidget(widget); + dashboard.addWidget(dashboardWidget); + return dashboard; + } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/IntegrationConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/IntegrationConverterTest.java index 114abaebb4..3244b13f58 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/IntegrationConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/IntegrationConverterTest.java @@ -25,9 +25,9 @@ import com.epam.ta.reportportal.entity.integration.IntegrationParams; import com.epam.ta.reportportal.entity.integration.IntegrationType; import com.epam.ta.reportportal.entity.project.Project; -import com.epam.ta.reportportal.ws.model.activity.IntegrationActivityResource; -import com.epam.ta.reportportal.ws.model.integration.IntegrationResource; -import com.epam.ta.reportportal.ws.model.integration.IntegrationTypeResource; +import com.epam.ta.reportportal.model.activity.IntegrationActivityResource; +import com.epam.ta.reportportal.model.integration.IntegrationResource; +import com.epam.ta.reportportal.model.integration.IntegrationTypeResource; import com.google.common.collect.Sets; import java.sql.Date; import java.time.LocalDateTime; @@ -43,35 +43,39 @@ class IntegrationConverterTest { @Test void toResource() { final Integration integration = getIntegration(); - final IntegrationResource resource = IntegrationConverter.TO_INTEGRATION_RESOURCE.apply( - integration); + final IntegrationResource resource = + IntegrationConverter.TO_INTEGRATION_RESOURCE.apply(integration); assertEquals(resource.getCreationDate(), - Date.from(integration.getCreationDate().atZone(ZoneId.of("UTC")).toInstant())); + Date.from(integration.getCreationDate().atZone(ZoneId.of("UTC")).toInstant()) + ); assertEquals(resource.getEnabled(), integration.isEnabled()); assertEquals(resource.getId(), integration.getId()); assertEquals(resource.getProjectId(), integration.getProject().getId()); assertThat(resource.getIntegrationParams()).containsOnlyKeys("param1", "param2", "nullParam", - null); + null + ); assertThat(resource.getIntegrationParams()).doesNotContainKey("accessToken"); assertThat(resource.getIntegrationParams()).containsValues("qwerty", "asdfgh", "value", null); final IntegrationTypeResource integrationTypeResource = resource.getIntegrationType(); assertEquals(integrationTypeResource.getAuthFlow().name(), - integration.getType().getAuthFlow().name()); + integration.getType().getAuthFlow().name() + ); assertEquals(integrationTypeResource.getId(), integration.getType().getId()); assertEquals(integrationTypeResource.getName(), integration.getType().getName()); assertEquals(integrationTypeResource.getGroupType(), - integration.getType().getIntegrationGroup().name()); + integration.getType().getIntegrationGroup().name() + ); } @Test void toActivityResource() { final Integration integration = getIntegration(); - final IntegrationActivityResource resource = IntegrationConverter.TO_ACTIVITY_RESOURCE.apply( - integration); + final IntegrationActivityResource resource = + IntegrationConverter.TO_ACTIVITY_RESOURCE.apply(integration); assertEquals(resource.getId(), integration.getId()); assertEquals(resource.getProjectId(), integration.getProject().getId()); diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/IssueConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/IssueConverterTest.java index eb5e34dab8..1f3735ea22 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/IssueConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/IssueConverterTest.java @@ -22,7 +22,7 @@ import com.epam.ta.reportportal.entity.item.issue.IssueEntity; import com.epam.ta.reportportal.entity.item.issue.IssueGroup; import com.epam.ta.reportportal.entity.item.issue.IssueType; -import com.epam.ta.reportportal.ws.model.issue.Issue; +import com.epam.ta.reportportal.ws.reporting.Issue; import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/ItemAttributeConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/ItemAttributeConverterTest.java index acf039c71f..acb258c0ab 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/ItemAttributeConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/ItemAttributeConverterTest.java @@ -19,7 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.epam.ta.reportportal.entity.ItemAttribute; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/LogConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/LogConverterTest.java index 33d700039e..f808ce0abd 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/LogConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/LogConverterTest.java @@ -22,7 +22,7 @@ import com.epam.ta.reportportal.entity.enums.LogLevel; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.log.LogFull; -import com.epam.ta.reportportal.ws.model.log.LogResource; +import com.epam.ta.reportportal.model.log.LogResource; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; @@ -62,8 +62,10 @@ void toResource() { assertEquals(resource.getUuid(), logFull.getUuid()); assertEquals(resource.getMessage(), logFull.getLogMessage()); assertEquals(resource.getLevel(), LogLevel.toLevel(logFull.getLogLevel()).toString()); - assertEquals(resource.getLogTime(), - Date.from(logFull.getLogTime().atZone(ZoneId.of("UTC")).toInstant())); + assertEquals( + resource.getLogTime(), + Date.from(logFull.getLogTime().atZone(ZoneId.of("UTC")).toInstant()) + ); assertEquals(resource.getItemId(), logFull.getTestItem().getItemId()); final LogResource.BinaryContent binaryContent = resource.getBinaryContent(); diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/NotificationConfigConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/NotificationConfigConverterTest.java index b8aa512b05..5d889ccf8f 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/NotificationConfigConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/NotificationConfigConverterTest.java @@ -16,110 +16,107 @@ package com.epam.ta.reportportal.ws.converter.converters; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + import com.epam.ta.reportportal.entity.enums.LogicalOperator; import com.epam.ta.reportportal.entity.enums.SendCase; import com.epam.ta.reportportal.entity.project.email.LaunchAttributeRule; import com.epam.ta.reportportal.entity.project.email.SenderCase; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.model.project.email.SenderCaseDTO; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; import com.google.common.collect.Sets; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; /** * @author Ihar Kahadouski */ class NotificationConfigConverterTest { - @Test - void toCaseModelNullTest() { - assertThrows(NullPointerException.class, () -> NotificationConfigConverter.TO_CASE_MODEL.apply(null)); - } - - @Test - void toResource() { - final Set senderCases = getSenderCases(); - List resources = NotificationConfigConverter.TO_RESOURCE.apply(senderCases); - - assertEquals(resources.size(), senderCases.size()); - } - - @Test - void toCaseResource() { - final SenderCase senderCase = getCase(); - final SenderCaseDTO senderCaseDTO = NotificationConfigConverter.TO_CASE_RESOURCE.apply(senderCase); - - assertThat(senderCaseDTO.getRecipients()).containsExactlyInAnyOrderElementsOf(senderCase.getRecipients()); - // assertThat(senderCaseDTO.getAttributes()).containsExactlyInAnyOrderElementsOf(senderCase.getLaunchAttributeRules()); - assertThat(senderCaseDTO.getLaunchNames()).containsExactlyInAnyOrderElementsOf(senderCase.getLaunchNames()); - assertEquals(senderCaseDTO.getSendCase(), senderCase.getSendCase().getCaseString()); - } - - @Test - void toCaseModel() { - final SenderCaseDTO caseDTO = getCaseDTO(); - final SenderCase senderCase = NotificationConfigConverter.TO_CASE_MODEL.apply(caseDTO); - - assertThat(senderCase.getRecipients()).containsExactlyInAnyOrderElementsOf(caseDTO.getRecipients()); - assertThat(senderCase.getLaunchNames()).containsExactlyInAnyOrderElementsOf(caseDTO.getLaunchNames()); - // assertThat(senderCase.getLaunchAttributes()).containsExactlyInAnyOrderElementsOf(caseDTO.getAttributes()); - assertEquals(senderCase.getSendCase().getCaseString(), caseDTO.getSendCase()); - assertEquals(senderCase.isEnabled(), caseDTO.isEnabled()); - } - - private static Set getSenderCases() { - Set senderCases = new HashSet<>(); - senderCases.add(getCase()); - final LaunchAttributeRule launchAttributeRule = new LaunchAttributeRule(); - launchAttributeRule.setId(1L); - launchAttributeRule.setKey("key"); - launchAttributeRule.setValue("value"); - senderCases.add(new SenderCase( - Sets.newHashSet("recipent3", "recipient8"), - Sets.newHashSet("launch1", "launch5", "launch10"), - Sets.newHashSet(launchAttributeRule), - SendCase.ALWAYS, - true, - LogicalOperator.AND - )); - return senderCases; - } - - private static SenderCase getCase() { - final LaunchAttributeRule launchAttributeRule = new LaunchAttributeRule(); - launchAttributeRule.setId(2L); - launchAttributeRule.setKey("key1"); - launchAttributeRule.setValue("value1"); - return new SenderCase( - Sets.newHashSet("recipent1", "recipient2"), - Sets.newHashSet("launch1", "launch2", "launch3"), - Sets.newHashSet(launchAttributeRule), - SendCase.MORE_10, - true, - LogicalOperator.AND - ); - } - - private static SenderCaseDTO getCaseDTO() { - SenderCaseDTO senderCaseDTO = new SenderCaseDTO(); - senderCaseDTO.setRecipients(Arrays.asList("recipient1", "recipient2")); - senderCaseDTO.setLaunchNames(Arrays.asList("launch1", "launch2")); - final ItemAttributeResource launchAttribute = new ItemAttributeResource(); - launchAttribute.setKey("key"); - launchAttribute.setValue("val"); - senderCaseDTO.setAttributes(Sets.newHashSet(launchAttribute)); - senderCaseDTO.setSendCase("always"); - senderCaseDTO.setEnabled(true); - senderCaseDTO.setAttributesOperator(LogicalOperator.AND.getOperator()); - return senderCaseDTO; - } + @Test + void toCaseModelNullTest() { + assertThrows( + NullPointerException.class, () -> NotificationConfigConverter.TO_CASE_MODEL.apply(null)); + } + + @Test + void toResource() { + final Set senderCases = getSenderCases(); + List resources = NotificationConfigConverter.TO_RESOURCE.apply(senderCases); + + assertEquals(resources.size(), senderCases.size()); + } + + @Test + void toCaseResource() { + final SenderCase senderCase = getCase(); + final SenderCaseDTO senderCaseDTO = + NotificationConfigConverter.TO_CASE_RESOURCE.apply(senderCase); + + assertThat(senderCaseDTO.getRecipients()).containsExactlyInAnyOrderElementsOf( + senderCase.getRecipients()); + // assertThat(senderCaseDTO.getAttributes()).containsExactlyInAnyOrderElementsOf(senderCase.getLaunchAttributeRules()); + assertThat(senderCaseDTO.getLaunchNames()).containsExactlyInAnyOrderElementsOf( + senderCase.getLaunchNames()); + assertEquals(senderCaseDTO.getSendCase(), senderCase.getSendCase().getCaseString()); + } + + @Test + void toCaseModel() { + final SenderCaseDTO caseDTO = getCaseDTO(); + final SenderCase senderCase = NotificationConfigConverter.TO_CASE_MODEL.apply(caseDTO); + + assertThat(senderCase.getRecipients()).containsExactlyInAnyOrderElementsOf( + caseDTO.getRecipients()); + assertThat(senderCase.getLaunchNames()).containsExactlyInAnyOrderElementsOf( + caseDTO.getLaunchNames()); + // assertThat(senderCase.getLaunchAttributes()).containsExactlyInAnyOrderElementsOf(caseDTO.getAttributes()); + assertEquals(senderCase.getSendCase().getCaseString(), caseDTO.getSendCase()); + assertEquals(senderCase.isEnabled(), caseDTO.isEnabled()); + } + + private static Set getSenderCases() { + Set senderCases = new HashSet<>(); + senderCases.add(getCase()); + final LaunchAttributeRule launchAttributeRule = new LaunchAttributeRule(); + launchAttributeRule.setId(1L); + launchAttributeRule.setKey("key"); + launchAttributeRule.setValue("value"); + senderCases.add(new SenderCase(Sets.newHashSet("recipent3", "recipient8"), + Sets.newHashSet("launch1", "launch5", "launch10"), Sets.newHashSet(launchAttributeRule), + SendCase.ALWAYS, true, LogicalOperator.AND + )); + return senderCases; + } + + private static SenderCase getCase() { + final LaunchAttributeRule launchAttributeRule = new LaunchAttributeRule(); + launchAttributeRule.setId(2L); + launchAttributeRule.setKey("key1"); + launchAttributeRule.setValue("value1"); + return new SenderCase(Sets.newHashSet("recipent1", "recipient2"), + Sets.newHashSet("launch1", "launch2", "launch3"), Sets.newHashSet(launchAttributeRule), + SendCase.MORE_10, true, LogicalOperator.AND + ); + } + + private static SenderCaseDTO getCaseDTO() { + SenderCaseDTO senderCaseDTO = new SenderCaseDTO(); + senderCaseDTO.setRecipients(Arrays.asList("recipient1", "recipient2")); + senderCaseDTO.setLaunchNames(Arrays.asList("launch1", "launch2")); + final ItemAttributeResource launchAttribute = new ItemAttributeResource(); + launchAttribute.setKey("key"); + launchAttribute.setValue("val"); + senderCaseDTO.setAttributes(Sets.newHashSet(launchAttribute)); + senderCaseDTO.setSendCase("always"); + senderCaseDTO.setEnabled(true); + senderCaseDTO.setAttributesOperator(LogicalOperator.AND.getOperator()); + return senderCaseDTO; + } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/ParametersConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/ParametersConverterTest.java index a71e99c26a..a038d0bfc8 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/ParametersConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/ParametersConverterTest.java @@ -19,7 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.epam.ta.reportportal.entity.item.Parameter; -import com.epam.ta.reportportal.ws.model.ParameterResource; +import com.epam.ta.reportportal.ws.reporting.ParameterResource; import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/PatternTemplateConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/PatternTemplateConverterTest.java index f97b2dbb7e..1cd49588c5 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/PatternTemplateConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/PatternTemplateConverterTest.java @@ -20,8 +20,8 @@ import com.epam.ta.reportportal.entity.pattern.PatternTemplate; import com.epam.ta.reportportal.entity.pattern.PatternTemplateType; -import com.epam.ta.reportportal.ws.model.activity.PatternTemplateActivityResource; -import com.epam.ta.reportportal.ws.model.project.config.pattern.PatternTemplateResource; +import com.epam.ta.reportportal.model.activity.PatternTemplateActivityResource; +import com.epam.ta.reportportal.model.project.config.pattern.PatternTemplateResource; import org.junit.jupiter.api.Test; /** @@ -48,8 +48,8 @@ public void toActivityResourceTest() { PatternTemplate patternTemplate = get(); - PatternTemplateActivityResource resource = PatternTemplateConverter.TO_ACTIVITY_RESOURCE.apply( - patternTemplate); + PatternTemplateActivityResource resource = + PatternTemplateConverter.TO_ACTIVITY_RESOURCE.apply(patternTemplate); assertEquals(patternTemplate.getId(), resource.getId()); assertEquals(patternTemplate.getProjectId(), resource.getProjectId()); diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/ProjectActivityConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/ProjectActivityConverterTest.java index 05a4dfb394..b327307386 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/ProjectActivityConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/ProjectActivityConverterTest.java @@ -22,7 +22,7 @@ import com.epam.ta.reportportal.entity.attribute.Attribute; import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.project.ProjectAttribute; -import com.epam.ta.reportportal.ws.model.activity.ProjectAttributesActivityResource; +import com.epam.ta.reportportal.model.activity.ProjectAttributesActivityResource; import com.google.common.collect.Sets; import org.junit.jupiter.api.Test; @@ -34,8 +34,8 @@ class ProjectActivityConverterTest { @Test void toActivityResource() { final Project project = getProject(); - final ProjectAttributesActivityResource resource = ProjectActivityConverter.TO_ACTIVITY_RESOURCE.apply( - project); + final ProjectAttributesActivityResource resource = + ProjectActivityConverter.TO_ACTIVITY_RESOURCE.apply(project); assertEquals(resource.getProjectId(), project.getId()); assertEquals(resource.getProjectName(), project.getName()); @@ -51,8 +51,8 @@ private static Project getProject() { final Attribute attribute = new Attribute(); attribute.setId(2L); attribute.setName("attr.lol"); - final ProjectAttribute projectAttribute = new ProjectAttribute().withProject(project) - .withValue("value").withAttribute(attribute); + final ProjectAttribute projectAttribute = + new ProjectAttribute().withProject(project).withValue("value").withAttribute(attribute); project.setProjectAttributes(Sets.newHashSet(projectAttribute)); return project; } diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/RestorePasswordBidConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/RestorePasswordBidConverterTest.java index 6d4bdd0f36..be482e52aa 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/RestorePasswordBidConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/RestorePasswordBidConverterTest.java @@ -20,7 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import com.epam.ta.reportportal.entity.user.RestorePasswordBid; -import com.epam.ta.reportportal.ws.model.user.RestorePasswordRQ; +import com.epam.ta.reportportal.model.user.RestorePasswordRQ; import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/TestItemConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/TestItemConverterTest.java index 3d1a8139c6..7366429323 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/TestItemConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/TestItemConverterTest.java @@ -35,8 +35,8 @@ import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.entity.statistics.Statistics; import com.epam.ta.reportportal.entity.statistics.StatisticsField; -import com.epam.ta.reportportal.ws.model.TestItemResource; -import com.epam.ta.reportportal.ws.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.model.activity.TestItemActivityResource; +import com.epam.ta.reportportal.ws.reporting.TestItemResource; import com.google.common.collect.Sets; import java.time.LocalDateTime; import java.time.ZoneId; @@ -52,7 +52,8 @@ class TestItemConverterTest { @Test void toActivityResourceNullTest() { assertThrows(NullPointerException.class, - () -> TestItemConverter.TO_ACTIVITY_RESOURCE.apply(null, null)); + () -> TestItemConverter.TO_ACTIVITY_RESOURCE.apply(null, null) + ); } @Test @@ -63,30 +64,30 @@ void toResourceNullTest() { @Test void toActivityResource() { final TestItem item = getItem(true); - final TestItemActivityResource activityResource = TestItemConverter.TO_ACTIVITY_RESOURCE.apply( - item, 4L); + final TestItemActivityResource activityResource = + TestItemConverter.TO_ACTIVITY_RESOURCE.apply(item, 4L); assertEquals(activityResource.getId(), item.getItemId()); assertEquals(activityResource.getName(), item.getName()); assertEquals((long) activityResource.getProjectId(), 4L); assertEquals(activityResource.getIssueDescription(), - item.getItemResults().getIssue().getIssueDescription()); + item.getItemResults().getIssue().getIssueDescription() + ); assertEquals(activityResource.getIssueTypeLongName(), - item.getItemResults().getIssue().getIssueType().getLongName()); + item.getItemResults().getIssue().getIssueType().getLongName() + ); assertEquals(activityResource.getStatus(), item.getItemResults().getStatus().name()); - assertEquals( - activityResource.getTickets(), - item.getItemResults() - .getIssue() - .getTickets() - .stream() + assertEquals(activityResource.getTickets(), + item.getItemResults().getIssue().getTickets().stream() .map(it -> it.getTicketId().concat(":").concat(it.getUrl())) .collect(Collectors.joining(", ")) ); assertEquals(activityResource.isIgnoreAnalyzer(), - item.getItemResults().getIssue().getIgnoreAnalyzer()); + item.getItemResults().getIssue().getIgnoreAnalyzer() + ); assertEquals(activityResource.isAutoAnalyzed(), - item.getItemResults().getIssue().getAutoAnalyzed()); + item.getItemResults().getIssue().getAutoAnalyzed() + ); } @Test @@ -104,29 +105,30 @@ void toResource() { assertEquals(resource.getStatus(), item.getItemResults().getStatus().name()); assertEquals(resource.getType(), item.getType().name()); assertEquals(resource.getStartTime(), - Date.from(item.getStartTime().atZone(ZoneId.of("UTC")).toInstant())); + Date.from(item.getStartTime().atZone(ZoneId.of("UTC")).toInstant()) + ); assertEquals(resource.getEndTime(), - Date.from(item.getItemResults().getEndTime().atZone(ZoneId.of("UTC")).toInstant())); + Date.from(item.getItemResults().getEndTime().atZone(ZoneId.of("UTC")).toInstant()) + ); assertEquals(resource.getUniqueId(), item.getUniqueId()); - assertThat(resource.getAttributes() - .stream() - .map(ItemAttributeConverter.FROM_RESOURCE) + assertThat(resource.getAttributes().stream().map(ItemAttributeConverter.FROM_RESOURCE) .collect(Collectors.toSet())).containsExactlyElementsOf(item.getAttributes()); - assertThat(resource.getParameters() - .stream() - .map(ParametersConverter.TO_MODEL) + assertThat(resource.getParameters().stream().map(ParametersConverter.TO_MODEL) .collect(Collectors.toSet())).containsExactlyElementsOf(item.getParameters()); assertThat(resource.getStatisticsResource()).isEqualToComparingFieldByField( - StatisticsConverter.TO_RESOURCE.apply(item.getItemResults() - .getStatistics())); + StatisticsConverter.TO_RESOURCE.apply(item.getItemResults().getStatistics())); assertEquals(resource.getIssue().getComment(), - item.getItemResults().getIssue().getIssueDescription()); + item.getItemResults().getIssue().getIssueDescription() + ); assertEquals(resource.getIssue().getAutoAnalyzed(), - item.getItemResults().getIssue().getAutoAnalyzed()); + item.getItemResults().getIssue().getAutoAnalyzed() + ); assertEquals(resource.getIssue().getIssueType(), - item.getItemResults().getIssue().getIssueType().getLocator()); + item.getItemResults().getIssue().getIssueType().getLocator() + ); assertEquals(resource.getIssue().getIgnoreAnalyzer(), - item.getItemResults().getIssue().getIgnoreAnalyzer()); + item.getItemResults().getIssue().getIgnoreAnalyzer() + ); } @Test @@ -144,21 +146,18 @@ void toResourceWithoutIssue() { assertEquals(resource.getStatus(), item.getItemResults().getStatus().name()); assertEquals(resource.getType(), item.getType().name()); assertEquals(resource.getStartTime(), - Date.from(item.getStartTime().atZone(ZoneId.of("UTC")).toInstant())); + Date.from(item.getStartTime().atZone(ZoneId.of("UTC")).toInstant()) + ); assertEquals(resource.getEndTime(), - Date.from(item.getItemResults().getEndTime().atZone(ZoneId.of("UTC")).toInstant())); + Date.from(item.getItemResults().getEndTime().atZone(ZoneId.of("UTC")).toInstant()) + ); assertEquals(resource.getUniqueId(), item.getUniqueId()); - assertThat(resource.getAttributes() - .stream() - .map(ItemAttributeConverter.FROM_RESOURCE) + assertThat(resource.getAttributes().stream().map(ItemAttributeConverter.FROM_RESOURCE) .collect(Collectors.toSet())).containsExactlyElementsOf(item.getAttributes()); - assertThat(resource.getParameters() - .stream() - .map(ParametersConverter.TO_MODEL) + assertThat(resource.getParameters().stream().map(ParametersConverter.TO_MODEL) .collect(Collectors.toSet())).containsExactlyElementsOf(item.getParameters()); assertThat(resource.getStatisticsResource()).isEqualToComparingFieldByField( - StatisticsConverter.TO_RESOURCE.apply(item.getItemResults() - .getStatistics())); + StatisticsConverter.TO_RESOURCE.apply(item.getItemResults().getStatistics())); assertNull(resource.getIssue()); } @@ -177,7 +176,8 @@ private TestItem getItem(boolean hasIssue) { parameter.setValue("value"); item.setParameters(Sets.newHashSet(parameter)); item.setAttributes(Sets.newHashSet(new ItemAttribute("key1", "value1", false), - new ItemAttribute("key2", "value2", false))); + new ItemAttribute("key2", "value2", false) + )); final Launch launch = new Launch(); launch.setProjectId(4L); launch.setId(2L); @@ -194,7 +194,8 @@ private TestItem getItem(boolean hasIssue) { issue.setIssueId(3L); issue.setIssueType( new IssueType(new IssueGroup(TestItemIssueGroup.PRODUCT_BUG), "locator", "long name", - "SNA", "color")); + "SNA", "color" + )); issue.setIgnoreAnalyzer(false); issue.setAutoAnalyzed(false); issue.setIssueDescription("issue description"); diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/TicketConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/TicketConverterTest.java index c286ef43e2..1e6ed1c49e 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/TicketConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/TicketConverterTest.java @@ -19,7 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.epam.ta.reportportal.entity.bts.Ticket; -import com.epam.ta.reportportal.ws.model.issue.Issue; +import com.epam.ta.reportportal.ws.reporting.Issue; import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/UserConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/UserConverterTest.java index 459b8ed93b..9cc250ff48 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/UserConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/UserConverterTest.java @@ -27,8 +27,8 @@ import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.entity.user.UserType; -import com.epam.ta.reportportal.ws.model.activity.UserActivityResource; -import com.epam.ta.reportportal.ws.model.user.UserResource; +import com.epam.ta.reportportal.model.activity.UserActivityResource; +import com.epam.ta.reportportal.model.user.UserResource; import com.google.common.collect.Sets; import java.util.HashMap; import org.junit.jupiter.api.Test; @@ -38,63 +38,65 @@ */ class UserConverterTest { - @Test - void toResource() { - final User user = getUser(); - final UserResource resource = UserConverter.TO_RESOURCE.apply(user); + @Test + void toResource() { + final User user = getUser(); + final UserResource resource = UserConverter.TO_RESOURCE.apply(user); - assertEquals(resource.getEmail(), user.getEmail()); - assertEquals(resource.getFullName(), user.getFullName()); - assertEquals(resource.getUserId(), user.getLogin()); - assertEquals(resource.getUserRole(), user.getRole().name()); - assertEquals(resource.getAccountType(), user.getUserType().name()); - assertEquals(resource.getPhotoId(), user.getAttachment()); - assertThat((HashMap) resource.getMetadata()).containsAllEntriesOf(getMetadata()); - assertThat(resource.getAssignedProjects()).containsKeys("project1", "project2"); - } + assertEquals(resource.getEmail(), user.getEmail()); + assertEquals(resource.getFullName(), user.getFullName()); + assertEquals(resource.getUserId(), user.getLogin()); + assertEquals(resource.getUserRole(), user.getRole().name()); + assertEquals(resource.getAccountType(), user.getUserType().name()); + assertEquals(resource.getPhotoId(), user.getAttachment()); + assertThat((HashMap) resource.getMetadata()).containsAllEntriesOf( + getMetadata()); + assertThat(resource.getAssignedProjects()).containsKeys("project1", "project2"); + } - @Test - void toActivityResource() { - final User user = getUser(); - final Long projectId = 2L; - final UserActivityResource resource = UserConverter.TO_ACTIVITY_RESOURCE.apply(user, projectId); + @Test + void toActivityResource() { + final User user = getUser(); + final Long projectId = 2L; + final UserActivityResource resource = UserConverter.TO_ACTIVITY_RESOURCE.apply(user, projectId); - assertEquals(resource.getId(), user.getId()); - assertEquals(resource.getFullName(), user.getLogin()); - assertEquals(resource.getDefaultProjectId(), projectId); - } + assertEquals(resource.getId(), user.getId()); + assertEquals(resource.getFullName(), user.getLogin()); + assertEquals(resource.getDefaultProjectId(), projectId); + } - private static User getUser() { - final User user = new User(); - user.setLogin("login"); - user.setUserType(UserType.INTERNAL); - user.setRole(UserRole.USER); - user.setAttachment("attachmentId"); - user.setEmail("example@domain.com"); - user.setFullName("full name"); - user.setId(1L); - user.setAttachmentThumbnail("thumbnailId"); - user.setExpired(false); - final HashMap metadata = getMetadata(); - user.setMetadata(new Metadata(metadata)); - final Project project1 = new Project(); - project1.setName("project1"); - project1.setProjectType(ProjectType.INTERNAL); - final ProjectUser projectUser1 = new ProjectUser().withProject(project1).withProjectRole(ProjectRole.MEMBER).withUser(user); - final Project project2 = new Project(); - project2.setName("project2"); - project2.setProjectType(ProjectType.INTERNAL); - final ProjectUser projectUser2 = new ProjectUser().withProject(project2) - .withProjectRole(ProjectRole.PROJECT_MANAGER) - .withUser(user); - user.setProjects(Sets.newHashSet(projectUser1, projectUser2)); - return user; - } + private static User getUser() { + final User user = new User(); + user.setLogin("login"); + user.setUserType(UserType.INTERNAL); + user.setRole(UserRole.USER); + user.setAttachment("attachmentId"); + user.setEmail("example@domain.com"); + user.setFullName("full name"); + user.setId(1L); + user.setAttachmentThumbnail("thumbnailId"); + user.setExpired(false); + final HashMap metadata = getMetadata(); + user.setMetadata(new Metadata(metadata)); + final Project project1 = new Project(); + project1.setName("project1"); + project1.setProjectType(ProjectType.INTERNAL); + final ProjectUser projectUser1 = + new ProjectUser().withProject(project1).withProjectRole(ProjectRole.MEMBER).withUser(user); + final Project project2 = new Project(); + project2.setName("project2"); + project2.setProjectType(ProjectType.INTERNAL); + final ProjectUser projectUser2 = + new ProjectUser().withProject(project2).withProjectRole(ProjectRole.PROJECT_MANAGER) + .withUser(user); + user.setProjects(Sets.newHashSet(projectUser1, projectUser2)); + return user; + } - private static HashMap getMetadata() { - final HashMap metadata = new HashMap<>(); - metadata.put("key1", "value1"); - metadata.put("key2", "value2"); - return metadata; - } + private static HashMap getMetadata() { + final HashMap metadata = new HashMap<>(); + metadata.put("key1", "value1"); + metadata.put("key2", "value2"); + return metadata; + } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/UserCreationBidConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/UserCreationBidConverterTest.java index b1b0935fdc..797ad0f883 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/UserCreationBidConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/UserCreationBidConverterTest.java @@ -21,7 +21,7 @@ import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.user.UserCreationBid; -import com.epam.ta.reportportal.ws.model.user.CreateUserRQ; +import com.epam.ta.reportportal.model.user.CreateUserRQ; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/WidgetConverterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/WidgetConverterTest.java index 2804bb5490..419224a044 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/converters/WidgetConverterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/converters/WidgetConverterTest.java @@ -16,6 +16,11 @@ package com.epam.ta.reportportal.ws.converter.converters; +import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_LAUNCH_ID; +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.epam.ta.reportportal.commons.querygen.FilterCondition; import com.epam.ta.reportportal.entity.dashboard.Dashboard; import com.epam.ta.reportportal.entity.dashboard.DashboardWidget; @@ -26,146 +31,150 @@ import com.epam.ta.reportportal.entity.project.Project; import com.epam.ta.reportportal.entity.widget.Widget; import com.epam.ta.reportportal.entity.widget.WidgetOptions; -import com.epam.ta.reportportal.ws.model.Position; -import com.epam.ta.reportportal.ws.model.Size; -import com.epam.ta.reportportal.ws.model.activity.WidgetActivityResource; -import com.epam.ta.reportportal.ws.model.dashboard.DashboardResource; -import com.epam.ta.reportportal.ws.model.widget.WidgetResource; +import com.epam.ta.reportportal.model.Position; +import com.epam.ta.reportportal.model.Size; +import com.epam.ta.reportportal.model.activity.WidgetActivityResource; +import com.epam.ta.reportportal.model.dashboard.DashboardResource; +import com.epam.ta.reportportal.model.widget.WidgetResource; import com.google.common.collect.Sets; -import org.junit.jupiter.api.Test; -import org.springframework.data.domain.Sort; - import java.util.HashMap; import java.util.Map; - -import static com.epam.ta.reportportal.commons.querygen.constant.GeneralCriteriaConstant.CRITERIA_LAUNCH_ID; -import static org.assertj.core.api.Java6Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; +import org.springframework.data.domain.Sort; /** * @author Ihar Kahadouski */ class WidgetConverterTest { - @Test - void toWidgetResource() { - final Widget widget = getWidget(); - final WidgetResource resource = WidgetConverter.TO_WIDGET_RESOURCE.apply(widget); - assertEquals(resource.getName(), widget.getName()); - assertEquals(resource.getWidgetId(), widget.getId()); - assertEquals(resource.getWidgetType(), widget.getWidgetType()); - assertEquals(resource.getDescription(), widget.getDescription()); - assertEquals(resource.getOwner(), widget.getOwner()); - assertEquals(resource.getContentParameters().getItemsCount(), widget.getItemsCount()); - assertThat(resource.getContentParameters().getContentFields()).containsExactlyElementsOf(widget.getContentFields()); - assertThat(resource.getContentParameters().getWidgetOptions()).containsAllEntriesOf(widget.getWidgetOptions().getOptions()); - assertThat(resource.getAppliedFilters()).hasSize(1); - } - - @Test - void toActivityResource() { - final Widget widget = getWidget(); - final WidgetActivityResource resource = WidgetConverter.TO_ACTIVITY_RESOURCE.apply(widget); - assertEquals(resource.getId(), widget.getId()); - assertEquals(resource.getName(), widget.getName()); - assertEquals(resource.getProjectId(), widget.getProject().getId()); - assertEquals(resource.getDescription(), widget.getDescription()); - assertEquals(resource.getItemsCount(), widget.getItemsCount()); - assertEquals(resource.getContentFields(), widget.getContentFields()); - assertThat(resource.getWidgetOptions()).containsAllEntriesOf(widget.getWidgetOptions().getOptions()); - } - - @Test - void toObjectModel() { - final DashboardWidget dashboardWidget = getDashboardWIdget(); - final DashboardResource.WidgetObjectModel widgetObjectModel = WidgetConverter.TO_OBJECT_MODEL.apply(dashboardWidget); - - assertEquals(widgetObjectModel.getWidgetId(), dashboardWidget.getId().getWidgetId()); - assertEquals(widgetObjectModel.getWidgetPosition().getX(), dashboardWidget.getPositionX()); - assertEquals(widgetObjectModel.getWidgetPosition().getY(), dashboardWidget.getPositionY()); - assertEquals(widgetObjectModel.getWidgetSize().getHeight(), dashboardWidget.getHeight()); - assertEquals(widgetObjectModel.getWidgetSize().getWidth(), dashboardWidget.getWidth()); - assertEquals(dashboardWidget.getWidget().getWidgetOptions().getOptions(), widgetObjectModel.getWidgetOptions()); - } - - @Test - void toDashboardWidget() { - final DashboardResource.WidgetObjectModel widgetObjectModel = getWidgetObjectModel(); - final Dashboard dashboard = new Dashboard(); - dashboard.setId(2L); - dashboard.setName("name"); - final Widget widget = new Widget(); - widget.setName("name"); - widget.setOwner("default"); - - final DashboardWidget dashboardWidget = WidgetConverter.toDashboardWidget(widgetObjectModel, dashboard, widget, true); - - assertThat(dashboardWidget.getDashboard()).isEqualToComparingFieldByField(dashboard); - assertThat(dashboardWidget.getWidget()).isEqualToComparingFieldByField(widget); - assertEquals(dashboardWidget.getHeight(), widgetObjectModel.getWidgetSize().getHeight()); - assertEquals(dashboardWidget.getWidth(), widgetObjectModel.getWidgetSize().getWidth()); - assertEquals(dashboardWidget.getPositionX(), widgetObjectModel.getWidgetPosition().getX()); - assertEquals(dashboardWidget.getPositionY(), widgetObjectModel.getWidgetPosition().getY()); - assertEquals(dashboardWidget.getWidgetName(), widget.getName()); - assertEquals("default", dashboardWidget.getWidgetOwner()); - assertTrue(dashboardWidget.isCreatedOn()); - } - - private Widget getWidget() { - final Widget widget = new Widget(); - widget.setDescription("description"); - widget.setItemsCount(10); - widget.setWidgetType("widgetType"); - widget.setName("name"); - final Project project = new Project(); - project.setId(3L); - widget.setProject(project); - final WidgetOptions widgetOptions = new WidgetOptions(); - final HashMap options = new HashMap<>(); - options.put("option1", "val1"); - options.put("option2", "val2"); - widgetOptions.setOptions(options); - widget.setWidgetOptions(widgetOptions); - final UserFilter filter = new UserFilter(); - filter.setId(1L); - filter.setOwner("owner"); - filter.setName("name"); - filter.setTargetClass(ObjectType.Launch); - filter.setDescription("filter description"); - filter.setFilterCondition(Sets.newHashSet(FilterCondition.builder().eq(CRITERIA_LAUNCH_ID, "100").build())); - widget.setFilters(Sets.newHashSet(filter)); - final FilterSort filterSort = new FilterSort(); - filterSort.setField("name"); - filterSort.setDirection(Sort.Direction.ASC); - filterSort.setId(2L); - filter.setFilterSorts(Sets.newHashSet(filterSort)); - return widget; - } - - private static DashboardWidget getDashboardWIdget() { - final DashboardWidget dashboardWidget = new DashboardWidget(); - final Widget widget = new Widget(); - widget.setId(1L); - widget.setWidgetOptions(new WidgetOptions(Map.of("hello", "world"))); - dashboardWidget.setWidget(widget); - final Dashboard dashboard = new Dashboard(); - dashboard.setId(2L); - dashboardWidget.setId(new DashboardWidgetId(dashboard.getId(), widget.getId())); - dashboardWidget.setDashboard(dashboard); - dashboardWidget.setPositionX(2); - dashboardWidget.setPositionY(4); - dashboardWidget.setHeight(5); - dashboardWidget.setWidth(6); - return dashboardWidget; - } - - private static DashboardResource.WidgetObjectModel getWidgetObjectModel() { - final DashboardResource.WidgetObjectModel widgetObjectModel = new DashboardResource.WidgetObjectModel(); - widgetObjectModel.setWidgetId(1L); - widgetObjectModel.setWidgetPosition(new Position(3, 5)); - widgetObjectModel.setWidgetSize(new Size(4, 8)); - return widgetObjectModel; - } + @Test + void toWidgetResource() { + final Widget widget = getWidget(); + final WidgetResource resource = WidgetConverter.TO_WIDGET_RESOURCE.apply(widget); + assertEquals(resource.getName(), widget.getName()); + assertEquals(resource.getWidgetId(), widget.getId()); + assertEquals(resource.getWidgetType(), widget.getWidgetType()); + assertEquals(resource.getDescription(), widget.getDescription()); + assertEquals(resource.getOwner(), widget.getOwner()); + assertEquals(resource.getContentParameters().getItemsCount(), widget.getItemsCount()); + assertThat(resource.getContentParameters().getContentFields()).containsExactlyElementsOf( + widget.getContentFields()); + assertThat(resource.getContentParameters().getWidgetOptions()).containsAllEntriesOf( + widget.getWidgetOptions().getOptions()); + assertThat(resource.getAppliedFilters()).hasSize(1); + } + + @Test + void toActivityResource() { + final Widget widget = getWidget(); + final WidgetActivityResource resource = WidgetConverter.TO_ACTIVITY_RESOURCE.apply(widget); + assertEquals(resource.getId(), widget.getId()); + assertEquals(resource.getName(), widget.getName()); + assertEquals(resource.getProjectId(), widget.getProject().getId()); + assertEquals(resource.getDescription(), widget.getDescription()); + assertEquals(resource.getItemsCount(), widget.getItemsCount()); + assertEquals(resource.getContentFields(), widget.getContentFields()); + assertThat(resource.getWidgetOptions()).containsAllEntriesOf( + widget.getWidgetOptions().getOptions()); + } + + @Test + void toObjectModel() { + final DashboardWidget dashboardWidget = getDashboardWIdget(); + final DashboardResource.WidgetObjectModel widgetObjectModel = + WidgetConverter.TO_OBJECT_MODEL.apply(dashboardWidget); + + assertEquals(widgetObjectModel.getWidgetId(), dashboardWidget.getId().getWidgetId()); + assertEquals(widgetObjectModel.getWidgetPosition().getX(), dashboardWidget.getPositionX()); + assertEquals(widgetObjectModel.getWidgetPosition().getY(), dashboardWidget.getPositionY()); + assertEquals(widgetObjectModel.getWidgetSize().getHeight(), dashboardWidget.getHeight()); + assertEquals(widgetObjectModel.getWidgetSize().getWidth(), dashboardWidget.getWidth()); + assertEquals( + dashboardWidget.getWidget().getWidgetOptions().getOptions(), + widgetObjectModel.getWidgetOptions() + ); + } + + @Test + void toDashboardWidget() { + final DashboardResource.WidgetObjectModel widgetObjectModel = getWidgetObjectModel(); + final Dashboard dashboard = new Dashboard(); + dashboard.setId(2L); + dashboard.setName("name"); + final Widget widget = new Widget(); + widget.setName("name"); + widget.setOwner("default"); + + final DashboardWidget dashboardWidget = + WidgetConverter.toDashboardWidget(widgetObjectModel, dashboard, widget, true); + + assertThat(dashboardWidget.getDashboard()).isEqualToComparingFieldByField(dashboard); + assertThat(dashboardWidget.getWidget()).isEqualToComparingFieldByField(widget); + assertEquals(dashboardWidget.getHeight(), widgetObjectModel.getWidgetSize().getHeight()); + assertEquals(dashboardWidget.getWidth(), widgetObjectModel.getWidgetSize().getWidth()); + assertEquals(dashboardWidget.getPositionX(), widgetObjectModel.getWidgetPosition().getX()); + assertEquals(dashboardWidget.getPositionY(), widgetObjectModel.getWidgetPosition().getY()); + assertEquals(dashboardWidget.getWidgetName(), widget.getName()); + assertEquals("default", dashboardWidget.getWidgetOwner()); + assertTrue(dashboardWidget.isCreatedOn()); + } + + private Widget getWidget() { + final Widget widget = new Widget(); + widget.setDescription("description"); + widget.setItemsCount(10); + widget.setWidgetType("widgetType"); + widget.setName("name"); + final Project project = new Project(); + project.setId(3L); + widget.setProject(project); + final WidgetOptions widgetOptions = new WidgetOptions(); + final HashMap options = new HashMap<>(); + options.put("option1", "val1"); + options.put("option2", "val2"); + widgetOptions.setOptions(options); + widget.setWidgetOptions(widgetOptions); + final UserFilter filter = new UserFilter(); + filter.setId(1L); + filter.setOwner("owner"); + filter.setName("name"); + filter.setTargetClass(ObjectType.Launch); + filter.setDescription("filter description"); + filter.setFilterCondition( + Sets.newHashSet(FilterCondition.builder().eq(CRITERIA_LAUNCH_ID, "100").build())); + widget.setFilters(Sets.newHashSet(filter)); + final FilterSort filterSort = new FilterSort(); + filterSort.setField("name"); + filterSort.setDirection(Sort.Direction.ASC); + filterSort.setId(2L); + filter.setFilterSorts(Sets.newHashSet(filterSort)); + return widget; + } + + private static DashboardWidget getDashboardWIdget() { + final DashboardWidget dashboardWidget = new DashboardWidget(); + final Widget widget = new Widget(); + widget.setId(1L); + widget.setWidgetOptions(new WidgetOptions(Map.of("hello", "world"))); + dashboardWidget.setWidget(widget); + final Dashboard dashboard = new Dashboard(); + dashboard.setId(2L); + dashboardWidget.setId(new DashboardWidgetId(dashboard.getId(), widget.getId())); + dashboardWidget.setDashboard(dashboard); + dashboardWidget.setPositionX(2); + dashboardWidget.setPositionY(4); + dashboardWidget.setHeight(5); + dashboardWidget.setWidth(6); + return dashboardWidget; + } + + private static DashboardResource.WidgetObjectModel getWidgetObjectModel() { + final DashboardResource.WidgetObjectModel widgetObjectModel = + new DashboardResource.WidgetObjectModel(); + widgetObjectModel.setWidgetId(1L); + widgetObjectModel.setWidgetPosition(new Position(3, 5)); + widgetObjectModel.setWidgetSize(new Size(4, 8)); + return widgetObjectModel; + } } \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceAttributeUpdaterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceAttributeUpdaterTest.java index f58d7b5c7a..4b52d367cb 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceAttributeUpdaterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceAttributeUpdaterTest.java @@ -20,8 +20,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.epam.ta.reportportal.entity.ItemAttribute; -import com.epam.ta.reportportal.ws.model.attribute.ItemAttributeResource; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; +import com.epam.ta.reportportal.ws.reporting.ItemAttributeResource; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; import java.util.List; import java.util.Map; import java.util.Set; diff --git a/src/test/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceMetadataAttributeUpdaterTest.java b/src/test/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceMetadataAttributeUpdaterTest.java index f09dadb2fe..5c584d2859 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceMetadataAttributeUpdaterTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/converter/resource/handler/attribute/launch/LaunchResourceMetadataAttributeUpdaterTest.java @@ -19,7 +19,7 @@ import static com.epam.ta.reportportal.core.launch.cluster.pipeline.SaveLastRunAttributePartProvider.RP_CLUSTER_LAST_RUN_KEY; import com.epam.ta.reportportal.entity.ItemAttribute; -import com.epam.ta.reportportal.ws.model.launch.LaunchResource; +import com.epam.ta.reportportal.ws.reporting.LaunchResource; import java.util.List; import java.util.Map; import java.util.Set; diff --git a/src/test/java/com/epam/ta/reportportal/ws/rabbit/AsyncReportingListenerTest.java b/src/test/java/com/epam/ta/reportportal/ws/rabbit/AsyncReportingListenerTest.java index e86e86e793..32d4d4796c 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/rabbit/AsyncReportingListenerTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/rabbit/AsyncReportingListenerTest.java @@ -33,12 +33,12 @@ import com.epam.ta.reportportal.entity.log.LogFull; import com.epam.ta.reportportal.util.ProjectExtractor; import com.epam.ta.reportportal.ws.converter.builders.LogFullBuilder; -import com.epam.ta.reportportal.ws.model.FinishExecutionRQ; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; -import com.epam.ta.reportportal.ws.model.StartTestItemRQ; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; -import com.epam.ta.reportportal.ws.model.log.SaveLogRQ.File; +import com.epam.ta.reportportal.ws.reporting.FinishExecutionRQ; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ; +import com.epam.ta.reportportal.ws.reporting.SaveLogRQ.File; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; +import com.epam.ta.reportportal.ws.reporting.StartTestItemRQ; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -241,7 +241,8 @@ void whenMessageReceived_andItemIsNotPresent_thenCreateLaunchLog() { when(launch.getId()).thenReturn(ID); when(launchRepository.findByUuid(LAUNCH_ID)).thenReturn(Optional.of(launch)); - LogFull logFull = new LogFullBuilder().addSaveLogRq(saveLogRQ).addLaunch(launch).addProjectId(ID).get(); + LogFull logFull = new LogFullBuilder().addSaveLogRq(saveLogRQ).addLaunch(launch) + .addProjectId(ID).get(); final Log log = LOG_FULL_TO_LOG.apply(logFull); asyncReportingListener.onMessage(message); @@ -280,7 +281,8 @@ void whenMessageReceived_andItemIsPresent_thenCreateItemLog() { TestItem testItem = mock(TestItem.class); when(testItemRepository.findByUuid(ITEM_ID)).thenReturn(Optional.of(testItem)); - LogFull logFull = new LogFullBuilder().addSaveLogRq(saveLogRQ).addTestItem(testItem).addProjectId(ID).get(); + LogFull logFull = new LogFullBuilder().addSaveLogRq(saveLogRQ).addTestItem(testItem) + .addProjectId(ID).get(); final Log log = LOG_FULL_TO_LOG.apply(logFull); Launch launch = mock(Launch.class); diff --git a/src/test/java/com/epam/ta/reportportal/ws/validation/BusinessRuleTest.java b/src/test/java/com/epam/ta/reportportal/ws/validation/BusinessRuleTest.java index 8671cc0bb8..7a4a958f25 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/validation/BusinessRuleTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/validation/BusinessRuleTest.java @@ -24,7 +24,7 @@ import com.epam.ta.reportportal.commons.validation.BusinessRuleViolationException; import com.epam.ta.reportportal.commons.validation.Suppliers; import com.epam.ta.reportportal.exception.ReportPortalException; -import com.epam.ta.reportportal.ws.model.ErrorType; +import com.epam.ta.reportportal.ws.reporting.ErrorType; import org.junit.jupiter.api.Test; /** diff --git a/src/test/java/com/epam/ta/reportportal/ws/validation/JaskonRequiredPropertiesValidatorTest.java b/src/test/java/com/epam/ta/reportportal/ws/validation/JaskonRequiredPropertiesValidatorTest.java index 2d5b6e21c4..f6b49b05e3 100644 --- a/src/test/java/com/epam/ta/reportportal/ws/validation/JaskonRequiredPropertiesValidatorTest.java +++ b/src/test/java/com/epam/ta/reportportal/ws/validation/JaskonRequiredPropertiesValidatorTest.java @@ -21,10 +21,10 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; -import com.epam.ta.reportportal.ws.model.issue.Issue; -import com.epam.ta.reportportal.ws.model.issue.IssueDefinition; -import com.epam.ta.reportportal.ws.model.launch.StartLaunchRQ; +import com.epam.ta.reportportal.model.issue.IssueDefinition; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.Issue; +import com.epam.ta.reportportal.ws.reporting.StartLaunchRQ; import java.util.Calendar; import java.util.Collections; import java.util.UUID; diff --git a/src/test/java/com/epam/ta/reportportal/ws/validation/PageTest.java b/src/test/java/com/epam/ta/reportportal/ws/validation/PageTest.java new file mode 100644 index 0000000000..4219ccc390 --- /dev/null +++ b/src/test/java/com/epam/ta/reportportal/ws/validation/PageTest.java @@ -0,0 +1,47 @@ +package com.epam.ta.reportportal.ws.validation; + +import com.epam.ta.reportportal.model.Page; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Tests for {@link Page.PageMetadata} + * Initially grabbed from Spring's PagedResourcesUnitTest.java + * + * @author Andrei Varabyeu + */ +public class PageTest { + + private static final Page.PageMetadata METADATA = new Page.PageMetadata(10, 1, 200); + + @Test + public void preventsNegativePageSize() { + assertThrows(IllegalArgumentException.class, () -> new Page.PageMetadata(-1, 0, 0)); + } + + @Test + public void preventsNegativePageNumber() { + assertThrows(IllegalArgumentException.class, () -> new Page.PageMetadata(0, -1, 0)); + } + + @Test + public void preventsNegativeTotalElements() { + assertThrows(IllegalArgumentException.class, () -> new Page.PageMetadata(0, 0, -1)); + } + + @Test + public void preventsNegativeTotalPages() { + assertThrows(IllegalArgumentException.class, () -> new Page.PageMetadata(0, 0, 0, -1)); + } + + @Test + public void allowsOneIndexedPages() { + assertDoesNotThrow(() -> new Page.PageMetadata(10, 1, 0)); + } + + @Test + public void calculatesTotalPagesCorrectly() { + assertEquals(4L, new Page.PageMetadata(5, 0, 16).getTotalPages()); + } +} \ No newline at end of file diff --git a/src/test/java/com/epam/ta/reportportal/ws/validation/TicketsValidationTest.java b/src/test/java/com/epam/ta/reportportal/ws/validation/TicketsValidationTest.java new file mode 100644 index 0000000000..9e433bf7b6 --- /dev/null +++ b/src/test/java/com/epam/ta/reportportal/ws/validation/TicketsValidationTest.java @@ -0,0 +1,130 @@ +package com.epam.ta.reportportal.ws.validation; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.epam.ta.reportportal.model.item.LinkExternalIssueRQ; +import com.epam.ta.reportportal.ws.reporting.FinishTestItemRQ; +import com.epam.ta.reportportal.ws.reporting.Issue; +import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** + * @author Pavel Bortnik + */ +public class TicketsValidationTest { + + private static Validator validator; + + @BeforeAll + public static void init() { + Locale.setDefault(Locale.US); + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void finishIncorrectTicket() { + FinishTestItemRQ finishTestItem = getFinishTestItem(); + + Issue issue = new Issue(); + issue.setIssueType("ti001"); + + Set tickets = new HashSet<>(); + tickets.add(new Issue.ExternalSystemIssue()); + issue.setExternalSystemIssues(tickets); + + finishTestItem.setIssue(issue); + + Set> validate = validator.validate(finishTestItem); + + assertEquals(validate.size(), 4); + validate.forEach(it -> assertEquals(it.getMessage(), "must not be blank")); + } + + @Test + public void finishWithCorrectTicket() { + FinishTestItemRQ finishTestItem = getFinishTestItem(); + + Issue issue = new Issue(); + issue.setIssueType("ti001"); + + Set tickets = new HashSet<>(); + Issue.ExternalSystemIssue ticket = new Issue.ExternalSystemIssue(); + ticket.setTicketId("1234"); + ticket.setBtsUrl("btsUrl"); + ticket.setBtsProject("btsProject"); + ticket.setUrl("btsProject"); + tickets.add(ticket); + issue.setExternalSystemIssues(tickets); + + finishTestItem.setIssue(issue); + + Set> validate = validator.validate(finishTestItem); + + assertTrue(validate.isEmpty()); + } + + @Test + public void linkEmptyCollections() { + final LinkExternalIssueRQ linkExternalIssueRQ = new LinkExternalIssueRQ(); + linkExternalIssueRQ.setTestItemIds(new ArrayList<>()); + linkExternalIssueRQ.setIssues(new ArrayList<>()); + Set> validate = + validator.validate(linkExternalIssueRQ); + + assertEquals(validate.size(), 2); + validate.forEach(it -> assertEquals(it.getMessage(), "must not be empty")); + } + + @Test + public void linkIncorrectTicket() { + LinkExternalIssueRQ linkExternalIssueRQ = new LinkExternalIssueRQ(); + linkExternalIssueRQ.setTestItemIds(Lists.newArrayList(1L)); + + Issue.ExternalSystemIssue ticket = new Issue.ExternalSystemIssue(); + linkExternalIssueRQ.setIssues(Lists.newArrayList(ticket)); + + Set> validate = + validator.validate(linkExternalIssueRQ); + + System.out.println(); + + assertEquals(validate.size(), 4); + validate.forEach(it -> assertEquals(it.getMessage(), "must not be blank")); + } + + @Test + public void linkWithCorrectTicket() { + LinkExternalIssueRQ linkExternalIssueRQ = new LinkExternalIssueRQ(); + linkExternalIssueRQ.setTestItemIds(Lists.newArrayList(1L)); + + Issue.ExternalSystemIssue ticket = new Issue.ExternalSystemIssue(); + ticket.setTicketId("1234"); + ticket.setBtsUrl("btsUrl"); + ticket.setBtsProject("btsProject"); + ticket.setUrl("btsProject"); + linkExternalIssueRQ.setIssues(Lists.newArrayList(ticket)); + + Set> validate = + validator.validate(linkExternalIssueRQ); + + assertTrue(validate.isEmpty()); + } + + private FinishTestItemRQ getFinishTestItem() { + FinishTestItemRQ finishTestItemRQ = new FinishTestItemRQ(); + finishTestItemRQ.setStatus("PASSED"); + finishTestItemRQ.setEndTime(new Date()); + return finishTestItemRQ; + } + +} diff --git a/src/test/java/com/epam/ta/reportportal/ws/validation/WidgetRqValidatorTest.java b/src/test/java/com/epam/ta/reportportal/ws/validation/WidgetRqValidatorTest.java new file mode 100644 index 0000000000..0e7132f779 --- /dev/null +++ b/src/test/java/com/epam/ta/reportportal/ws/validation/WidgetRqValidatorTest.java @@ -0,0 +1,76 @@ +package com.epam.ta.reportportal.ws.validation; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.epam.ta.reportportal.model.widget.ContentParameters; +import com.epam.ta.reportportal.model.widget.MaterializedWidgetType; +import com.epam.ta.reportportal.model.widget.WidgetRQ; +import com.epam.ta.reportportal.ws.model.ValidationConstraints; +import java.util.Collections; +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** + * @author Pavel Bortnik + */ +public class WidgetRqValidatorTest { + + private static Validator validator; + + @BeforeAll + public static void init() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void validWidgetRQ() { + WidgetRQ widgetRQ = basicWidgetRq(); + final Set> validate = validator.validate(widgetRQ); + assertTrue(validate.isEmpty()); + } + + @Test + public void invalidLimitWidgetRQ() { + WidgetRQ widgetRQ = basicWidgetRq(); + widgetRQ.getContentParameters().setItemsCount(601); + final Set> validate = validator.validate(widgetRQ); + assertEquals(1, validate.size()); + assertEquals( + "Widget item limit size must be between " + ValidationConstraints.MIN_WIDGET_LIMIT + " and " + + ValidationConstraints.MAX_WIDGET_LIMIT, + validate.stream().findFirst().get().getMessage() + ); + } + + @Test + public void validLimitMaterializedView() { + WidgetRQ widgetRQ = basicWidgetRq(); + widgetRQ.setWidgetType(MaterializedWidgetType.COMPONENT_HEALTH_CHECK_TABLE.getType()); + widgetRQ.getContentParameters().setItemsCount(601); + Set> validate = validator.validate(widgetRQ); + assertTrue(validate.isEmpty()); + } + + private WidgetRQ basicWidgetRq() { + WidgetRQ widgetRQ = new WidgetRQ(); + widgetRQ.setName("testWidget"); + widgetRQ.setWidgetType("componentHealthCheck"); + widgetRQ.setFilterIds(Collections.emptyList()); + widgetRQ.setDescription("testDescription"); + + ContentParameters contentParameters = new ContentParameters(); + contentParameters.setContentFields(Collections.emptyList()); + contentParameters.setItemsCount(100); + contentParameters.setWidgetOptions(Collections.emptyMap()); + + widgetRQ.setContentParameters(contentParameters); + + return widgetRQ; + } + +}