diff options
author | Julien Camus <julien.camus@sonarsource.com> | 2024-12-17 17:37:43 +0100 |
---|---|---|
committer | Steve Marion <steve.marion@sonarsource.com> | 2024-12-18 11:13:24 +0100 |
commit | 108e25bce0062be83ab15c587aecfa1e51ba5cf1 (patch) | |
tree | 8102236ce649305a1d270a56cc284d5d12a4c31c | |
parent | 16e6a0469c02298a8b5c478313dd68c93705922e (diff) | |
download | sonarqube-108e25bce0062be83ab15c587aecfa1e51ba5cf1.tar.gz sonarqube-108e25bce0062be83ab15c587aecfa1e51ba5cf1.zip |
SONAR-24004 Replace lambda with method reference
62 files changed, 381 insertions, 415 deletions
diff --git a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/AdHocRuleCreatorIT.java b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/AdHocRuleCreatorIT.java index 4327e98bad7..dcd42febcb9 100644 --- a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/AdHocRuleCreatorIT.java +++ b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/AdHocRuleCreatorIT.java @@ -30,6 +30,7 @@ import org.sonar.api.utils.System2; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbSession; import org.sonar.db.DbTester; +import org.sonar.db.issue.ImpactDto; import org.sonar.db.rule.RuleDto; import org.sonar.scanner.protocol.Constants; import org.sonar.scanner.protocol.output.ScannerReport; @@ -71,7 +72,7 @@ public class AdHocRuleCreatorIT { assertThat(rule.getAdHocSeverity()).isNull(); assertThat(rule.getAdHocType()).isNull(); assertThat(rule.getCleanCodeAttribute()).isEqualTo(CleanCodeAttribute.defaultCleanCodeAttribute()); - assertThat(rule.getDefaultImpacts()).extracting(i -> i.getSoftwareQuality(), i -> i.getSeverity()) + assertThat(rule.getDefaultImpacts()).extracting(ImpactDto::getSoftwareQuality, ImpactDto::getSeverity) .containsExactly(Tuple.tuple(SoftwareQuality.MAINTAINABILITY, org.sonar.api.issue.impact.Severity.MEDIUM)); } @@ -105,7 +106,7 @@ public class AdHocRuleCreatorIT { assertThat(rule.getAdHocSeverity()).isEqualTo(Severity.BLOCKER); assertThat(rule.getAdHocType()).isEqualTo(RuleType.BUG.getDbConstant()); assertThat(rule.getCleanCodeAttribute()).isEqualTo(CleanCodeAttribute.DISTINCT); - assertThat(rule.getDefaultImpacts()).extracting(i -> i.getSoftwareQuality(), i -> i.getSeverity()) + assertThat(rule.getDefaultImpacts()).extracting(ImpactDto::getSoftwareQuality, ImpactDto::getSeverity) .containsExactly(tuple(SoftwareQuality.RELIABILITY, org.sonar.api.issue.impact.Severity.LOW)); } diff --git a/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/NewSizeMeasuresStep.java b/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/NewSizeMeasuresStep.java index fc33b908e16..38dd2250a36 100644 --- a/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/NewSizeMeasuresStep.java +++ b/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/NewSizeMeasuresStep.java @@ -76,7 +76,7 @@ public class NewSizeMeasuresStep implements ComputationStep { new PathAwareCrawler<>( FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) .buildFor(List.of(duplicationFormula))) - .visit(treeRootHolder.getRoot()); + .visit(treeRootHolder.getRoot()); } private static class NewSizeCounter implements Counter<NewSizeCounter> { @@ -131,7 +131,7 @@ public class NewSizeMeasuresStep implements ComputationStep { duplicationCounters.addBlock(duplication.getOriginal()); Arrays.stream(duplication.getDuplicates()) .filter(InnerDuplicate.class::isInstance) - .map(duplicate -> (InnerDuplicate) duplicate) + .map(InnerDuplicate.class::cast) .forEach(duplicate -> duplicationCounters.addBlock(duplicate.getTextBlock())); } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactoryTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactoryTest.java index dbd6a1cf073..646061b3525 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactoryTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactoryTest.java @@ -209,7 +209,8 @@ class TrackerRawInputFactoryTest { assertThat(locations.getFlow(0).getLocation(0).getMsg()).isEqualTo("loc1"); assertThat(locations.getFlow(0).getLocation(0).getMsgFormattingCount()).isEqualTo(1); - assertThat(locations.getFlow(0).getLocation(0).getMsgFormatting(0)).extracting(m -> m.getStart(), m -> m.getEnd(), m -> m.getType()) + assertThat(locations.getFlow(0).getLocation(0).getMsgFormatting(0)) + .extracting(DbIssues.MessageFormatting::getStart, DbIssues.MessageFormatting::getEnd, DbIssues.MessageFormatting::getType) .containsExactly(0, 4, DbIssues.MessageFormattingType.CODE); assertThat(locations.getFlow(1).hasDescription()).isFalse(); @@ -395,8 +396,7 @@ class TrackerRawInputFactoryTest { Arguments.of(IssueType.CODE_SMELL, RuleType.CODE_SMELL, STATUS_OPEN), Arguments.of(IssueType.BUG, RuleType.BUG, STATUS_OPEN), Arguments.of(IssueType.VULNERABILITY, RuleType.VULNERABILITY, STATUS_OPEN), - Arguments.of(IssueType.SECURITY_HOTSPOT, RuleType.SECURITY_HOTSPOT, STATUS_TO_REVIEW) - ); + Arguments.of(IssueType.SECURITY_HOTSPOT, RuleType.SECURITY_HOTSPOT, STATUS_TO_REVIEW)); } @ParameterizedTest @@ -570,7 +570,8 @@ class TrackerRawInputFactoryTest { } private void registerRule(RuleKey ruleKey, String name) { - registerRule(ruleKey, name, r -> {}); + registerRule(ruleKey, name, r -> { + }); } private void registerRule(RuleKey ruleKey, String name, Consumer<DumbRule> dumbRulePopulator) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MapBasedRawMeasureRepositoryTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MapBasedRawMeasureRepositoryTest.java index b695087fb7f..26747289941 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MapBasedRawMeasureRepositoryTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MapBasedRawMeasureRepositoryTest.java @@ -92,7 +92,7 @@ public class MapBasedRawMeasureRepositoryTest { @Test public void add_throws_NPE_if_Component_argument_is_null() { - assertThatThrownBy(() -> underTest.add(null, metric1, SOME_MEASURE)) + assertThatThrownBy(() -> underTest.add(null, metric1, SOME_MEASURE)) .isInstanceOf(NullPointerException.class); } @@ -153,7 +153,7 @@ public class MapBasedRawMeasureRepositoryTest { public static Object[][] measures() { return MEASURES.stream() .map(c -> new Measure[] {c}) - .toArray(i -> new Object[i][]); + .toArray(Object[][]::new); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateMeasuresStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateMeasuresStepTest.java index 27e05834df3..58747ebe4cc 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateMeasuresStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateMeasuresStepTest.java @@ -145,7 +145,7 @@ class QualityGateMeasuresStepTest { underTest.execute(new TestComputationStepContext()); - assertThatThrownBy(() -> qualityGateStatusHolder.getStatus()) + assertThatThrownBy(qualityGateStatusHolder::getStatus) .isInstanceOf(IllegalStateException.class) .hasMessage("Quality gate status has not been set yet"); } diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/issue/IssueDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/issue/IssueDaoIT.java index 15758d0f49b..861c73e0d2b 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/issue/IssueDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/issue/IssueDaoIT.java @@ -651,18 +651,17 @@ class IssueDaoIT { i -> i.setStatus(STATUS_REOPENED).setEffort(60L).replaceAllImpacts(List.of(createImpact(RELIABILITY, INFO), createImpact(SECURITY, BLOCKER)))); db.issues().insert(rule, project, file, - i -> i.setStatus(STATUS_RESOLVED).setEffort(60L).setResolution(RESOLUTION_WONT_FIX).replaceAllImpacts(List.of(createImpact(MAINTAINABILITY, HIGH), createImpact(RELIABILITY, INFO), createImpact(SECURITY, BLOCKER)))); + i -> i.setStatus(STATUS_RESOLVED).setEffort(60L).setResolution(RESOLUTION_WONT_FIX) + .replaceAllImpacts(List.of(createImpact(MAINTAINABILITY, HIGH), createImpact(RELIABILITY, INFO), createImpact(SECURITY, BLOCKER)))); db.issues().insert(rule, project, file, - i -> i.setStatus(STATUS_RESOLVED).setEffort(60L).setResolution(RESOLUTION_WONT_FIX).replaceAllImpacts(List.of(createImpact(SECURITY - , HIGH)))); + i -> i.setStatus(STATUS_RESOLVED).setEffort(60L).setResolution(RESOLUTION_WONT_FIX).replaceAllImpacts(List.of(createImpact(SECURITY, HIGH)))); // issues in ignored status db.issues().insert(rule, project, file, i -> i.setStatus(Issue.STATUS_CLOSED).setEffort(60L).replaceAllImpacts(List.of(createImpact(SECURITY, HIGH)))); db.issues().insert(rule, project, file, i -> i.setStatus(STATUS_RESOLVED).setEffort(60L).setResolution(RESOLUTION_FALSE_POSITIVE).replaceAllImpacts(List.of(createImpact(SECURITY, HIGH)))); - Collection<IssueImpactSeverityGroupDto> result = underTest.selectIssueImpactSeverityGroupsByComponent(db.getSession(), file, inLeak ? - 1L : Long.MAX_VALUE); + Collection<IssueImpactSeverityGroupDto> result = underTest.selectIssueImpactSeverityGroupsByComponent(db.getSession(), file, inLeak ? 1L : Long.MAX_VALUE); assertThat(result).hasSize(6); assertThat(result.stream().filter(IssueImpactSeverityGroupDto::isInLeak)).hasSize(inLeak ? 6 : 0); @@ -1096,8 +1095,7 @@ class IssueDaoIT { underTest.updateIfBeforeSelectedDate(db.getSession(), issueDto); - assertThat(underTest.selectOrFailByKey(db.getSession(), ISSUE_KEY1).getImpacts()).extracting(i -> i.getSoftwareQuality(), - i -> i.getSeverity()) + assertThat(underTest.selectOrFailByKey(db.getSession(), ISSUE_KEY1).getImpacts()).extracting(ImpactDto::getSoftwareQuality, ImpactDto::getSeverity) .containsExactlyInAnyOrder(tuple(RELIABILITY, MEDIUM), tuple(SECURITY, LOW)); } @@ -1111,7 +1109,7 @@ class IssueDaoIT { underTest.insert(db.getSession(), issueDto); assertThat(underTest.selectOrFailByKey(db.getSession(), ISSUE_KEY1).getImpacts()).extracting(ImpactDto::getSoftwareQuality, - ImpactDto::getSeverity, ImpactDto::isManualSeverity) + ImpactDto::getSeverity, ImpactDto::isManualSeverity) .containsExactlyInAnyOrder(tuple(MAINTAINABILITY, MEDIUM, true), tuple(RELIABILITY, HIGH, false)); } diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/purge/PurgeCommandsIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/purge/PurgeCommandsIT.java index b250f707397..95e5ef37cd5 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/purge/PurgeCommandsIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/purge/PurgeCommandsIT.java @@ -780,7 +780,7 @@ class PurgeCommandsIT { purgeCommands.deleteReportSchedules(mainBranch.getUuid()); assertThat(dbTester.getDbClient().reportScheduleDao().selectAll(dbTester.getSession())).hasSize(1) - .extracting(r -> r.getUuid()).containsExactly("uuid2"); + .extracting(ReportScheduleDto::getUuid).containsExactly("uuid2"); } @Test @@ -799,25 +799,22 @@ class PurgeCommandsIT { purgeCommands.deleteReportSubscriptions(mainBranch.getUuid()); assertThat(dbTester.getDbClient().reportSubscriptionDao().selectAll(dbTester.getSession())).hasSize(1) - .extracting(r -> r.getUuid()).containsExactly("uuid2"); + .extracting(ReportSubscriptionDto::getUuid).containsExactly("uuid2"); } @Test void deleteAnticipatedTransitions_shouldDeleteAnticipatedTransitionsOlderThanDate() { ComponentDto projectDto = ComponentTesting.newPrivateProjectDto(); - //dates at the boundary of the deletion threshold set to 30 days + // dates at the boundary of the deletion threshold set to 30 days Instant okCreationDate = Instant.now().minus(29, ChronoUnit.DAYS); Instant oldCreationDate = Instant.now().minus(31, ChronoUnit.DAYS); - dbTester.getDbClient().anticipatedTransitionDao().insert(dbTester.getSession(), getAnticipatedTransitionsDto(projectDto.uuid() + "ok" - , projectDto.uuid(), okCreationDate)); - dbTester.getDbClient().anticipatedTransitionDao().insert(dbTester.getSession(), getAnticipatedTransitionsDto(projectDto.uuid() + "old" - , projectDto.uuid(), oldCreationDate)); + dbTester.getDbClient().anticipatedTransitionDao().insert(dbTester.getSession(), getAnticipatedTransitionsDto(projectDto.uuid() + "ok", projectDto.uuid(), okCreationDate)); + dbTester.getDbClient().anticipatedTransitionDao().insert(dbTester.getSession(), getAnticipatedTransitionsDto(projectDto.uuid() + "old", projectDto.uuid(), oldCreationDate)); underTest.deleteAnticipatedTransitions(projectDto.uuid(), Instant.now().minus(30, ChronoUnit.DAYS).toEpochMilli()); - List<AnticipatedTransitionDto> anticipatedTransitionDtos = - dbTester.getDbClient().anticipatedTransitionDao().selectByProjectUuid(dbTester.getSession(), projectDto.uuid()); + List<AnticipatedTransitionDto> anticipatedTransitionDtos = dbTester.getDbClient().anticipatedTransitionDao().selectByProjectUuid(dbTester.getSession(), projectDto.uuid()); assertThat(anticipatedTransitionDtos).hasSize(1); assertThat(anticipatedTransitionDtos.get(0).getUuid()).isEqualTo(projectDto.uuid() + "ok"); @@ -973,13 +970,13 @@ class PurgeCommandsIT { } private static Object[] projects() { - return new Object[]{ + return new Object[] { ComponentTesting.newPrivateProjectDto(), ComponentTesting.newPublicProjectDto(), }; } private static Object[] views() { - return new Object[]{ + return new Object[] { ComponentTesting.newPortfolio(), ComponentTesting.newApplication() }; } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/DBSessionsImplTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/DBSessionsImplTest.java index 6a42b7b2b93..5dfe2717682 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/DBSessionsImplTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/DBSessionsImplTest.java @@ -33,6 +33,7 @@ import java.util.stream.IntStream; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; +import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -408,7 +409,7 @@ class DBSessionsImplTest { return dbSession; } - private static DbSessionCaller[] DIRTYING_CALLS = { + private static final DbSessionCaller[] DIRTYING_CALLS = { session -> session.insert(secure().nextAlphabetic(3)), session -> session.insert(secure().nextAlphabetic(2), new Object()), session -> session.update(secure().nextAlphabetic(3)), @@ -417,17 +418,11 @@ class DBSessionsImplTest { session -> session.delete(secure().nextAlphabetic(3), new Object()), }; - private static DbSessionCaller[] COMMIT_CALLS = { - session -> session.commit(), + private static final DbSessionCaller[] COMMIT_CALLS = {SqlSession::commit, session -> session.commit(new Random().nextBoolean()), }; - private static DbSessionCaller[] ROLLBACK_CALLS = { - session -> session.rollback(), - session -> session.rollback(new Random().nextBoolean()), - }; - - private static DbSessionCaller[] NEUTRAL_CALLS = { + private static final DbSessionCaller[] NEUTRAL_CALLS = { session -> session.selectOne(secure().nextAlphabetic(3)), session -> session.selectOne(secure().nextAlphabetic(3), new Object()), session -> session.select(secure().nextAlphabetic(3), mock(ResultHandler.class)), @@ -439,11 +434,7 @@ class DBSessionsImplTest { session -> session.selectMap(secure().nextAlphabetic(3), secure().nextAlphabetic(3)), session -> session.selectMap(secure().nextAlphabetic(3), new Object(), secure().nextAlphabetic(3)), session -> session.selectMap(secure().nextAlphabetic(3), new Object(), secure().nextAlphabetic(3), new RowBounds()), - session -> session.getMapper(Object.class), - session -> session.getConfiguration(), - session -> session.getConnection(), - session -> session.clearCache(), - session -> session.flushStatements() + session -> session.getMapper(Object.class), SqlSession::getConfiguration, SqlSession::getConnection, SqlSession::clearCache, SqlSession::flushStatements }; private interface DbSessionCaller { diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/OffsetBasedPaginationTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/OffsetBasedPaginationTest.java index ae30debc1f1..3136b8f227f 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/OffsetBasedPaginationTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/OffsetBasedPaginationTest.java @@ -51,7 +51,7 @@ class OffsetBasedPaginationTest { @Test void forOffset_whenZeroOffset_shouldStartOffsetAtZero() { assertThat(OffsetBasedPagination.forOffset(0, 100)) - .extracting(p -> p.getOffset(), p -> p.getPageSize()) + .extracting(OffsetBasedPagination::getOffset, OffsetBasedPagination::getPageSize) .containsExactly(0, 100); } diff --git a/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/step/DataChangeIT.java b/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/step/DataChangeIT.java index 273fbca71d1..e272adf70b4 100644 --- a/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/step/DataChangeIT.java +++ b/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/step/DataChangeIT.java @@ -160,7 +160,7 @@ class DataChangeIT { } }; - assertThatThrownBy(() -> change.execute()) + assertThatThrownBy(change::execute) .isInstanceOf(SQLException.class); } @@ -437,8 +437,7 @@ class DataChangeIT { new PhoneNumberRow(1, "1"), new PhoneNumberRow(1, "32234"), new PhoneNumberRow(1, "42343"), - new PhoneNumberRow(2, "432423") - ); + new PhoneNumberRow(2, "432423")); } private Set<PhoneNumberRow> getPhoneNumberRows() { @@ -449,7 +448,8 @@ class DataChangeIT { .collect(toSet()); } - private record PhoneNumberRow(long personId, String phoneNumber){} + private record PhoneNumberRow(long personId, String phoneNumber) { + } @Test void display_current_row_details_if_error_during_mass_update() throws Exception { diff --git a/server/sonar-main/src/test/java/org/sonar/application/config/AppSettingsLoaderImplTest.java b/server/sonar-main/src/test/java/org/sonar/application/config/AppSettingsLoaderImplTest.java index 2d48e5573f0..08fbdb58410 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/config/AppSettingsLoaderImplTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/config/AppSettingsLoaderImplTest.java @@ -113,7 +113,7 @@ public class AppSettingsLoaderImplTest { FileUtils.forceMkdir(propsFileAsDir); AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[0], homeDir, serviceLoaderWrapper); - assertThatThrownBy(() -> underTest.load()) + assertThatThrownBy(underTest::load) .isInstanceOf(IllegalStateException.class) .hasMessage("Cannot open file " + propsFileAsDir.getAbsolutePath()); } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/FieldAwareTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/FieldAwareTest.java index d1bc06593c4..6ad25b42567 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/FieldAwareTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/FieldAwareTest.java @@ -30,17 +30,11 @@ public class FieldAwareTest { @Test public void indexType_is_a_reserved_field_name_whatever_the_case() { - Stream<BiConsumer<TestFieldAware, String>> fieldSetters = Stream.of( - (testFieldAware, fieldName) -> testFieldAware.createBooleanField(fieldName), - (testFieldAware, fieldName) -> testFieldAware.createByteField(fieldName), - (testFieldAware, fieldName) -> testFieldAware.createDateTimeField(fieldName), - (testFieldAware, fieldName) -> testFieldAware.createDoubleField(fieldName), - (testFieldAware, fieldName) -> testFieldAware.createIntegerField(fieldName), - (testFieldAware, fieldName) -> testFieldAware.createLongField(fieldName), + Stream<BiConsumer<TestFieldAware, String>> fieldSetters = Stream.of(FieldAware::createBooleanField, FieldAware::createByteField, FieldAware::createDateTimeField, + FieldAware::createDoubleField, FieldAware::createIntegerField, FieldAware::createLongField, (testFieldAware, fieldName) -> testFieldAware.keywordFieldBuilder(fieldName).build(), (testFieldAware, fieldName) -> testFieldAware.textFieldBuilder(fieldName).build(), - (testFieldAware, fieldName) -> testFieldAware.nestedFieldBuilder(fieldName).addKeywordField("foo").build() - ); + (testFieldAware, fieldName) -> testFieldAware.nestedFieldBuilder(fieldName).addKeywordField("foo").build()); fieldSetters.forEach(c -> { TestFieldAware underTest = new TestFieldAware(); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewAuthorizedIndexTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewAuthorizedIndexTest.java index 1c020a1441a..aa8db3f90fc 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewAuthorizedIndexTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewAuthorizedIndexTest.java @@ -60,7 +60,7 @@ public class NewAuthorizedIndexTest { public void build_fails_if_no_relation_mapping_has_been_created() { NewAuthorizedIndex underTest = new NewAuthorizedIndex(someIndex, defaultSettingsConfiguration); - assertThatThrownBy(() -> underTest.build()) + assertThatThrownBy(underTest::build) .isInstanceOf(IllegalStateException.class) .hasMessage("At least one relation mapping must be defined"); } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewIndexTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewIndexTest.java index e8a2ee572b0..feb66de9819 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewIndexTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewIndexTest.java @@ -44,7 +44,6 @@ import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; @RunWith(DataProviderRunner.class) public class NewIndexTest { - private static final String SOME_INDEX_NAME = secure().nextAlphabetic(5).toLowerCase(); private final MapSettings settings = new MapSettings(); private final SettingsConfiguration defaultSettingsConfiguration = newBuilder(settings.asConfig()).build(); @@ -191,7 +190,7 @@ public class NewIndexTest { public void fail_when_nested_with_no_field(NewIndex<?> newIndex, TypeMapping typeMapping) { NestedFieldBuilder<TypeMapping> nestedFieldBuilder = typeMapping.nestedFieldBuilder("measures"); - assertThatThrownBy(() -> nestedFieldBuilder.build()) + assertThatThrownBy(nestedFieldBuilder::build) .isInstanceOf(IllegalArgumentException.class) .hasMessage("At least one sub-field must be declared in nested property 'measures'"); } @@ -307,7 +306,7 @@ public class NewIndexTest { SettingsConfiguration settingsConfiguration = newBuilder(settings.asConfig()).setDefaultNbOfShards(5).build(); IndexMainType mainType = IndexType.main(index, "foo"); - assertThatThrownBy(() -> new SimplestNewIndex(mainType, settingsConfiguration)) + assertThatThrownBy(() -> new SimplestNewIndex(mainType, settingsConfiguration)) .isInstanceOf(IllegalStateException.class) .hasMessage("The property 'sonar.search.replicas' is not an int value: For input string: \"ꝱꝲꝳପ\""); } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewRegularIndexTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewRegularIndexTest.java index dd3210cfb8a..dab38519db3 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewRegularIndexTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewRegularIndexTest.java @@ -44,7 +44,6 @@ import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; public class NewRegularIndexTest { private static final String SOME_INDEX_NAME = secure().nextAlphabetic(10).toLowerCase(Locale.ENGLISH); - private MapSettings settings = new MapSettings(); private SettingsConfiguration defaultSettingsConfiguration = newBuilder(settings.asConfig()).build(); @@ -53,7 +52,7 @@ public class NewRegularIndexTest { public void getMainType_fails_with_ISE_if_createTypeMapping_with_IndexMainType_has_not_been_called(Index index) { NewRegularIndex newIndex = new NewRegularIndex(index, defaultSettingsConfiguration); - assertThatThrownBy(() -> newIndex.getMainType()) + assertThatThrownBy(newIndex::getMainType) .isInstanceOf(IllegalStateException.class) .hasMessage("Main type has not been defined"); } @@ -88,7 +87,7 @@ public class NewRegularIndexTest { assertThatThrownBy(() -> underTest.createTypeMapping(IndexType.relation(IndexType.main(index, "donut"), "bar"))) .isInstanceOf(IllegalArgumentException.class) - .hasMessage("main type of relation must be "+ mainType); + .hasMessage("main type of relation must be " + mainType); } @Test @@ -96,7 +95,7 @@ public class NewRegularIndexTest { public void build_fails_with_ISE_if_no_mainType_is_defined(Index index) { NewRegularIndex underTest = new NewRegularIndex(index, defaultSettingsConfiguration); - assertThatThrownBy(() -> underTest.build()) + assertThatThrownBy(underTest::build) .isInstanceOf(IllegalStateException.class) .hasMessage("Mapping for main type must be defined"); } @@ -115,7 +114,7 @@ public class NewRegularIndexTest { NewRegularIndex underTest = new NewRegularIndex(index, defaultSettingsConfiguration); underTest.createTypeMapping(IndexType.main(index, "foo")); - assertThatThrownBy(() -> underTest.build()) + assertThatThrownBy(underTest::build) .isInstanceOf(IllegalStateException.class) .hasMessage("At least one relation must be defined when index accepts relations"); } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java index 2614352fdd5..1a837c2e461 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java @@ -54,7 +54,7 @@ public class AuthorizationDocTest { @Test public void projectUuidOf_fails_with_NPE_if_argument_is_null() { - assertThatThrownBy(() -> AuthorizationDoc.entityUuidOf(null)) + assertThatThrownBy(() -> AuthorizationDoc.entityUuidOf(null)) .isInstanceOf(NullPointerException.class); } @@ -85,7 +85,7 @@ public class AuthorizationDocTest { IndexType.IndexMainType mainType = IndexType.main(Index.simple("foo"), "bar"); AuthorizationDoc underTest = AuthorizationDoc.fromDto(mainType, dto); - assertThatThrownBy(() -> underTest.getId()) + assertThatThrownBy(underTest::getId) .isInstanceOf(NullPointerException.class) .hasMessage("entityUuid can't be null"); } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookCustomDnsTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookCustomDnsTest.java index d788f58b51b..f4716fa0bf4 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookCustomDnsTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookCustomDnsTest.java @@ -84,7 +84,7 @@ public class WebhookCustomDnsTest { Optional<InetAddress> inet6Address = Collections.list(NetworkInterface.getNetworkInterfaces()) .stream() .flatMap(ni -> Collections.list(ni.getInetAddresses()).stream()) - .filter(i -> i instanceof Inet6Address).findAny(); + .filter(Inet6Address.class::isInstance).findAny(); if (!inet6Address.isPresent()) { return; diff --git a/server/sonar-telemetry/src/it/java/org/sonar/telemetry/legacy/QualityProfileDataProviderIT.java b/server/sonar-telemetry/src/it/java/org/sonar/telemetry/legacy/QualityProfileDataProviderIT.java index f521c3cf7d4..3cd96a10039 100644 --- a/server/sonar-telemetry/src/it/java/org/sonar/telemetry/legacy/QualityProfileDataProviderIT.java +++ b/server/sonar-telemetry/src/it/java/org/sonar/telemetry/legacy/QualityProfileDataProviderIT.java @@ -51,8 +51,8 @@ public class QualityProfileDataProviderIT { QProfileDto qProfile1 = createQualityProfile(false, null); dbTester.qualityProfiles().setAsDefault(qProfile1); Assertions.assertThat(underTest.retrieveQualityProfilesData()) - .extracting(p -> p.uuid(), p -> p.isDefault(), p -> p.isBuiltIn(), p -> p.builtInParent(), - p -> p.rulesActivatedCount(), p -> p.rulesDeactivatedCount(), p -> p.rulesOverriddenCount()) + .extracting(TelemetryData.QualityProfile::uuid, TelemetryData.QualityProfile::isDefault, TelemetryData.QualityProfile::isBuiltIn, TelemetryData.QualityProfile::builtInParent, + TelemetryData.QualityProfile::rulesActivatedCount, TelemetryData.QualityProfile::rulesDeactivatedCount, TelemetryData.QualityProfile::rulesOverriddenCount) .containsExactlyInAnyOrder(tuple(qProfile1.getKee(), true, false, false, null, null, null)); } @@ -64,8 +64,8 @@ public class QualityProfileDataProviderIT { dbTester.qualityProfiles().setAsDefault(childProfile); Assertions.assertThat(underTest.retrieveQualityProfilesData()) - .extracting(p -> p.uuid(), p -> p.isDefault(), p -> p.isBuiltIn(), p -> p.builtInParent(), - p -> p.rulesActivatedCount(), p -> p.rulesDeactivatedCount(), p -> p.rulesOverriddenCount()) + .extracting(TelemetryData.QualityProfile::uuid, TelemetryData.QualityProfile::isDefault, TelemetryData.QualityProfile::isBuiltIn, TelemetryData.QualityProfile::builtInParent, + TelemetryData.QualityProfile::rulesActivatedCount, TelemetryData.QualityProfile::rulesDeactivatedCount, TelemetryData.QualityProfile::rulesOverriddenCount) .containsExactlyInAnyOrder( tuple(rootProfile.getKee(), false, false, false, null, null, null), tuple(childProfile.getKee(), true, false, false, null, null, null)); @@ -82,11 +82,10 @@ public class QualityProfileDataProviderIT { dbTester.qualityProfiles().associateWithProject(projectData.getProjectDto(), associatedProfile); Assertions.assertThat(underTest.retrieveQualityProfilesData()) - .extracting(p -> p.uuid(), p -> p.isDefault()) + .extracting(TelemetryData.QualityProfile::uuid, TelemetryData.QualityProfile::isDefault) .containsExactlyInAnyOrder( tuple(associatedProfile.getKee(), false), - tuple(unassociatedProfile.getKee(), false) - ); + tuple(unassociatedProfile.getKee(), false)); } @Test @@ -101,11 +100,10 @@ public class QualityProfileDataProviderIT { dbTester.qualityProfiles().setAsDefault(rootBuiltinProfile, childProfile, grandChildProfile); Assertions.assertThat(underTest.retrieveQualityProfilesData()) - .extracting(p -> p.uuid(), p -> p.isBuiltIn(), p -> p.builtInParent()) + .extracting(TelemetryData.QualityProfile::uuid, TelemetryData.QualityProfile::isBuiltIn, TelemetryData.QualityProfile::builtInParent) .containsExactlyInAnyOrder(tuple(rootBuiltinProfile.getKee(), true, null), tuple(childProfile.getKee(), false, true), - tuple(grandChildProfile.getKee(), false, true) - ); + tuple(grandChildProfile.getKee(), false, true)); } @Test @@ -122,11 +120,11 @@ public class QualityProfileDataProviderIT { dbTester.qualityProfiles().setAsDefault(childProfile); Assertions.assertThat(underTest.retrieveQualityProfilesData()) - .extracting(p -> p.uuid(), p -> p.rulesActivatedCount(), p -> p.rulesDeactivatedCount(), p -> p.rulesOverriddenCount()) + .extracting(TelemetryData.QualityProfile::uuid, TelemetryData.QualityProfile::rulesActivatedCount, TelemetryData.QualityProfile::rulesDeactivatedCount, + TelemetryData.QualityProfile::rulesOverriddenCount) .containsExactlyInAnyOrder( tuple(rootBuiltinProfile.getKee(), null, null, null), - tuple(childProfile.getKee(), 1, 1, 0) - ); + tuple(childProfile.getKee(), 1, 1, 0)); } @Test @@ -138,7 +136,6 @@ public class QualityProfileDataProviderIT { RuleDto rule = dbTester.rules().insert(); RuleParamDto initialRuleParam = dbTester.rules().insertRuleParam(rule, p -> p.setName("key").setDefaultValue("initial")); - ActiveRuleDto activeRuleDto = dbTester.qualityProfiles().activateRule(rootBuiltinProfile, rule); dbTester.getDbClient().activeRuleDao().insertParam(dbTester.getSession(), activeRuleDto, newParam(activeRuleDto, initialRuleParam, "key", "value")); @@ -150,7 +147,8 @@ public class QualityProfileDataProviderIT { dbTester.qualityProfiles().setAsDefault(childProfile); Assertions.assertThat(underTest.retrieveQualityProfilesData()) - .extracting(p -> p.uuid(), p -> p.rulesActivatedCount(), p -> p.rulesDeactivatedCount(), p -> p.rulesOverriddenCount()) + .extracting(TelemetryData.QualityProfile::uuid, TelemetryData.QualityProfile::rulesActivatedCount, TelemetryData.QualityProfile::rulesDeactivatedCount, + TelemetryData.QualityProfile::rulesOverriddenCount) .containsExactlyInAnyOrder( tuple(rootBuiltinProfile.getKee(), null, null, null), tuple(childProfile.getKee(), 0, 0, 1)); diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginJarLoaderTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginJarLoaderTest.java index c30b9cb4651..614159708c2 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginJarLoaderTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginJarLoaderTest.java @@ -36,8 +36,8 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.SonarRuntime; -import org.sonar.api.utils.MessageException; import org.sonar.api.testfixtures.log.LogTester; +import org.sonar.api.utils.MessageException; import org.sonar.core.platform.PluginInfo; import org.sonar.server.platform.ServerFileSystem; import org.sonar.updatecenter.common.PluginManifest; @@ -201,7 +201,7 @@ public class PluginJarLoaderTest { String dir = getDirName(fs.getInstalledExternalPluginsDir()); - assertThatThrownBy(() -> underTest.loadPlugins()) + assertThatThrownBy(underTest::loadPlugins) .isInstanceOf(MessageException.class) .hasMessageContaining("Found a plugin 'plugin1' in the directory '" + dir + "' with the same key [plugin1] as a built-in feature 'plugin1'. " + "Please remove '" + new File(dir, jar.getName()) + "'"); @@ -213,7 +213,7 @@ public class PluginJarLoaderTest { createJar(fs.getInstalledBundledPluginsDir(), "plugin1", "main", null); String dir = getDirName(fs.getDownloadedPluginsDir()); - assertThatThrownBy(() -> underTest.loadPlugins()) + assertThatThrownBy(underTest::loadPlugins) .isInstanceOf(MessageException.class) .hasMessage("Fail to update plugin: plugin1. Built-in feature with same key already exists: plugin1. " + "Move or delete plugin from " + dir + " directory"); @@ -226,7 +226,7 @@ public class PluginJarLoaderTest { String dir = getDirName(fs.getInstalledExternalPluginsDir()); - assertThatThrownBy(() -> underTest.loadPlugins()) + assertThatThrownBy(underTest::loadPlugins) .isInstanceOf(MessageException.class) .hasMessageContaining("Found two versions of the plugin 'plugin1' [plugin1] in the directory '" + dir + "'. Please remove ") .hasMessageContaining(jar2.getName()) @@ -239,7 +239,7 @@ public class PluginJarLoaderTest { File jar2 = createJar(fs.getInstalledBundledPluginsDir(), "plugin1", "main", null); String dir = getDirName(fs.getInstalledBundledPluginsDir()); - assertThatThrownBy(() -> underTest.loadPlugins()) + assertThatThrownBy(underTest::loadPlugins) .isInstanceOf(MessageException.class) .hasMessageContaining("Found two versions of the plugin plugin1 [plugin1] in the directory " + dir + ". Please remove one of ") .hasMessageContaining(jar2.getName()) @@ -250,7 +250,7 @@ public class PluginJarLoaderTest { public void fail_when_sqale_plugin_is_installed() throws Exception { copyTestPluginTo("fake-sqale-plugin", fs.getInstalledExternalPluginsDir()); - assertThatThrownBy(() -> underTest.loadPlugins()) + assertThatThrownBy(underTest::loadPlugins) .isInstanceOf(MessageException.class) .hasMessage("The following plugin is no longer compatible with this version of SonarQube: 'sqale'"); } @@ -261,7 +261,7 @@ public class PluginJarLoaderTest { createJar(fs.getInstalledExternalPluginsDir(), "scmgit", "main", null); createJar(fs.getInstalledExternalPluginsDir(), "scmsvn", "main", null); - assertThatThrownBy(() -> underTest.loadPlugins()) + assertThatThrownBy(underTest::loadPlugins) .isInstanceOf(MessageException.class) .hasMessage("The following plugins are no longer compatible with this version of SonarQube: 'scmgit', 'scmsvn', 'sqale'"); } @@ -270,7 +270,7 @@ public class PluginJarLoaderTest { public void fail_when_report_is_installed() throws Exception { copyTestPluginTo("fake-report-plugin", fs.getInstalledExternalPluginsDir()); - assertThatThrownBy(() -> underTest.loadPlugins()) + assertThatThrownBy(underTest::loadPlugins) .isInstanceOf(MessageException.class) .hasMessage("The following plugin is no longer compatible with this version of SonarQube: 'report'"); } @@ -279,7 +279,7 @@ public class PluginJarLoaderTest { public void fail_when_views_is_installed() throws Exception { copyTestPluginTo("fake-views-plugin", fs.getInstalledExternalPluginsDir()); - assertThatThrownBy(() -> underTest.loadPlugins()) + assertThatThrownBy(underTest::loadPlugins) .isInstanceOf(MessageException.class) .hasMessage("The following plugin is no longer compatible with this version of SonarQube: 'views'"); } @@ -289,7 +289,7 @@ public class PluginJarLoaderTest { when(sonarRuntime.getApiVersion()).thenReturn(org.sonar.api.utils.Version.parse("1.0")); copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir()); - assertThatThrownBy(() -> underTest.loadPlugins()) + assertThatThrownBy(underTest::loadPlugins) .hasMessage("Plugin Base Plugin [testbase] requires at least Sonar Plugin API version 4.5.4 (current: 1.0)"); } diff --git a/server/sonar-webserver-common/src/it/java/org/sonar/server/common/user/service/UserServiceIT.java b/server/sonar-webserver-common/src/it/java/org/sonar/server/common/user/service/UserServiceIT.java index 14233509ae1..3a3f0137cfa 100644 --- a/server/sonar-webserver-common/src/it/java/org/sonar/server/common/user/service/UserServiceIT.java +++ b/server/sonar-webserver-common/src/it/java/org/sonar/server/common/user/service/UserServiceIT.java @@ -113,7 +113,8 @@ public class UserServiceIT { settings.asConfig(), new NoOpAuditPersister(), localAuthentication); private final IdentityProviderRepository identityProviderRepository = mock(); - private final UserService userService = new UserService(db.getDbClient(), new AvatarResolverImpl(), managedInstanceService, managedInstanceChecker, userDeactivator, userUpdater, identityProviderRepository); + private final UserService userService = new UserService(db.getDbClient(), new AvatarResolverImpl(), managedInstanceService, managedInstanceChecker, userDeactivator, userUpdater, + identityProviderRepository); @Before public void setUp() { @@ -844,9 +845,10 @@ public class UserServiceIT { assertThat(updatedUser.getExternalId()).isEqualTo("prov_id"); assertThat(updatedUser.getExternalLogin()).isEqualTo("prov_login"); } + @DataProvider public static Object[][] updateUserProvider() { - return new Object[][]{ + return new Object[][] { {new UpdateUser().setName("new name")}, {new UpdateUser().setEmail("newEmail@test.com")}, {new UpdateUser().setName("new name").setEmail("newEmail@test.com")}}; @@ -882,14 +884,12 @@ public class UserServiceIT { } private void mockUsersAsManaged(String... userUuids) { - when(managedInstanceService.getUserUuidToManaged(any(), any())).thenAnswer(invocation -> - { - Set<?> allUsersUuids = invocation.getArgument(1, Set.class); - return allUsersUuids.stream() - .map(userUuid -> (String) userUuid) - .collect(toMap(identity(), userUuid -> Set.of(userUuids).contains(userUuid))); - } - ); + when(managedInstanceService.getUserUuidToManaged(any(), any())).thenAnswer(invocation -> { + Set<?> allUsersUuids = invocation.getArgument(1, Set.class); + return allUsersUuids.stream() + .map(String.class::cast) + .collect(toMap(identity(), userUuid -> Set.of(userUuids).contains(userUuid))); + }); } private static UsersSearchRequest.Builder getBuilderWithDefaultsPageSize() { diff --git a/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/GlobalInfoLoader.java b/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/GlobalInfoLoader.java index c1a42aa3cac..2ca4a984087 100644 --- a/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/GlobalInfoLoader.java +++ b/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/GlobalInfoLoader.java @@ -32,7 +32,7 @@ public class GlobalInfoLoader { public GlobalInfoLoader(SystemInfoSection[] sections) { this.globalSections = Arrays.stream(sections) - .filter(section -> section instanceof Global) + .filter(Global.class::isInstance) .toList(); } diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/search/BaseDocTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/search/BaseDocTest.java index eec916c6b7c..fff0a6c8f30 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/search/BaseDocTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/search/BaseDocTest.java @@ -37,7 +37,6 @@ import static org.junit.Assert.fail; public class BaseDocTest { private final IndexType.IndexMainType someType = IndexType.main(Index.simple("bar"), "donut"); - @Test public void getField() { Map<String, Object> fields = new HashMap<>(); @@ -125,7 +124,7 @@ public class BaseDocTest { }; - assertThatThrownBy(() -> doc.getFields()) + assertThatThrownBy(doc::getFields) .isInstanceOf(IllegalStateException.class) .hasMessage("parent must be set on a doc associated to a IndexRelationType (see BaseDoc#setParent(String))"); } diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexSearchTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexSearchTest.java index b920a74b835..4751ee4cdbf 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexSearchTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexSearchTest.java @@ -24,10 +24,10 @@ import java.util.List; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.sonar.db.component.ComponentQualifiers; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; +import org.sonar.db.component.ComponentQualifiers; import org.sonar.db.component.ProjectData; import org.sonar.db.entity.EntityDto; import org.sonar.db.project.ProjectDto; @@ -110,7 +110,7 @@ public class ComponentIndexSearchTest { List<ProjectData> projects = IntStream.range(0, 9) .mapToObj(i -> db.components().insertPrivateProject(p -> p.setName("project " + i))) .toList(); - ProjectDto[] projectDtos = projects.stream().map(p -> p.getProjectDto()).toArray(ProjectDto[]::new); + ProjectDto[] projectDtos = projects.stream().map(ProjectData::getProjectDto).toArray(ProjectDto[]::new); index(projectDtos); SearchIdResult<String> result = underTest.search(ComponentQuery.builder().build(), new SearchOptions().setPage(2, 3)); diff --git a/server/sonar-webserver-webapi-v2/src/test/java/org/sonar/server/v2/api/rule/converter/RuleRestResponseGeneratorTest.java b/server/sonar-webserver-webapi-v2/src/test/java/org/sonar/server/v2/api/rule/converter/RuleRestResponseGeneratorTest.java index 76f5b1edfa5..ee5343bb765 100644 --- a/server/sonar-webserver-webapi-v2/src/test/java/org/sonar/server/v2/api/rule/converter/RuleRestResponseGeneratorTest.java +++ b/server/sonar-webserver-webapi-v2/src/test/java/org/sonar/server/v2/api/rule/converter/RuleRestResponseGeneratorTest.java @@ -43,6 +43,8 @@ import org.sonar.server.common.rule.service.RuleInformation; import org.sonar.server.common.text.MacroInterpreter; import org.sonar.server.language.LanguageTesting; import org.sonar.server.rule.RuleDescriptionFormatter; +import org.sonar.server.v2.api.rule.resource.Parameter; +import org.sonar.server.v2.api.rule.response.RuleDescriptionSectionRestResponse; import org.sonar.server.v2.api.rule.response.RuleRestResponse; import static org.assertj.core.api.Assertions.assertThat; @@ -64,7 +66,6 @@ public class RuleRestResponseGeneratorTest { @InjectMocks private RuleRestResponseGenerator ruleRestResponseGenerator; - @Test public void toRuleRestResponse_shouldReturnSameFieldForStandardMapping() { when(macroInterpreter.interpret(Mockito.anyString())).thenAnswer(invocation -> "interpreted" + invocation.getArgument(0)); @@ -78,7 +79,8 @@ public class RuleRestResponseGeneratorTest { assertThat(ruleRestResponse.key()).isEqualTo(dto.getKey().toString()); assertThat(ruleRestResponse.repositoryKey()).isEqualTo(dto.getRepositoryKey()); assertThat(ruleRestResponse.name()).isEqualTo(dto.getName()); - assertThat(ruleRestResponse.descriptionSections()).extracting(s -> s.key(), s -> s.content(), s -> s.context()) + assertThat(ruleRestResponse.descriptionSections()) + .extracting(RuleDescriptionSectionRestResponse::key, RuleDescriptionSectionRestResponse::content, RuleDescriptionSectionRestResponse::context) .containsExactly(dto.getRuleDescriptionSectionDtos().stream().map(s -> tuple(s.getKey(), "interpreted" + "html" + s.getContent(), s.getContext())).toArray(Tuple[]::new)); assertThat(ruleRestResponse.severity()).isEqualTo(dto.getSeverityString()); assertThat(ruleRestResponse.type().name()).isEqualTo(RuleType.valueOf(dto.getType()).name()); @@ -123,7 +125,7 @@ public class RuleRestResponseGeneratorTest { RuleParamDto ruleParamDto2 = RuleTesting.newRuleParam(dto); RuleRestResponse ruleRestResponse = ruleRestResponseGenerator.toRuleRestResponse(new RuleInformation(dto, List.of(ruleParamDto1, ruleParamDto2))); - assertThat(ruleRestResponse.parameters()).extracting(p -> p.key(), p -> p.htmlDescription(), p -> p.defaultValue()) + assertThat(ruleRestResponse.parameters()).extracting(Parameter::key, Parameter::htmlDescription, Parameter::defaultValue) .containsExactlyInAnyOrder(tuple(ruleParamDto1.getName(), ruleParamDto1.getDescription(), ruleParamDto1.getDefaultValue()), tuple(ruleParamDto2.getName(), ruleParamDto2.getDescription(), ruleParamDto2.getDefaultValue())); } @@ -140,7 +142,8 @@ public class RuleRestResponseGeneratorTest { RuleRestResponse ruleRestResponse = ruleRestResponseGenerator.toRuleRestResponse(new RuleInformation(dto, List.of())); assertThat(ruleRestResponse.name()).isEqualTo(dto.getAdHocName()); - assertThat(ruleRestResponse.descriptionSections()).extracting(r -> r.key(), r -> r.content(), r -> r.context()) + assertThat(ruleRestResponse.descriptionSections()) + .extracting(RuleDescriptionSectionRestResponse::key, RuleDescriptionSectionRestResponse::content, RuleDescriptionSectionRestResponse::context) .containsExactly(tuple("default", "interpreted" + dto.getAdHocDescription(), null)); assertThat(ruleRestResponse.severity()).isEqualTo(dto.getAdHocSeverity()); assertThat(ruleRestResponse.type().name()).isEqualTo(RuleType.valueOf(dto.getAdHocType()).name()); @@ -158,7 +161,8 @@ public class RuleRestResponseGeneratorTest { RuleRestResponse ruleRestResponse = ruleRestResponseGenerator.toRuleRestResponse(new RuleInformation(dto, List.of())); assertThat(ruleRestResponse.name()).isEqualTo(dto.getAdHocName()); - assertThat(ruleRestResponse.descriptionSections()).extracting(r -> r.key(), r -> r.content(), r -> r.context()) + assertThat(ruleRestResponse.descriptionSections()) + .extracting(RuleDescriptionSectionRestResponse::key, RuleDescriptionSectionRestResponse::content, RuleDescriptionSectionRestResponse::context) .containsExactly(tuple("default", "interpreted" + dto.getAdHocDescription(), null)); assertThat(ruleRestResponse.severity()).isEqualTo(dto.getAdHocSeverity()); assertThat(ruleRestResponse.type().name()).isEqualTo(RuleType.valueOf(dto.getAdHocType()).name()); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateAzureActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateAzureActionIT.java index b62a28310d8..d8b03bd98d1 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateAzureActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateAzureActionIT.java @@ -119,7 +119,7 @@ public class UpdateAzureActionIT { .setParam("key", almSettingDto.getKey()) .setParam("url", AZURE_URL); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Please provide the Personal Access Token to update the URL."); } @@ -134,8 +134,8 @@ public class UpdateAzureActionIT { .setParam("personalAccessToken", "0123456789") .setParam("url", AZURE_URL) .execute()) - .isInstanceOf(NotFoundException.class) - .hasMessageContaining("DevOps Platform setting with key 'unknown' cannot be found"); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("DevOps Platform setting with key 'unknown' cannot be found"); } @Test @@ -151,8 +151,8 @@ public class UpdateAzureActionIT { .setParam("personalAccessToken", "0123456789") .setParam("url", AZURE_URL) .execute()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining(format("An DevOps Platform setting with key '%s' already exists", almSetting2.getKey())); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(format("An DevOps Platform setting with key '%s' already exists", almSetting2.getKey())); } @Test @@ -166,7 +166,7 @@ public class UpdateAzureActionIT { .setParam("newKey", "Azure Server - Infra Team") .setParam("personalAccessToken", "0123456789") .execute()) - .isInstanceOf(ForbiddenException.class); + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateBitbucketActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateBitbucketActionIT.java index 880d49735f6..e2c50940ff6 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateBitbucketActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateBitbucketActionIT.java @@ -99,7 +99,7 @@ public class UpdateBitbucketActionIT { .setParam("key", almSettingDto.getKey()) .setParam("url", "https://bitbucket.enterprise-unicorn.com"); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Please provide the Personal Access Token to update the URL."); } @@ -126,14 +126,14 @@ public class UpdateBitbucketActionIT { public void fail_when_key_does_not_match_existing_alm_setting() { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); - + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "unknown") .setParam("url", "https://bitbucket.enterprise-unicorn.com") .setParam("personalAccessToken", "0123456789") .execute()) - .isInstanceOf(NotFoundException.class) - .hasMessageContaining("DevOps Platform setting with key 'unknown' cannot be found"); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("DevOps Platform setting with key 'unknown' cannot be found"); } @Test @@ -149,8 +149,8 @@ public class UpdateBitbucketActionIT { .setParam("url", "https://bitbucket.enterprise-unicorn.com") .setParam("personalAccessToken", "0123456789") .execute()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining(format("An DevOps Platform setting with key '%s' already exists", almSetting2.getKey())); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(format("An DevOps Platform setting with key '%s' already exists", almSetting2.getKey())); } @Test @@ -165,7 +165,7 @@ public class UpdateBitbucketActionIT { .setParam("url", "https://bitbucket.enterprise-unicorn.com") .setParam("personalAccessToken", "0123456789") .execute()) - .isInstanceOf(ForbiddenException.class); + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateGitlabActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateGitlabActionIT.java index c476992d6ae..40d8213ec69 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateGitlabActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateGitlabActionIT.java @@ -124,7 +124,7 @@ public class UpdateGitlabActionIT { .setParam("key", almSettingDto.getKey()) .setParam("url", GITLAB_URL); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Please provide the Personal Access Token to update the URL."); } @@ -139,8 +139,8 @@ public class UpdateGitlabActionIT { .setParam("personalAccessToken", "0123456789") .setParam("url", GITLAB_URL) .execute()) - .isInstanceOf(NotFoundException.class) - .hasMessageContaining("DevOps Platform setting with key 'unknown' cannot be found"); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("DevOps Platform setting with key 'unknown' cannot be found"); } @Test @@ -156,8 +156,8 @@ public class UpdateGitlabActionIT { .setParam("personalAccessToken", "0123456789") .setParam("url", GITLAB_URL) .execute()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining(format("An DevOps Platform setting with key '%s' already exists", almSetting2.getKey())); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(format("An DevOps Platform setting with key '%s' already exists", almSetting2.getKey())); } @Test @@ -172,7 +172,7 @@ public class UpdateGitlabActionIT { .setParam("personalAccessToken", "0123456789") .setParam("url", GITLAB_URL) .execute()) - .isInstanceOf(ForbiddenException.class); + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/SearchActionComponentsIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/SearchActionComponentsIT.java index e5d63e074de..462d716dc40 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/SearchActionComponentsIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/SearchActionComponentsIT.java @@ -27,13 +27,13 @@ import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.Mockito; import org.sonar.api.config.Configuration; import org.sonar.api.resources.Languages; -import org.sonar.db.component.ComponentQualifiers; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.Durations; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; +import org.sonar.db.component.ComponentQualifiers; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ProjectData; import org.sonar.db.issue.IssueDto; @@ -64,7 +64,6 @@ import org.sonarqube.ws.Issues.SearchWsResponse; import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; -import static org.sonar.db.component.ComponentQualifiers.APP; import static org.sonar.api.utils.DateUtils.addDays; import static org.sonar.api.utils.DateUtils.parseDateTime; import static org.sonar.api.web.UserRole.USER; @@ -73,6 +72,7 @@ import static org.sonar.core.util.Uuids.UUID_EXAMPLE_02; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; import static org.sonar.db.component.BranchType.BRANCH; import static org.sonar.db.component.BranchType.PULL_REQUEST; +import static org.sonar.db.component.ComponentQualifiers.APP; import static org.sonar.db.component.ComponentTesting.newDirectory; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.component.ComponentTesting.newProjectCopy; @@ -92,7 +92,7 @@ class SearchActionComponentsIT { private final DbTester db = DbTester.create(); @RegisterExtension private final EsTester es = EsTester.create(); - + private final Configuration config = Mockito.mock(Configuration.class); private final DbClient dbClient = db.getDbClient(); @@ -709,17 +709,17 @@ class SearchActionComponentsIT { private void allowAnyoneOnProjects(ProjectDto... projects) { userSession.registerProjects(projects); - Arrays.stream(projects).forEach(p -> permissionIndexer.allowOnlyAnyone(p)); + Arrays.stream(projects).forEach(permissionIndexer::allowOnlyAnyone); } private void allowAnyoneOnPortfolios(ComponentDto... portfolios) { userSession.registerPortfolios(portfolios); - Arrays.stream(portfolios).forEach(p -> permissionIndexer.allowOnlyAnyone(p)); + Arrays.stream(portfolios).forEach(permissionIndexer::allowOnlyAnyone); } private void allowAnyoneOnApplication(ProjectDto application, ProjectDto... projects) { userSession.registerApplication(application); - Arrays.stream(projects).forEach(p -> permissionIndexer.allowOnlyAnyone(p)); + Arrays.stream(projects).forEach(permissionIndexer::allowOnlyAnyone); } private void indexIssues() { diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/measure/ws/ComponentTreeActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/measure/ws/ComponentTreeActionIT.java index 0fa15ae84a1..22b94dd1281 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/measure/ws/ComponentTreeActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/measure/ws/ComponentTreeActionIT.java @@ -1192,7 +1192,7 @@ class ComponentTreeActionIT { .setParam(PARAM_QUALIFIERS, "BRC") .setParam(PARAM_METRIC_KEYS, complexity.getKey()); - assertThatThrownBy(() -> testRequest.execute()).isInstanceOf(IllegalArgumentException.class) + assertThatThrownBy(testRequest::execute).isInstanceOf(IllegalArgumentException.class) .hasMessage("Value of parameter 'qualifiers' (BRC) must be one of: [UTS, FIL, DIR, TRK]"); } diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/ws/SetActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/ws/SetActionIT.java index e65d4c42860..2a89605770e 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/ws/SetActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/ws/SetActionIT.java @@ -43,7 +43,6 @@ import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.component.SnapshotDto; import org.sonar.db.newcodeperiod.NewCodePeriodDao; -import org.sonar.db.newcodeperiod.NewCodePeriodDbTester; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.db.project.ProjectDto; @@ -132,8 +131,8 @@ public class SetActionIT { .setParam("project", project.getKey()) .setParam("type", "specific_analysis") .execute()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Invalid type 'SPECIFIC_ANALYSIS'. Projects can only be set with types: [PREVIOUS_VERSION, NUMBER_OF_DAYS, REFERENCE_BRANCH]"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid type 'SPECIFIC_ANALYSIS'. Projects can only be set with types: [PREVIOUS_VERSION, NUMBER_OF_DAYS, REFERENCE_BRANCH]"); } @Test @@ -146,8 +145,8 @@ public class SetActionIT { .setParam("branch", DEFAULT_MAIN_BRANCH_NAME) .setParam("type", "number_of_days") .execute()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("New code definition type 'NUMBER_OF_DAYS' requires a value"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("New code definition type 'NUMBER_OF_DAYS' requires a value"); } @Test @@ -160,8 +159,8 @@ public class SetActionIT { .setParam("type", "specific_analysis") .setParam("branch", DEFAULT_MAIN_BRANCH_NAME) .execute()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("New code definition type 'SPECIFIC_ANALYSIS' requires a value"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("New code definition type 'SPECIFIC_ANALYSIS' requires a value"); } @Test @@ -175,8 +174,8 @@ public class SetActionIT { .setParam("branch", DEFAULT_MAIN_BRANCH_NAME) .setParam("value", "unknown") .execute()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Failed to parse number of days: unknown"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Failed to parse number of days: unknown"); } @Test @@ -189,8 +188,7 @@ public class SetActionIT { .setParam("type", "number_of_days") .setParam("branch", DEFAULT_MAIN_BRANCH_NAME) .setParam("value", "92"); - assertThatThrownBy(() -> request - .execute()) + assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Failed to set the New Code Definition. The given value is not compatible with the Clean as You Code methodology. " + "Please refer to the documentation for compliant options."); @@ -221,8 +219,8 @@ public class SetActionIT { .setParam("branch", DEFAULT_MAIN_BRANCH_NAME) .setParam("value", "unknown") .execute()) - .isInstanceOf(NotFoundException.class) - .hasMessageContaining("Analysis 'unknown' is not found"); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Analysis 'unknown' is not found"); } @Test @@ -242,9 +240,9 @@ public class SetActionIT { .setParam("branch", DEFAULT_MAIN_BRANCH_NAME) .setParam("value", analysisBranch.getUuid()) .execute()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Analysis '" + analysisBranch.getUuid() + "' does not belong to branch '" + DEFAULT_MAIN_BRANCH_NAME + - "' of project '" + project.getKey() + "'"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Analysis '" + analysisBranch.getUuid() + "' does not belong to branch '" + DEFAULT_MAIN_BRANCH_NAME + + "' of project '" + project.getKey() + "'"); } // validation of project/branch @@ -253,8 +251,8 @@ public class SetActionIT { assertThatThrownBy(() -> ws.newRequest() .setParam("branch", "branch") .execute()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("If branch key is specified, project key needs to be specified too"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("If branch key is specified, project key needs to be specified too"); } @Test @@ -263,8 +261,8 @@ public class SetActionIT { .setParam("type", "previous_version") .setParam("project", "unknown") .execute()) - .isInstanceOf(NotFoundException.class) - .hasMessageContaining("Project 'unknown' not found"); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project 'unknown' not found"); } @Test @@ -277,8 +275,8 @@ public class SetActionIT { .setParam("type", "previous_version") .setParam("branch", "unknown") .execute()) - .isInstanceOf(NotFoundException.class) - .hasMessageContaining("Branch 'unknown' in project '" + project.getKey() + "' not found"); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Branch 'unknown' in project '" + project.getKey() + "' not found"); } // permission @@ -290,8 +288,8 @@ public class SetActionIT { .setParam("project", project.getKey()) .setParam("type", "previous_version") .execute()) - .isInstanceOf(ForbiddenException.class) - .hasMessageContaining("Insufficient privileges"); + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test @@ -299,8 +297,8 @@ public class SetActionIT { assertThatThrownBy(() -> ws.newRequest() .setParam("type", "previous_version") .execute()) - .isInstanceOf(ForbiddenException.class) - .hasMessageContaining("Insufficient privileges"); + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } // success cases diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/ws/UnsetActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/ws/UnsetActionIT.java index bb7a5a75581..bec4270a046 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/ws/UnsetActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/ws/UnsetActionIT.java @@ -68,7 +68,7 @@ public class UnsetActionIT { private WsActionTester ws; @Before - public void setup(){ + public void setup() { when(documentationLinkGenerator.getDocumentationLink(any())).thenReturn("https://docs.sonarsource.com/someddoc"); ws = new WsActionTester(new UnsetAction(dbClient, userSession, componentFinder, editionProvider, dao, documentationLinkGenerator)); } @@ -95,7 +95,7 @@ public class UnsetActionIT { TestRequest request = ws.newRequest() .setParam("branch", "branch"); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("If branch key is specified, project key needs to be specified too"); } @@ -106,8 +106,8 @@ public class UnsetActionIT { .setParam("type", "previous_version") .setParam("project", "unknown") .execute()) - .isInstanceOf(NotFoundException.class) - .hasMessageContaining("Project 'unknown' not found"); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project 'unknown' not found"); } @Test @@ -120,8 +120,8 @@ public class UnsetActionIT { .setParam("type", "previous_version") .setParam("branch", "unknown") .execute()) - .isInstanceOf(NotFoundException.class) - .hasMessageContaining("Branch 'unknown' in project '" + project.getKey() + "' not found"); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Branch 'unknown' in project '" + project.getKey() + "' not found"); } // permission @@ -133,8 +133,8 @@ public class UnsetActionIT { .setParam("project", project.getKey()) .setParam("type", "previous_version") .execute()) - .isInstanceOf(ForbiddenException.class) - .hasMessageContaining("Insufficient privileges"); + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test @@ -142,8 +142,8 @@ public class UnsetActionIT { assertThatThrownBy(() -> ws.newRequest() .setParam("type", "previous_version") .execute()) - .isInstanceOf(ForbiddenException.class) - .hasMessageContaining("Insufficient privileges"); + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } // success cases @@ -236,7 +236,7 @@ public class UnsetActionIT { .setParam("branch", "branch"); logInAsProjectAdministrator(project); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Failed to unset the New Code Definition. Your project " + "New Code Definition is not compatible with the Clean as You Code methodology. Please update your project New Code Definition"); @@ -255,7 +255,7 @@ public class UnsetActionIT { .setParam("branch", "branch"); logInAsProjectAdministrator(project); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Failed to unset the New Code Definition. Your instance " + "New Code Definition is not compatible with the Clean as You Code methodology. Please update your instance New Code Definition"); @@ -271,7 +271,7 @@ public class UnsetActionIT { TestRequest request = ws.newRequest() .setParam("project", project.getKey()); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Failed to unset the New Code Definition. Your instance " + "New Code Definition is not compatible with the Clean as You Code methodology. Please update your instance New Code Definition"); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/CopyActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/CopyActionIT.java index f13c6647947..8bdf03e35f3 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/CopyActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/CopyActionIT.java @@ -147,7 +147,7 @@ public class CopyActionIT { .setParam(PARAM_SOURCE_NAME, qualityGate.getName()) .setParam(PARAM_NAME, "new-name") .execute()) - .isInstanceOf(ForbiddenException.class); + .isInstanceOf(ForbiddenException.class); } @Test @@ -157,8 +157,8 @@ public class CopyActionIT { assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_NAME, "new-name") .execute()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("The 'sourceName' parameter is missing"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'sourceName' parameter is missing"); } @Test @@ -169,8 +169,8 @@ public class CopyActionIT { .setParam(PARAM_SOURCE_NAME, "unknown") .setParam(PARAM_NAME, "new-name") .execute()) - .isInstanceOf(NotFoundException.class) - .hasMessageContaining("No quality gate has been found for name unknown"); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("No quality gate has been found for name unknown"); } @Test @@ -183,14 +183,14 @@ public class CopyActionIT { .setParam(PARAM_SOURCE_NAME, qualityGate.getName()); ofNullable(nameParameter).ifPresent(t -> request.setParam(PARAM_NAME, t)); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The 'name' parameter is missing"); } @DataProvider public static Object[][] nullOrEmpty() { - return new Object[][]{ + return new Object[][] { {null}, {""}, {" "} @@ -207,7 +207,7 @@ public class CopyActionIT { .setParam(PARAM_SOURCE_NAME, qualityGate.getName()) .setParam(PARAM_NAME, existingQualityGate.getName()) .execute()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Name has already been taken"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Name has already been taken"); } } diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/CreateActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/CreateActionIT.java index 227157807ba..9589c94c873 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/CreateActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/CreateActionIT.java @@ -131,7 +131,7 @@ public class CreateActionIT { TestRequest request = ws.newRequest(); Optional.ofNullable(nameParameter).ifPresent(t -> request.setParam(PARAM_NAME, "")); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The 'name' parameter is missing"); } diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRuleActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRuleActionIT.java index e13a7d15b66..f317eeaff4d 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRuleActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRuleActionIT.java @@ -100,7 +100,7 @@ class ActivateRuleActionIT { .setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString()) .setParam(PARAM_KEY, secure().nextAlphanumeric(UUID_SIZE)); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); } @@ -113,7 +113,7 @@ class ActivateRuleActionIT { .setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString()) .setParam(PARAM_KEY, qualityProfile.getKee()); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class); } @@ -128,7 +128,7 @@ class ActivateRuleActionIT { .setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString()) .setParam(PARAM_KEY, qualityProfile.getKee()); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Operation forbidden for built-in Quality Profile 'Xoo profile' with language 'xoo'"); } @@ -144,7 +144,7 @@ class ActivateRuleActionIT { .setParam(PARAM_RULE, rule.getKey().toString()) .setParam(PARAM_KEY, qualityProfile.getKee()); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage(String.format("Operation forbidden for rule '%s' imported from an external rule engine.", rule.getKey())); } @@ -162,7 +162,7 @@ class ActivateRuleActionIT { .setParam(PARAM_SEVERITY, "BLOCKER") .setParam(PARAM_IMPACTS, "MAINTAINABILITY=BLOCKER"); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage("'severity' and 'impacts' parameters can't be provided both at the same time"); } @@ -179,7 +179,7 @@ class ActivateRuleActionIT { .setParam(PARAM_KEY, qualityProfile.getKee()) .setParam(PARAM_IMPACTS, "MAINTAINABILITY=UNKNOWN_SEVERITY"); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Unexpected value for parameter 'impacts': MAINTAINABILITY=UNKNOWN_SEVERITY"); } @@ -198,7 +198,7 @@ class ActivateRuleActionIT { .setParam(PARAM_KEY, qualityProfile.getKee()) .setParam(PARAM_IMPACTS, "MAINTAINABILITY=BLOCKER;SECURITY=MEDIUM"); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Only impacts defined on the rule can be overridden. (MAINTAINABILITY)"); } diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRulesActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRulesActionIT.java index 4cbf8dd889d..3382d28c636 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRulesActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRulesActionIT.java @@ -19,7 +19,6 @@ */ package org.sonar.server.qualityprofile.ws; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.Mockito; @@ -136,7 +135,7 @@ class ActivateRulesActionIT { .setMethod("POST") .setParam(PARAM_TARGET_KEY, secure().nextAlphanumeric(UUID_SIZE)); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); } @@ -148,7 +147,7 @@ class ActivateRulesActionIT { .setMethod("POST") .setParam(PARAM_TARGET_KEY, qualityProfile.getKee()); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class); } diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionIT.java index e950a21bab8..7362e8b78b8 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionIT.java @@ -140,7 +140,7 @@ public class DeactivateRuleActionIT { .setParam(PARAM_RULE, rule.getKey().toString()) .setParam(PARAM_KEY, qualityProfile.getKee()); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage(String.format("Operation forbidden for rule '%s' imported from an external rule engine.", rule.getKey())); } diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/CheckSecretKeyActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/CheckSecretKeyActionIT.java index f9560146990..428a573b6d1 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/CheckSecretKeyActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/CheckSecretKeyActionIT.java @@ -88,7 +88,7 @@ public class CheckSecretKeyActionIT { public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - assertThatThrownBy(() -> call()) + assertThatThrownBy(this::call) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/GenerateSecretKeyActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/GenerateSecretKeyActionIT.java index 826d2f7fcf7..87a5044603e 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/GenerateSecretKeyActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/GenerateSecretKeyActionIT.java @@ -83,12 +83,11 @@ public class GenerateSecretKeyActionIT { public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - assertThatThrownBy(() -> call()) + assertThatThrownBy(this::call) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } - private GenerateSecretKeyWsResponse call() { return ws.newRequest() .setMethod("GET") diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/ResetActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/ResetActionIT.java index 6824bee5de7..4b07ab5483e 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/ResetActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/ResetActionIT.java @@ -54,10 +54,10 @@ import static java.lang.String.format; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.sonar.db.component.ComponentQualifiers.PROJECT; -import static org.sonar.db.component.ComponentQualifiers.VIEW; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.USER; +import static org.sonar.db.component.ComponentQualifiers.PROJECT; +import static org.sonar.db.component.ComponentQualifiers.VIEW; import static org.sonar.db.property.PropertyTesting.newComponentPropertyDto; import static org.sonar.db.property.PropertyTesting.newGlobalPropertyDto; import static org.sonar.db.property.PropertyTesting.newUserPropertyDto; @@ -303,7 +303,7 @@ public class ResetActionIT { .setParam("keys", "foo") .setParam("component", "unknown"); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("Component key 'unknown' not found"); } @@ -317,7 +317,7 @@ public class ResetActionIT { TestRequest request = ws.newRequest() .setParam("keys", settingKey) .setParam("component", project.getKey()); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage(format("Setting '%s' can only be used in sonar.properties", settingKey)); } @@ -392,9 +392,9 @@ public class ResetActionIT { private void assertUserPropertyExists(String key, UserDto user) { assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() - .setKey(key) - .setUserUuid(user.getUuid()) - .build(), + .setKey(key) + .setUserUuid(user.getUuid()) + .build(), dbSession)).isNotEmpty(); } diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/LinesActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/LinesActionIT.java index fea1aa3d69b..f10046d3680 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/LinesActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/LinesActionIT.java @@ -102,7 +102,7 @@ public class LinesActionIT { TestRequest request = tester.newRequest() .setParam("uuid", file.uuid()); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class); } @@ -319,8 +319,8 @@ public class LinesActionIT { .setParam("key", file.getKey()) .setParam("branch", "another_branch") .execute()) - .isInstanceOf(NotFoundException.class) - .hasMessageContaining(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch")); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch")); } @Test @@ -334,8 +334,8 @@ public class LinesActionIT { .setParam("uuid", file.uuid()) .setParam("branch", "another_branch") .execute()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Parameter 'uuid' cannot be used at the same time as 'branch' or 'pullRequest'"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Parameter 'uuid' cannot be used at the same time as 'branch' or 'pullRequest'"); } @Test @@ -347,8 +347,8 @@ public class LinesActionIT { assertThatThrownBy(() -> tester.newRequest() .setParam("uuid", branch.getUuid()) .execute()) - .isInstanceOf(NotFoundException.class) - .hasMessageContaining(format("Component id '%s' not found", branch.getUuid())); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Component id '%s' not found", branch.getUuid())); } @Test diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ui/ws/MarketplaceActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ui/ws/MarketplaceActionIT.java index 97f71ebb8df..63265c04cbb 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ui/ws/MarketplaceActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ui/ws/MarketplaceActionIT.java @@ -72,7 +72,7 @@ public class MarketplaceActionIT { userSessionRule.anonymous(); TestRequest request = ws.newRequest(); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class) .hasMessageContaining("Authentication is required"); } @@ -82,7 +82,7 @@ public class MarketplaceActionIT { userSessionRule.logIn(); TestRequest request = ws.newRequest(); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/CreateActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/CreateActionIT.java index 88c1a1766c2..e54c8e38864 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/CreateActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/CreateActionIT.java @@ -80,7 +80,8 @@ public class CreateActionIT { private final ManagedInstanceService managedInstanceService = mock(ManagedInstanceService.class); private final IdentityProviderRepository identityProviderRepository = mock(); private final UserService userService = new UserService(db.getDbClient(), new AvatarResolverImpl(), managedInstanceService, managedInstanceChecker, mock(UserDeactivator.class), - new UserUpdater(mock(NewUserNotifier.class), db.getDbClient(), new DefaultGroupFinder(db.getDbClient()), settings.asConfig(), new NoOpAuditPersister(), localAuthentication), identityProviderRepository); + new UserUpdater(mock(NewUserNotifier.class), db.getDbClient(), new DefaultGroupFinder(db.getDbClient()), settings.asConfig(), new NoOpAuditPersister(), localAuthentication), + identityProviderRepository); private final WsActionTester tester = new WsActionTester(new CreateAction(userSessionRule, managedInstanceChecker, userService)); @Before @@ -305,15 +306,13 @@ public class CreateActionIT { public void fail_when_password_is_set_on_none_local_user() { logInAsSystemAdministrator(); - TestRequest request =tester.newRequest() - .setParam("login","john") - .setParam("name","John") + TestRequest request = tester.newRequest() + .setParam("login", "john") + .setParam("name", "John") .setParam("password", "1234") .setParam("local", "false"); - assertThatThrownBy(() -> { - request.execute(); - }) + assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Password should only be set on local user"); } diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/SearchActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/SearchActionIT.java index 972e08e521f..923746bd59c 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/SearchActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/SearchActionIT.java @@ -139,18 +139,18 @@ public class SearchActionIT { assertThat(ws.newRequest() .setParam("q", "user-%_%-") .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin) - .containsExactlyInAnyOrder(user.getLogin()); + .extracting(User::getLogin) + .containsExactlyInAnyOrder(user.getLogin()); assertThat(ws.newRequest() .setParam("q", "user@MAIL.com") .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin) - .containsExactlyInAnyOrder(user.getLogin()); + .extracting(User::getLogin) + .containsExactlyInAnyOrder(user.getLogin()); assertThat(ws.newRequest() .setParam("q", "user-name") .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin) - .containsExactlyInAnyOrder(user.getLogin()); + .extracting(User::getLogin) + .containsExactlyInAnyOrder(user.getLogin()); } @Test @@ -265,14 +265,14 @@ public class SearchActionIT { userSession.logIn().setSystemAdministrator(); assertThat(ws.newRequest() .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin, User::getTokensCount) - .containsExactlyInAnyOrder(tuple(user.getLogin(), 2)); + .extracting(User::getLogin, User::getTokensCount) + .containsExactlyInAnyOrder(tuple(user.getLogin(), 2)); userSession.logIn(); assertThat(ws.newRequest() .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin, User::hasTokensCount) - .containsExactlyInAnyOrder(tuple(user.getLogin(), false)); + .extracting(User::getLogin, User::hasTokensCount) + .containsExactlyInAnyOrder(tuple(user.getLogin(), false)); } @Test @@ -282,14 +282,14 @@ public class SearchActionIT { userSession.logIn().setSystemAdministrator(); assertThat(ws.newRequest() .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin, User::getEmail) - .containsExactlyInAnyOrder(tuple(user.getLogin(), user.getEmail())); + .extracting(User::getLogin, User::getEmail) + .containsExactlyInAnyOrder(tuple(user.getLogin(), user.getEmail())); userSession.logIn(); assertThat(ws.newRequest() .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin, User::hasEmail) - .containsExactlyInAnyOrder(tuple(user.getLogin(), false)); + .extracting(User::getLogin, User::hasEmail) + .containsExactlyInAnyOrder(tuple(user.getLogin(), false)); } @Test @@ -317,14 +317,14 @@ public class SearchActionIT { userSession.logIn().setSystemAdministrator(); assertThat(ws.newRequest() .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin, u -> u.getGroups().getGroupsList()) - .containsExactlyInAnyOrder(tuple(user.getLogin(), asList(group1.getName(), group2.getName()))); + .extracting(User::getLogin, u -> u.getGroups().getGroupsList()) + .containsExactlyInAnyOrder(tuple(user.getLogin(), asList(group1.getName(), group2.getName()))); userSession.logIn(); assertThat(ws.newRequest() .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin, User::hasGroups) - .containsExactlyInAnyOrder(tuple(user.getLogin(), false)); + .extracting(User::getLogin, User::hasGroups) + .containsExactlyInAnyOrder(tuple(user.getLogin(), false)); } @Test @@ -347,14 +347,14 @@ public class SearchActionIT { userSession.logIn().setSystemAdministrator(); assertThat(ws.newRequest() .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin, User::getExternalIdentity) - .containsExactlyInAnyOrder(tuple(user.getLogin(), user.getExternalLogin())); + .extracting(User::getLogin, User::getExternalIdentity) + .containsExactlyInAnyOrder(tuple(user.getLogin(), user.getExternalLogin())); userSession.logIn(); assertThat(ws.newRequest() .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin, User::hasExternalIdentity) - .containsExactlyInAnyOrder(tuple(user.getLogin(), false)); + .extracting(User::getLogin, User::hasExternalIdentity) + .containsExactlyInAnyOrder(tuple(user.getLogin(), false)); } @Test @@ -403,18 +403,18 @@ public class SearchActionIT { userSession.logIn(user); assertThat(ws.newRequest().setParam("q", user.getLogin()) .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin, User::getName, User::getEmail, User::getExternalIdentity, User::getExternalProvider, - User::hasScmAccounts, User::hasAvatar, User::hasGroups, User::getTokensCount, User::hasLastConnectionDate, User::hasManaged) - .containsExactlyInAnyOrder( - tuple(user.getLogin(), user.getName(), user.getEmail(), user.getExternalLogin(), user.getExternalIdentityProvider(), true, true, true, 2, true, true)); + .extracting(User::getLogin, User::getName, User::getEmail, User::getExternalIdentity, User::getExternalProvider, + User::hasScmAccounts, User::hasAvatar, User::hasGroups, User::getTokensCount, User::hasLastConnectionDate, User::hasManaged) + .containsExactlyInAnyOrder( + tuple(user.getLogin(), user.getName(), user.getEmail(), user.getExternalLogin(), user.getExternalIdentityProvider(), true, true, true, 2, true, true)); userSession.logIn(otherUser); assertThat(ws.newRequest().setParam("q", user.getLogin()) .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin, User::getName, User::hasEmail, User::hasExternalIdentity, User::hasExternalProvider, - User::hasScmAccounts, User::hasAvatar, User::hasGroups, User::hasTokensCount, User::hasLastConnectionDate) - .containsExactlyInAnyOrder( - tuple(user.getLogin(), user.getName(), false, false, true, true, true, false, false, false)); + .extracting(User::getLogin, User::getName, User::hasEmail, User::hasExternalIdentity, User::hasExternalProvider, + User::hasScmAccounts, User::hasAvatar, User::hasGroups, User::hasTokensCount, User::hasLastConnectionDate) + .containsExactlyInAnyOrder( + tuple(user.getLogin(), user.getName(), false, false, true, true, true, false, false, false)); } @Test @@ -527,8 +527,8 @@ public class SearchActionIT { assertThat(ws.newRequest() .setParam("q", "user-%_%-") .executeProtobuf(SearchWsResponse.class).getUsersList()) - .extracting(User::getLogin) - .containsExactlyInAnyOrder(user.getLogin()); + .extracting(User::getLogin) + .containsExactlyInAnyOrder(user.getLogin()); assertUserWithFilter(SearchAction.LAST_CONNECTION_DATE_FROM, lastConnection.minus(1, ChronoUnit.DAYS), user.getLogin(), true); assertUserWithFilter(SearchAction.LAST_CONNECTION_DATE_FROM, lastConnection.plus(1, ChronoUnit.DAYS), user.getLogin(), false); @@ -587,14 +587,12 @@ public class SearchActionIT { } private void mockUsersAsManaged(String... userUuids) { - when(managedInstanceService.getUserUuidToManaged(any(), any())).thenAnswer(invocation -> - { - Set<?> allUsersUuids = invocation.getArgument(1, Set.class); - return allUsersUuids.stream() - .map(userUuid -> (String) userUuid) - .collect(toMap(identity(), userUuid -> Set.of(userUuids).contains(userUuid))); - } - ); + when(managedInstanceService.getUserUuidToManaged(any(), any())).thenAnswer(invocation -> { + Set<?> allUsersUuids = invocation.getArgument(1, Set.class); + return allUsersUuids.stream() + .map(String.class::cast) + .collect(toMap(identity(), userUuid -> Set.of(userUuids).contains(userUuid))); + }); } @Test diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/UpdateActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/UpdateActionIT.java index e44b54ffe51..6293fc839d9 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/UpdateActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/UpdateActionIT.java @@ -266,9 +266,7 @@ public class UpdateActionIT { TestRequest request = ws.newRequest() .setParam("login", USER_LOGIN); - assertThatThrownBy(() -> { - request.execute(); - }) + assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("User 'john' doesn't exist"); } @@ -280,9 +278,7 @@ public class UpdateActionIT { TestRequest request = ws.newRequest() .setParam("login", USER_LOGIN) .setParam("email", "invalid-email"); - assertThatThrownBy(() -> { - request.execute(); - }) + assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Email 'invalid-email' is not valid"); } diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usergroups/ws/UsersActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usergroups/ws/UsersActionIT.java index 41982265143..8df4d9f277b 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usergroups/ws/UsersActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usergroups/ws/UsersActionIT.java @@ -201,22 +201,22 @@ public class UsersActionIT { .setParam(PARAM_GROUP_NAME, group.getName()) .execute() .getInput()).isSimilarTo(""" - { - "users": [ - {"login": "ada", "name": "Ada Lovelace", "selected": true} - ] - }"""); + { + "users": [ + {"login": "ada", "name": "Ada Lovelace", "selected": true} + ] + }"""); assertJson(newUsersRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(Param.SELECTED, SelectionMode.SELECTED.value()) .execute() .getInput()).isSimilarTo(""" - { - "users": [ - {"login": "ada", "name": "Ada Lovelace", "selected": true} - ] - }"""); + { + "users": [ + {"login": "ada", "name": "Ada Lovelace", "selected": true} + ] + }"""); } @Test @@ -255,18 +255,18 @@ public class UsersActionIT { .setParam(Param.SELECTED, SelectionMode.ALL.value()) .execute() .getInput()).isSimilarTo(""" - { - "p": 1, - "ps": 1, - "total": 2, - "paging": { - "pageIndex": 1, - "pageSize": 1, - "total": 2 - }, "users": [ - {"login": "ada", "name": "Ada Lovelace", "selected": true} - ] - }"""); + { + "p": 1, + "ps": 1, + "total": 2, + "paging": { + "pageIndex": 1, + "pageSize": 1, + "total": 2 + }, "users": [ + {"login": "ada", "name": "Ada Lovelace", "selected": true} + ] + }"""); assertJson(newUsersRequest() .setParam(PARAM_GROUP_NAME, group.getName()) @@ -275,18 +275,18 @@ public class UsersActionIT { .setParam(Param.SELECTED, SelectionMode.ALL.value()) .execute() .getInput()).isSimilarTo(""" - { - "p": 2, - "ps": 1, - "total": 2, - "paging": { - "pageIndex": 2, - "pageSize": 1, - "total": 2 - }, "users": [ - {"login": "grace", "name": "Grace Hopper", "selected": false} - ] - }"""); + { + "p": 2, + "ps": 1, + "total": 2, + "paging": { + "pageIndex": 2, + "pageSize": 1, + "total": 2 + }, "users": [ + {"login": "grace", "name": "Grace Hopper", "selected": false} + ] + }"""); } @Test @@ -303,58 +303,58 @@ public class UsersActionIT { .setParam(Param.SELECTED, SelectionMode.ALL.value()) .execute() .getInput()).isSimilarTo(""" - { - "users": [ - {"login": "ada.login", "name": "Ada Lovelace", "selected": true}, - {"login": "grace", "name": "Grace Hopper", "selected": false} - ] - } - """); + { + "users": [ + {"login": "ada.login", "name": "Ada Lovelace", "selected": true}, + {"login": "grace", "name": "Grace Hopper", "selected": false} + ] + } + """); assertJson(newUsersRequest().setParam(PARAM_GROUP_NAME, group.getName()) .setParam("q", ".logi") .execute() .getInput()).isSimilarTo(""" - { - "users": [ - { - "login": "ada.login", - "name": "Ada Lovelace", - "selected": true - } - ] - } - """); + { + "users": [ + { + "login": "ada.login", + "name": "Ada Lovelace", + "selected": true + } + ] + } + """); assertJson(newUsersRequest().setParam(PARAM_GROUP_NAME, group.getName()) .setParam("q", "OvE") .execute() .getInput()).isSimilarTo(""" - { - "users": [ - { - "login": "ada.login", - "name": "Ada Lovelace", - "selected": true - } - ] - } - """); + { + "users": [ + { + "login": "ada.login", + "name": "Ada Lovelace", + "selected": true + } + ] + } + """); assertJson(newUsersRequest().setParam(PARAM_GROUP_NAME, group.getName()) .setParam("q", "mail") .execute() .getInput()).isSimilarTo(""" - { - "users": [ - { - "login": "ada.login", - "name": "Ada Lovelace", - "selected": true - } - ] - } - """); + { + "users": [ + { + "login": "ada.login", + "name": "Ada Lovelace", + "selected": true + } + ] + } + """); } @Test @@ -385,14 +385,12 @@ public class UsersActionIT { } private void mockUsersAsManaged(String... userUuids) { - when(managedInstanceService.getUserUuidToManaged(any(), any())).thenAnswer(invocation -> - { - Set<?> allUsersUuids = invocation.getArgument(1, Set.class); - return allUsersUuids.stream() - .map(userUuid -> (String) userUuid) - .collect(toMap(identity(), userUuid -> Set.of(userUuids).contains(userUuid))); - } - ); + when(managedInstanceService.getUserUuidToManaged(any(), any())).thenAnswer(invocation -> { + Set<?> allUsersUuids = invocation.getArgument(1, Set.class); + return allUsersUuids.stream() + .map(String.class::cast) + .collect(toMap(identity(), userUuid -> Set.of(userUuids).contains(userUuid))); + }); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/SubmitActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/SubmitActionTest.java index 7e6c98453c4..5268fbe8b32 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/SubmitActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/SubmitActionTest.java @@ -93,13 +93,13 @@ public class SubmitActionTest { String devOpsPlatformUrl = "https://github.com"; String devOpsPlatformProjectIdentifier = "foo/bar"; - + String[] characteristics = { buildCharacteristicParam(BRANCH, "foo"), buildCharacteristicParam(PULL_REQUEST, "123"), buildCharacteristicParam("unsupported", "bar"), buildCharacteristicParam(DEVOPS_PLATFORM_URL, devOpsPlatformUrl), - buildCharacteristicParam(DEVOPS_PLATFORM_PROJECT_IDENTIFIER, devOpsPlatformProjectIdentifier) }; + buildCharacteristicParam(DEVOPS_PLATFORM_PROJECT_IDENTIFIER, devOpsPlatformProjectIdentifier)}; Ce.SubmitResponse submitResponse = tester.newRequest() .setParam("projectKey", "my_project") .setParam("projectName", "My Project") @@ -186,7 +186,7 @@ public class SubmitActionTest { .setMediaType(MediaTypes.PROTOBUF) .setMethod("POST"); - assertThatThrownBy(() -> request.execute()) + assertThatThrownBy(request::execute) .isInstanceOf(ServerException.class) .hasMessage("Error message"); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthCheckerImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthCheckerImplTest.java index edbd4a67eb6..d2854ebaaf6 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthCheckerImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthCheckerImplTest.java @@ -90,10 +90,10 @@ public class HealthCheckerImplTest { public void checkNode_returns_RED_status_if_at_least_one_RED_status_returned_by_NodeHealthCheck() { List<Health.Status> statuses = new ArrayList<>(); Stream.of( - IntStream.range(0, 1 + random.nextInt(20)).mapToObj(i -> RED), // at least 1 RED - IntStream.range(0, random.nextInt(20)).mapToObj(i -> YELLOW), // between 0 and 19 YELLOW - IntStream.range(0, random.nextInt(20)).mapToObj(i -> GREEN) // between 0 and 19 GREEN - ).flatMap(s -> s) + IntStream.range(0, 1 + random.nextInt(20)).mapToObj(i -> RED), // at least 1 RED + IntStream.range(0, random.nextInt(20)).mapToObj(i -> YELLOW), // between 0 and 19 YELLOW + IntStream.range(0, random.nextInt(20)).mapToObj(i -> GREEN) // between 0 and 19 GREEN + ).flatMap(s -> s) .forEach(statuses::add); Collections.shuffle(statuses); HealthCheckerImpl underTest = newNodeHealthCheckerImpl(statuses.stream()); @@ -121,7 +121,7 @@ public class HealthCheckerImplTest { when(nodeInformation.isStandalone()).thenReturn(true); HealthCheckerImpl underTest = new HealthCheckerImpl(nodeInformation, new NodeHealthCheck[0], new ClusterHealthCheck[0], sharedHealthState); - assertThatThrownBy(() -> underTest.checkCluster()) + assertThatThrownBy(underTest::checkCluster) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Clustering is not enabled"); } @@ -131,7 +131,7 @@ public class HealthCheckerImplTest { when(nodeInformation.isStandalone()).thenReturn(false); HealthCheckerImpl underTest = new HealthCheckerImpl(nodeInformation, new NodeHealthCheck[0], new ClusterHealthCheck[0], null); - assertThatThrownBy(() -> underTest.checkCluster()) + assertThatThrownBy(underTest::checkCluster) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("HealthState instance can't be null when clustering is enabled"); } @@ -175,10 +175,10 @@ public class HealthCheckerImplTest { when(nodeInformation.isStandalone()).thenReturn(false); List<Health.Status> statuses = new ArrayList<>(); Stream.of( - IntStream.range(0, 1 + random.nextInt(20)).mapToObj(i -> RED), // at least 1 RED - IntStream.range(0, random.nextInt(20)).mapToObj(i -> YELLOW), // between 0 and 19 YELLOW - IntStream.range(0, random.nextInt(20)).mapToObj(i -> GREEN) // between 0 and 19 GREEN - ).flatMap(s -> s) + IntStream.range(0, 1 + random.nextInt(20)).mapToObj(i -> RED), // at least 1 RED + IntStream.range(0, random.nextInt(20)).mapToObj(i -> YELLOW), // between 0 and 19 YELLOW + IntStream.range(0, random.nextInt(20)).mapToObj(i -> GREEN) // between 0 and 19 GREEN + ).flatMap(s -> s) .forEach(statuses::add); Collections.shuffle(statuses); HealthCheckerImpl underTest = newClusterHealthCheckerImpl(statuses.stream()); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthTest.java index 9417a15e888..8d996890f70 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthTest.java @@ -42,7 +42,7 @@ public class HealthTest { public void build_throws_NPE_if_status_is_null() { Health.Builder builder = Health.builder(); - expectStatusNotNullNPE(() -> builder.build()); + expectStatusNotNullNPE(builder::build); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthActionTest.java index e9d4a57c786..c4a78f599a2 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthActionTest.java @@ -89,7 +89,7 @@ public class HealthActionTest { public void request_fails_with_ForbiddenException_when_anonymous() { TestRequest request = underTest.newRequest(); - expectForbiddenException(() -> request.execute()); + expectForbiddenException(request::execute); } @@ -98,7 +98,7 @@ public class HealthActionTest { when(systemPasscode.isValid(any())).thenReturn(false); TestRequest request = underTest.newRequest(); - expectForbiddenException(() -> request.execute()); + expectForbiddenException(request::execute); } @Test @@ -108,7 +108,7 @@ public class HealthActionTest { when(healthChecker.checkCluster()).thenReturn(randomStatusMinimalClusterHealth()); TestRequest request = underTest.newRequest(); - expectForbiddenException(() -> request.execute()); + expectForbiddenException(request::execute); } @Test @@ -269,13 +269,13 @@ public class HealthActionTest { .setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]); IntStream.range(0, random.nextInt(4)).mapToObj(i -> secure().nextAlphabetic(5)).forEach(builder::addCause); return builder.setDetails( - newNodeDetailsBuilder() - .setType(random.nextBoolean() ? NodeDetails.Type.APPLICATION : NodeDetails.Type.SEARCH) - .setName(secure().nextAlphanumeric(3)) - .setHost(secure().nextAlphanumeric(4)) - .setPort(1 + random.nextInt(3)) - .setStartedAt(1 + random.nextInt(23)) - .build()) + newNodeDetailsBuilder() + .setType(random.nextBoolean() ? NodeDetails.Type.APPLICATION : NodeDetails.Type.SEARCH) + .setName(secure().nextAlphanumeric(3)) + .setHost(secure().nextAlphanumeric(4)) + .setPort(1 + random.nextInt(3)) + .setStartedAt(1 + random.nextInt(23)) + .build()) .build(); } @@ -284,13 +284,13 @@ public class HealthActionTest { .setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]); IntStream.range(0, random.nextInt(4)).mapToObj(i -> secure().nextAlphabetic(5)).forEach(builder::addCause); return builder.setDetails( - newNodeDetailsBuilder() - .setType(type) - .setName(name) - .setHost(host) - .setPort(port) - .setStartedAt(started) - .build()) + newNodeDetailsBuilder() + .setType(type) + .setName(name) + .setHost(host) + .setPort(port) + .setStartedAt(started) + .build()) .build(); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthCheckerModuleTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthCheckerModuleTest.java index d17fb1a4ff6..cdce3b64794 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthCheckerModuleTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthCheckerModuleTest.java @@ -30,9 +30,9 @@ import org.sonar.server.common.health.ClusterHealthCheck; import org.sonar.server.common.health.DbConnectionNodeCheck; import org.sonar.server.common.health.EsStatusClusterCheck; import org.sonar.server.common.health.EsStatusNodeCheck; -import org.sonar.server.health.HealthCheckerImpl; import org.sonar.server.common.health.NodeHealthCheck; import org.sonar.server.common.health.WebServerStatusNodeCheck; +import org.sonar.server.health.HealthCheckerImpl; import org.sonar.server.platform.NodeInformation; import static org.assertj.core.api.Assertions.assertThat; @@ -67,7 +67,7 @@ public class HealthCheckerModuleTest { underTest.configure(container); List<Class<?>> checks = container.getAddedObjects().stream() - .filter(o -> o instanceof Class) + .filter(Class.class::isInstance) .map(o -> (Class<?>) o) .filter(NodeHealthCheck.class::isAssignableFrom).collect(Collectors.toList()); assertThat(checks).containsOnly(WebServerStatusNodeCheck.class, DbConnectionNodeCheck.class, EsStatusNodeCheck.class, CeStatusNodeCheck.class); @@ -81,7 +81,7 @@ public class HealthCheckerModuleTest { underTest.configure(container); List<Class<?>> checks = container.getAddedObjects().stream() - .filter(o -> o instanceof Class) + .filter(Class.class::isInstance) .map(o -> (Class<?>) o) .filter(NodeHealthCheck.class::isAssignableFrom).collect(Collectors.toList()); assertThat(checks).containsOnly(WebServerStatusNodeCheck.class, DbConnectionNodeCheck.class, CeStatusNodeCheck.class); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthActionTest.java index e750f8ea2d7..6764890dc9c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthActionTest.java @@ -69,7 +69,7 @@ class SafeModeHealthActionTest { when(systemPasscode.isValid(any())).thenReturn(false); TestRequest request = underTest.newRequest(); - expectForbiddenException(() -> request.execute()); + expectForbiddenException(request::execute); } @ParameterizedTest diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthCheckerModuleTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthCheckerModuleTest.java index b3e988bd56c..270a0cdd371 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthCheckerModuleTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthCheckerModuleTest.java @@ -25,9 +25,9 @@ import org.junit.Test; import org.sonar.core.platform.ListContainer; import org.sonar.server.common.health.DbConnectionNodeCheck; import org.sonar.server.common.health.EsStatusNodeCheck; -import org.sonar.server.health.HealthCheckerImpl; import org.sonar.server.common.health.NodeHealthCheck; import org.sonar.server.common.health.WebServerSafemodeNodeCheck; +import org.sonar.server.health.HealthCheckerImpl; import static org.assertj.core.api.Assertions.assertThat; @@ -54,7 +54,7 @@ public class SafeModeHealthCheckerModuleTest { underTest.configure(container); List<Class<?>> checks = container.getAddedObjects().stream() - .filter(o -> o instanceof Class) + .filter(Class.class::isInstance) .map(o -> (Class<?>) o) .filter(NodeHealthCheck.class::isAssignableFrom) .collect(Collectors.toList()); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileReferenceTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileReferenceTest.java index 4b1ee2c733f..bba1b558bfc 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileReferenceTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileReferenceTest.java @@ -30,7 +30,6 @@ import static org.sonar.server.language.LanguageTesting.newLanguage; public class QProfileReferenceTest { - @Test public void fromKey_creates_reference_by_key() { QProfileReference ref = QProfileReference.fromKey("foo"); @@ -42,7 +41,7 @@ public class QProfileReferenceTest { public void getLanguage_throws_ISE_on_reference_by_key() { QProfileReference ref = QProfileReference.fromKey("foo"); - assertThatThrownBy(() -> ref.getLanguage()) + assertThatThrownBy(ref::getLanguage) .isInstanceOf(IllegalStateException.class) .hasMessage("Language is not defined. Please call hasKey()."); } @@ -51,7 +50,7 @@ public class QProfileReferenceTest { public void getName_throws_ISE_on_reference_by_key() { QProfileReference ref = QProfileReference.fromKey("foo"); - assertThatThrownBy(() -> ref.getName()) + assertThatThrownBy(ref::getName) .isInstanceOf(IllegalStateException.class) .hasMessage("Name is not defined. Please call hasKey()."); } @@ -68,7 +67,7 @@ public class QProfileReferenceTest { public void getKey_throws_ISE_on_reference_by_name() { QProfileReference ref = QProfileReference.fromName("js", "Sonar way"); - assertThatThrownBy(() -> ref.getKey()) + assertThatThrownBy(ref::getKey) .isInstanceOf(IllegalStateException.class) .hasMessage("Key is not defined. Please call hasKey()."); } diff --git a/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/WebServiceEngine.java b/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/WebServiceEngine.java index 149e2e84d24..1c51990cc48 100644 --- a/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/WebServiceEngine.java +++ b/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/WebServiceEngine.java @@ -192,7 +192,7 @@ public class WebServiceEngine implements LocalConnector, Startable { } private static boolean isRequestAbortedByClient(Exception exception) { - return Throwables.getCausalChain(exception).stream().anyMatch(t -> t instanceof ClientAbortException); + return Throwables.getCausalChain(exception).stream().anyMatch(ClientAbortException.class::isInstance); } private static boolean isResponseCommitted(Response response) { diff --git a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/MessageFormattingUtilsTest.java b/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/MessageFormattingUtilsTest.java index 250cd849bd5..d943cca692b 100644 --- a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/MessageFormattingUtilsTest.java +++ b/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/MessageFormattingUtilsTest.java @@ -36,6 +36,7 @@ public class MessageFormattingUtilsTest { public void nullFormattingListShouldBeEmptyList() { assertThat(MessageFormattingUtils.dbMessageFormattingListToWs(null)).isEmpty(); } + @Test public void singleEntryShouldBeIdentical() { DbIssues.MessageFormattings formattings = DbIssues.MessageFormattings.newBuilder() @@ -48,7 +49,7 @@ public class MessageFormattingUtilsTest { assertThat(MessageFormattingUtils.dbMessageFormattingToWs( formattings).get(0)) - .extracting(e -> e.getStart(), e -> e.getEnd(), e -> e.getType()) + .extracting(Common.MessageFormatting::getStart, Common.MessageFormatting::getEnd, Common.MessageFormatting::getType) .containsExactly(0, 4, Common.MessageFormattingType.CODE); } diff --git a/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/issue/internal/DefaultExternalIssueTest.java b/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/issue/internal/DefaultExternalIssueTest.java index fcc3f947621..dc768e6bb54 100644 --- a/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/issue/internal/DefaultExternalIssueTest.java +++ b/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/issue/internal/DefaultExternalIssueTest.java @@ -167,7 +167,7 @@ public class DefaultExternalIssueTest { .type(RuleType.BUG) .severity(Severity.BLOCKER); - assertThatThrownBy(() -> issue.save()) + assertThatThrownBy(issue::save) .isInstanceOf(IllegalStateException.class) .hasMessage("External issues must have a message"); } diff --git a/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/rule/internal/DefaultAdHocRuleTest.java b/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/rule/internal/DefaultAdHocRuleTest.java index 673a7790596..f2a456d58c2 100644 --- a/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/rule/internal/DefaultAdHocRuleTest.java +++ b/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/rule/internal/DefaultAdHocRuleTest.java @@ -87,7 +87,6 @@ public class DefaultAdHocRuleTest { verify(storage).store(any(DefaultAdHocRule.class)); } - @Test public void fail_to_store_if_no_engine_id() { SensorStorage storage = mock(SensorStorage.class); @@ -99,7 +98,7 @@ public class DefaultAdHocRuleTest { .severity(Severity.BLOCKER) .type(RuleType.CODE_SMELL); - assertThatThrownBy(() -> rule.save()) + assertThatThrownBy(rule::save) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Engine id is mandatory"); } @@ -115,7 +114,7 @@ public class DefaultAdHocRuleTest { .severity(Severity.BLOCKER) .type(RuleType.CODE_SMELL); - assertThatThrownBy(() -> rule.save()) + assertThatThrownBy(rule::save) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Rule id is mandatory"); } @@ -131,7 +130,7 @@ public class DefaultAdHocRuleTest { .severity(Severity.BLOCKER) .type(RuleType.CODE_SMELL); - assertThatThrownBy(() -> rule.save()) + assertThatThrownBy(rule::save) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Name is mandatory"); } @@ -146,7 +145,7 @@ public class DefaultAdHocRuleTest { .description("desc") .type(RuleType.CODE_SMELL); - assertThatThrownBy(() -> rule.save()) + assertThatThrownBy(rule::save) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Impact should be provided, or Severity and Type instead"); } @@ -161,7 +160,7 @@ public class DefaultAdHocRuleTest { .description("desc") .severity(Severity.BLOCKER); - assertThatThrownBy(() -> rule.save()) + assertThatThrownBy(rule::save) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Impact should be provided, or Severity and Type instead"); } diff --git a/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/highlighting/HighlightingMediumIT.java b/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/highlighting/HighlightingMediumIT.java index 5f9a6c869ea..87d2350f476 100644 --- a/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/highlighting/HighlightingMediumIT.java +++ b/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/highlighting/HighlightingMediumIT.java @@ -94,9 +94,9 @@ public class HighlightingMediumIT { .put("sonar.projectDescription", "Description of Foo Project") .put("sonar.sources", "src") .put("sonar.it.savedatatwice", "true") - .build());; + .build()); - assertThatThrownBy(() -> analysisBuilder.execute()) + assertThatThrownBy(analysisBuilder::execute) .isInstanceOf(UnsupportedOperationException.class) .hasMessageContaining("Trying to save highlighting twice for the same file is not supported"); } @@ -123,7 +123,7 @@ public class HighlightingMediumIT { .put("sonar.sources", "src") .build()); - assertThatThrownBy(() -> analysisBuilder.execute()) + assertThatThrownBy(analysisBuilder::execute) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Error processing line 2") .hasCauseInstanceOf(IllegalArgumentException.class); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/ProjectInfoTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/ProjectInfoTest.java index b27bfdd4423..47139b3e9de 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/ProjectInfoTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/ProjectInfoTest.java @@ -73,7 +73,7 @@ class ProjectInfoTest { settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, ""); settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, "version"); - assertThatThrownBy(() -> underTest.start()) + assertThatThrownBy(underTest::start) .isInstanceOf(RuntimeException.class); } @@ -83,7 +83,7 @@ class ProjectInfoTest { settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01"); settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, version); - assertThatThrownBy(() -> underTest.start()) + assertThatThrownBy(underTest::start) .isInstanceOf(MessageException.class) .hasMessage("\"" + version + "\" is not a valid project version. " + "The maximum length is 100 characters."); @@ -95,7 +95,7 @@ class ProjectInfoTest { settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01"); settings.setProperty(CoreProperties.BUILD_STRING_PROPERTY, buildString); - assertThatThrownBy(() -> underTest.start()) + assertThatThrownBy(underTest::start) .isInstanceOf(MessageException.class) .hasMessage("\"" + buildString + "\" is not a valid buildString. " + "The maximum length is 100 characters."); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssuePublisherTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssuePublisherTest.java index 0c4b12443ec..aa59812f63c 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssuePublisherTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssuePublisherTest.java @@ -226,7 +226,7 @@ public class IssuePublisherTest { ArgumentCaptor<ScannerReport.ExternalIssue> argument = ArgumentCaptor.forClass(ScannerReport.ExternalIssue.class); verify(reportPublisher.getWriter()).appendComponentExternalIssue(eq(file.scannerId()), argument.capture()); - assertThat(argument.getValue().getImpactsList()).extracting(i -> i.getSoftwareQuality(), i -> i.getSeverity()) + assertThat(argument.getValue().getImpactsList()).extracting(ScannerReport.Impact::getSoftwareQuality, ScannerReport.Impact::getSeverity) .containsExactly(tuple(MAINTAINABILITY.name(), org.sonar.api.issue.impact.Severity.LOW.name())); assertThat(argument.getValue().getCleanCodeAttribute()).isEqualTo(CleanCodeAttribute.CLEAR.name()); } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ScanPropertiesTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ScanPropertiesTest.java index 00afc461198..37f15a87a71 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ScanPropertiesTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ScanPropertiesTest.java @@ -95,7 +95,7 @@ public class ScanPropertiesTest { public void validate_fails_if_metadata_file_location_is_not_absolute() { settings.setProperty("sonar.scanner.metadataFilePath", "relative"); - assertThatThrownBy(() -> underTest.validate()) + assertThatThrownBy(underTest::validate) .isInstanceOf(MessageException.class) .hasMessage("Property 'sonar.scanner.metadataFilePath' must point to an absolute path: relative"); } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scm/ScmConfigurationTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scm/ScmConfigurationTest.java index a0c6608606b..9250b6680e9 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scm/ScmConfigurationTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scm/ScmConfigurationTest.java @@ -131,8 +131,7 @@ class ScmConfigurationTest { arguments(true, true, true), arguments(true, false, true), arguments(false, true, true), - arguments(false, false, false) - ); + arguments(false, false, false)); } @Test @@ -143,7 +142,7 @@ class ScmConfigurationTest { ScmProvider[] providers = {scmProvider, scmProvider}; ScmConfiguration underTest = new ScmConfiguration(inputModuleHierarchy, settings, analysisWarnings, providers); - assertThatThrownBy(() -> underTest.start()) + assertThatThrownBy(underTest::start) .isInstanceOf(MessageException.class) .hasMessageContaining("SCM provider autodetection failed. " + "Both key2 and key2 claim to support this project. " @@ -154,7 +153,7 @@ class ScmConfigurationTest { void fail_when_considerOldScmUrl_finds_invalid_provider_in_link() { when(settings.get(ScannerProperties.LINKS_SOURCES_DEV)).thenReturn(Optional.of("scm:invalid")); - assertThatThrownBy(() -> underTest.start()) + assertThatThrownBy(underTest::start) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("no SCM provider found for this key"); } |