From: Duarte Meneses Date: Mon, 26 Jun 2023 21:05:22 +0000 (-0500) Subject: SONAR-19962 Upgrade Sonar Plugin API to v10.0.0.695 X-Git-Tag: 10.2.0.77647~362 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=58f87e3e1313b39df5f3669ccf5f01f5d3e97490;p=sonarqube.git SONAR-19962 Upgrade Sonar Plugin API to v10.0.0.695 --- diff --git a/gradle.properties b/gradle.properties index 837aec54800..b2bb763418f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,6 @@ group=org.sonarsource.sonarqube version=10.2 -pluginApiVersion=9.17.0.587 +pluginApiVersion=10.0.0.695 description=Open source platform for continuous inspection of code quality projectTitle=SonarQube org.gradle.jvmargs=-Xmx2048m diff --git a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepIT.java b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepIT.java index c048f544747..414bca1a2e9 100644 --- a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepIT.java +++ b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepIT.java @@ -182,8 +182,8 @@ public class SendIssueNotificationsStepIT extends BaseStepTest { public void send_global_new_issues_notification() { analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList())); protoIssueCache.newAppender().append( - createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION) - .setCreationDate(new Date(ANALYSE_DATE))) + createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION) + .setCreationDate(new Date(ANALYSE_DATE))) .close(); when(notificationService.hasProjectSubscribersForTypes(eq(PROJECT.getUuid()), any())).thenReturn(true); @@ -238,8 +238,8 @@ public class SendIssueNotificationsStepIT extends BaseStepTest { public void do_not_send_global_new_issues_notification_if_issue_has_been_backdated() { analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList())); protoIssueCache.newAppender().append( - createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION) - .setCreationDate(new Date(ANALYSE_DATE - FIVE_MINUTES_IN_MS))) + createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION) + .setCreationDate(new Date(ANALYSE_DATE - FIVE_MINUTES_IN_MS))) .close(); when(notificationService.hasProjectSubscribersForTypes(PROJECT.getUuid(), NOTIF_TYPES)).thenReturn(true); @@ -317,7 +317,7 @@ public class SendIssueNotificationsStepIT extends BaseStepTest { analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList())); protoIssueCache.newAppender().append( - createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION).setAssigneeUuid(user.getUuid()).setCreationDate(new Date(ANALYSE_DATE))) + createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION).setAssigneeUuid(user.getUuid()).setCreationDate(new Date(ANALYSE_DATE))) .close(); when(notificationService.hasProjectSubscribersForTypes(eq(PROJECT.getUuid()), any())).thenReturn(true); @@ -478,8 +478,8 @@ public class SendIssueNotificationsStepIT extends BaseStepTest { analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList())); UserDto user = db.users().insertUser(); protoIssueCache.newAppender().append( - createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION).setAssigneeUuid(user.getUuid()) - .setCreationDate(new Date(ANALYSE_DATE - FIVE_MINUTES_IN_MS))) + createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION).setAssigneeUuid(user.getUuid()) + .setCreationDate(new Date(ANALYSE_DATE - FIVE_MINUTES_IN_MS))) .close(); when(notificationService.hasProjectSubscribersForTypes(PROJECT.getUuid(), NOTIF_TYPES)).thenReturn(true); diff --git a/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionImpl.java b/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionImpl.java index 19a5d6e943c..d05565cfc83 100644 --- a/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionImpl.java +++ b/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionImpl.java @@ -34,7 +34,6 @@ class ConditionImpl implements QualityGate.Condition { private final String metricKey; private final QualityGate.Operator operator; private final String errorThreshold; - private final boolean onLeakPeriod; @CheckForNull private final String value; @@ -49,7 +48,6 @@ class ConditionImpl implements QualityGate.Condition { this.metricKey = builder.metricKey; this.operator = builder.operator; this.errorThreshold = builder.errorThreshold; - this.onLeakPeriod = builder.metricKey.startsWith("new_"); this.value = builder.value; } @@ -92,22 +90,6 @@ class ConditionImpl implements QualityGate.Condition { return this; } - /** - * @deprecated in 7.6. This method has no longer any effect. - */ - @Deprecated - public Builder setWarningThreshold(String warningThreshold) { - return this; - } - - /** - * @deprecated in 7.6. This method has no longer any effect. - */ - @Deprecated - public Builder setOnLeakPeriod(boolean onLeakPeriod) { - return this; - } - public Builder setValue(String value) { this.value = value; return this; @@ -143,21 +125,6 @@ class ConditionImpl implements QualityGate.Condition { return errorThreshold; } - @Deprecated - @Override - public String getWarningThreshold() { - return null; - } - - /** - * @deprecated in 7.6. Conditions "on leak period" were removed. Use "New X" conditions instead. - */ - @Deprecated - @Override - public boolean isOnLeakPeriod() { - return onLeakPeriod; - } - @Override public String getValue() { checkState(status != NO_VALUE, "There is no value when status is %s", NO_VALUE); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/ViewsMeasureComputersVisitorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/ViewsMeasureComputersVisitorTest.java index f3ab3c8ba25..a56efc716cd 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/ViewsMeasureComputersVisitorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/ViewsMeasureComputersVisitorTest.java @@ -23,7 +23,7 @@ import java.util.Arrays; import org.junit.Rule; import org.junit.Test; import org.sonar.api.ce.measure.MeasureComputer; -import org.sonar.api.ce.measure.test.TestMeasureComputerDefinitionContext; +import org.sonar.api.testfixtures.measure.TestMeasureComputerDefinitionContext; import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerDefinitionImpl; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportSizeMeasuresStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportSizeMeasuresStepTest.java index a11b0317cfe..2cff9edad0c 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportSizeMeasuresStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportSizeMeasuresStepTest.java @@ -106,7 +106,6 @@ public class ReportSizeMeasuresStepTest { @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(CoreMetrics.FILES) - .add(CoreMetrics.DIRECTORIES) .add(CoreMetrics.LINES) .add(CoreMetrics.GENERATED_LINES) .add(CoreMetrics.NCLOC) diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ViewsSizeMeasuresStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ViewsSizeMeasuresStepTest.java index 70e73f63fb3..fbedc00e0b9 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ViewsSizeMeasuresStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ViewsSizeMeasuresStepTest.java @@ -35,7 +35,6 @@ import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.CLASSES; import static org.sonar.api.measures.CoreMetrics.CLASSES_KEY; -import static org.sonar.api.measures.CoreMetrics.DIRECTORIES; import static org.sonar.api.measures.CoreMetrics.FILES; import static org.sonar.api.measures.CoreMetrics.FILES_KEY; import static org.sonar.api.measures.CoreMetrics.FUNCTIONS; @@ -88,7 +87,7 @@ public class ViewsSizeMeasuresStepTest { builder(PROJECT_VIEW, PROJECTVIEW_3_REF).build()) .build(), builder(SUBVIEW, SUB_SUBVIEW_3_REF).addChildren( - builder(PROJECT_VIEW, PROJECTVIEW_4_REF).build()) + builder(PROJECT_VIEW, PROJECTVIEW_4_REF).build()) .build()) .build(), builder(SUBVIEW, SUBVIEW_2_REF).build(), @@ -97,7 +96,6 @@ public class ViewsSizeMeasuresStepTest { @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(FILES) - .add(DIRECTORIES) .add(LINES) .add(GENERATED_LINES) .add(NCLOC) diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/webhook/WebhookPostTaskTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/webhook/WebhookPostTaskTest.java index c2b7b85e653..e8e52c4642a 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/webhook/WebhookPostTaskTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/webhook/WebhookPostTaskTest.java @@ -32,11 +32,11 @@ import org.mockito.ArgumentCaptor; import org.sonar.api.ce.posttask.Branch; import org.sonar.api.ce.posttask.CeTask; import org.sonar.api.ce.posttask.PostProjectAnalysisTask.LogStatistics; -import org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester; import org.sonar.api.ce.posttask.Project; import org.sonar.api.ce.posttask.QualityGate; import org.sonar.api.config.Configuration; import org.sonar.api.measures.Metric; +import org.sonar.api.testfixtures.posttask.PostProjectAnalysisTaskTester; import org.sonar.ce.task.projectanalysis.component.ConfigurationRepository; import org.sonar.server.qualitygate.Condition; import org.sonar.server.qualitygate.EvaluatedCondition; @@ -54,12 +54,12 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester.newBranchBuilder; -import static org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester.newCeTaskBuilder; -import static org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester.newConditionBuilder; -import static org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester.newProjectBuilder; -import static org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester.newQualityGateBuilder; -import static org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester.newScannerContextBuilder; +import static org.sonar.api.testfixtures.posttask.PostProjectAnalysisTaskTester.newBranchBuilder; +import static org.sonar.api.testfixtures.posttask.PostProjectAnalysisTaskTester.newCeTaskBuilder; +import static org.sonar.api.testfixtures.posttask.PostProjectAnalysisTaskTester.newConditionBuilder; +import static org.sonar.api.testfixtures.posttask.PostProjectAnalysisTaskTester.newProjectBuilder; +import static org.sonar.api.testfixtures.posttask.PostProjectAnalysisTaskTester.newQualityGateBuilder; +import static org.sonar.api.testfixtures.posttask.PostProjectAnalysisTaskTester.newScannerContextBuilder; public class WebhookPostTaskTest { @@ -93,7 +93,6 @@ public class WebhookPostTaskTest { .setMetricKey(randomAlphanumeric(96)) .setOperator(QualityGate.Operator.LESS_THAN) .setErrorThreshold(randomAlphanumeric(22)) - .setOnLeakPeriod(random.nextBoolean()) .build(QualityGate.EvaluationStatus.OK, randomAlphanumeric(33)); QualityGate qualityGate = newQualityGateBuilder() .setId(randomAlphanumeric(23)) diff --git a/server/sonar-ce/src/it/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListenerIT.java b/server/sonar-ce/src/it/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListenerIT.java index f0184c08762..610a5329d81 100644 --- a/server/sonar-ce/src/it/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListenerIT.java +++ b/server/sonar-ce/src/it/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListenerIT.java @@ -199,7 +199,6 @@ public class ReportAnalysisFailureNotificationExecutionListenerIT { when(notificationService.hasProjectSubscribersForTypes(projectData.projectUuid(), singleton(ReportAnalysisFailureNotification.class))) .thenReturn(true); - Duration randomDuration = randomDuration(); assertThatThrownBy(() -> underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration, ceTaskResultMock, throwableMock)) .isInstanceOf(RowNotFoundException.class) @@ -239,7 +238,7 @@ public class ReportAnalysisFailureNotificationExecutionListenerIT { long executedAt = random.nextInt(999_999); ProjectData project = random.nextBoolean() ? dbTester.components().insertPrivateProject() : dbTester.components().insertPublicProject(); - ComponentDto branchComponent = dbTester.components().insertProjectBranch(project.getMainBranchComponent(), b->b.setKey("otherbranch")); + ComponentDto branchComponent = dbTester.components().insertProjectBranch(project.getMainBranchComponent(), b -> b.setKey("otherbranch")); initMocksToPassConditionsForBranch(branchComponent, project, taskUuid, createdAt, executedAt); Notification notificationMock = mockSerializer(); diff --git a/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java b/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java index bff8ef8ec94..8cdac135679 100644 --- a/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java +++ b/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java @@ -29,10 +29,7 @@ import org.sonar.api.SonarQubeSide; import org.sonar.api.config.EmailSettings; import org.sonar.api.internal.MetadataLoader; import org.sonar.api.internal.SonarRuntimeImpl; -import org.sonar.api.profiles.XMLProfileParser; -import org.sonar.api.profiles.XMLProfileSerializer; import org.sonar.api.resources.ResourceTypes; -import org.sonar.api.rules.AnnotationRuleParser; import org.sonar.api.server.profile.BuiltInQualityProfileAnnotationLoader; import org.sonar.api.server.rule.RulesDefinitionXmlLoader; import org.sonar.api.utils.Durations; @@ -110,7 +107,6 @@ import org.sonar.server.issue.workflow.IssueWorkflow; import org.sonar.server.l18n.ServerI18n; import org.sonar.server.log.ServerLogging; import org.sonar.server.measure.index.ProjectMeasuresIndexer; -import org.sonar.server.metric.MetricFinder; import org.sonar.server.metric.UnanalyzedLanguageMetrics; import org.sonar.server.notification.DefaultNotificationManager; import org.sonar.server.notification.NotificationService; @@ -361,13 +357,10 @@ public class ComputeEngineContainerImpl implements ComputeEngineContainer { // quality profile ActiveRuleIndexer.class, - XMLProfileParser.class, - XMLProfileSerializer.class, BuiltInQualityProfileAnnotationLoader.class, Rules.QProfiles.class, // rule - AnnotationRuleParser.class, DefaultRuleFinder.class, RulesDefinitionXmlLoader.class, AdHocRuleCreator.class, @@ -378,7 +371,6 @@ public class ComputeEngineContainerImpl implements ComputeEngineContainer { LanguagesProvider.class, // measure - MetricFinder.class, UnanalyzedLanguageMetrics.class, // components, diff --git a/server/sonar-db-dao/src/main/java/org/sonar/api/notifications/Notification.java b/server/sonar-db-dao/src/main/java/org/sonar/api/notifications/Notification.java new file mode 100644 index 00000000000..1e0f9fe53f0 --- /dev/null +++ b/server/sonar-db-dao/src/main/java/org/sonar/api/notifications/Notification.java @@ -0,0 +1,143 @@ +/* + * SonarQube + * Copyright (C) 2009-2023 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.api.notifications; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.CheckForNull; +import javax.annotation.Nullable; + +/** + * This class represents a notification that will be delivered to users. This is a general concept and it has no + * knowledge of the possible ways to be delivered (see {@link NotificationChannel}). + *

+ * When creating a new notification, it is strongly advised to give a default message that can be used by channels + * that don't want to specifically format messages for different notification types. You can use + * {@link Notification#setDefaultMessage(String)} for that purpose. + * + * Note: This class used to be part of the plugin API but is no longer part of it and plugins can no longer implement it. + * However, since notifications get serialized into the DB, it was moved here keeping the same package name. + */ +public class Notification implements Serializable { + + private static final String DEFAULT_MESSAGE_KEY = "default_message"; + + private final String type; + private final Map fields = new HashMap<>(); + + /** + *

+ * Create a new {@link Notification} of the given type. + * + * Example: type = "new-violations" + * + * @param type the type of notification + */ + public Notification(String type) { + this.type = type; + } + + /** + * Returns the type of the notification + * + * @return the type + */ + public String getType() { + return type; + } + + /** + *

+ * When creating a new notification, it is strongly advised to give a default message that can be + * used by channels that don't want to specifically format messages for different notification types. + * + *

+ * This method is equivalent to setting a value for the field {@link #DEFAULT_MESSAGE_KEY} with + * {@link #setFieldValue(String, String)}. + * + * + * @since 3.5 + */ + public Notification setDefaultMessage(String value) { + setFieldValue(DEFAULT_MESSAGE_KEY, value); + return this; + } + + /** + * Returns the default message to display for this notification. + */ + public String getDefaultMessage() { + String defaultMessage = getFieldValue(DEFAULT_MESSAGE_KEY); + if (defaultMessage == null) { + defaultMessage = this.toString(); + } + return defaultMessage; + } + + /** + * Adds a field (kind of property) to the notification + * + * @param field the name of the field (= the key) + * @param value the value of the field + * @return the notification itself + */ + public Notification setFieldValue(String field, @Nullable String value) { + fields.put(field, value); + return this; + } + + /** + * Returns the value of a field. + * + * @param field the field + * @return the value of the field + */ + @CheckForNull + public String getFieldValue(String field) { + return fields.get(field); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Notification)) { + return false; + } + if (this == obj) { + return true; + } + Notification other = (Notification) obj; + return this.type.equals(other.type) && this.fields.equals(other.fields); + } + + @Override + public int hashCode() { + return type.hashCode() * 31 + fields.hashCode(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("Notification{"); + sb.append("type='").append(type).append('\''); + sb.append(", fields=").append(fields); + sb.append('}'); + return sb.toString(); + } +} \ No newline at end of file diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/notification/NotificationQueueDto.java b/server/sonar-db-dao/src/main/java/org/sonar/db/notification/NotificationQueueDto.java index 6f80a532d66..edf2bbc034f 100644 --- a/server/sonar-db-dao/src/main/java/org/sonar/db/notification/NotificationQueueDto.java +++ b/server/sonar-db-dao/src/main/java/org/sonar/db/notification/NotificationQueueDto.java @@ -27,7 +27,6 @@ import java.io.ObjectOutputStream; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.sonar.api.notifications.Notification; -import org.sonar.api.utils.SonarException; /** * @since 3.7.1 @@ -70,7 +69,7 @@ public class NotificationQueueDto { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } - public static NotificationQueueDto toNotificationQueueDto(T notification) { + public static NotificationQueueDto toNotificationQueueDto(Notification notification) { try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) { objectOutputStream.writeObject(notification); @@ -78,7 +77,7 @@ public class NotificationQueueDto { return new NotificationQueueDto().setData(byteArrayOutputStream.toByteArray()); } catch (IOException e) { - throw new SonarException("Unable to write notification", e); + throw new IllegalStateException("Unable to write notification", e); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/api/notifications/NotificationTest.java b/server/sonar-db-dao/src/test/java/org/sonar/api/notifications/NotificationTest.java new file mode 100644 index 00000000000..9d1a436e12b --- /dev/null +++ b/server/sonar-db-dao/src/test/java/org/sonar/api/notifications/NotificationTest.java @@ -0,0 +1,99 @@ +/* + * SonarQube + * Copyright (C) 2009-2023 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.api.notifications; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class NotificationTest { + @Test + public void getType_shouldReturnTypePassedInConstructor() { + Notification notification = new Notification("type"); + assertThat(notification.getType()).isEqualTo("type"); + } + + @Test + public void getDefaultMessage_whenNotDefined_returnToString() { + Notification notification = new Notification("type"); + assertThat(notification.getDefaultMessage()).isEqualTo("Notification{type='type', fields={}}"); + } + + @Test + public void getDefaultMessage_whenDefined_returnDefinedMessage() { + Notification notification = new Notification("type"); + notification.setDefaultMessage("default"); + assertThat(notification.getDefaultMessage()).isEqualTo("default"); + } + + @Test + public void getFieldValue_whenNotDefined_shouldReturnNull() { + Notification notification = new Notification("type"); + assertThat(notification.getFieldValue("unknown")).isNull(); + } + + @Test + public void getFieldValue_whenDefined_shouldReturnValue() { + Notification notification = new Notification("type"); + notification.setFieldValue("key", "value"); + assertThat(notification.getFieldValue("key")).isEqualTo("value"); + } + + @Test + public void equals_whenTypeAndFieldsMatch_shouldReturnTrue() { + Notification notification1 = new Notification("type"); + Notification notification2 = new Notification("type"); + + notification1.setFieldValue("key", "value"); + notification2.setFieldValue("key", "value"); + + assertThat(notification1) + .hasSameHashCodeAs(notification2) + .isEqualTo(notification2); + } + + @Test + public void equals_whenTypeDontMatch_shouldReturnFalse() { + Notification notification1 = new Notification("type1"); + Notification notification2 = new Notification("type2"); + + assertThat(notification1).isNotEqualTo(notification2); + } + + @Test + public void equals_whenFieldsDontMatch_shouldReturnFalse() { + Notification notification1 = new Notification("type"); + Notification notification2 = new Notification("type"); + + notification1.setFieldValue("key", "value1"); + notification2.setFieldValue("key", "value2"); + + assertThat(notification1).isNotEqualTo(notification2); + } + + @Test + public void toString_shouldReturnTypeAndFields() { + Notification notification1 = new Notification("type"); + + notification1.setFieldValue("key", "value1"); + + assertThat(notification1).hasToString("Notification{type='type', fields={key=value1}}"); + } +} \ No newline at end of file diff --git a/server/sonar-server-common/src/it/java/org/sonar/server/metric/MetricFinderIT.java b/server/sonar-server-common/src/it/java/org/sonar/server/metric/MetricFinderIT.java deleted file mode 100644 index 81b527327ef..00000000000 --- a/server/sonar-server-common/src/it/java/org/sonar/server/metric/MetricFinderIT.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.metric; - -import java.util.Arrays; -import org.junit.Rule; -import org.junit.Test; -import org.sonar.api.measures.Metric; -import org.sonar.api.utils.System2; -import org.sonar.db.DbTester; -import org.sonar.db.metric.MetricDto; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.db.metric.MetricTesting.newMetricDto; - -public class MetricFinderIT { - - @Rule - public DbTester db = DbTester.create(System2.INSTANCE); - - private final MetricFinder underTest = new MetricFinder(db.getDbClient()); - - @Test - public void findAll_enabled() { - db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); - db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); - db.getDbClient().metricDao().insert(db.getSession(), newMetricDto().setEnabled(false)); - db.commit(); - - assertThat(underTest.findAll()).hasSize(2); - } - - @Test - public void findAll_by_keys() { - db.getDbClient().metricDao().insert(db.getSession(), newMetricDto().setKey("ncloc")); - db.getDbClient().metricDao().insert(db.getSession(), newMetricDto().setKey("foo")); - db.getDbClient().metricDao().insert(db.getSession(), newMetricDto().setKey("coverage")); - db.commit(); - - assertThat(underTest.findAll(Arrays.asList("ncloc", "foo"))).extracting(Metric::getKey).containsExactlyInAnyOrder("ncloc", "foo") - .doesNotContain("coverage"); - - } - - @Test - public void findById() { - MetricDto firstMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); - MetricDto secondMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); - db.commit(); - - assertThat(underTest.findByUuid(firstMetric.getUuid())).extracting(Metric::getKey).isEqualTo(firstMetric.getKey()); - } - - @Test - public void findById_filters_out_disabled() { - MetricDto firstMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); - MetricDto secondMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto().setEnabled(false)); - db.commit(); - - assertThat(underTest.findByUuid(secondMetric.getUuid())).isNull(); - } - - @Test - public void findById_doesnt_find_anything() { - MetricDto firstMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); - MetricDto secondMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); - db.commit(); - - assertThat(underTest.findByUuid("non existing")).isNull(); - } - - @Test - public void findByKey() { - MetricDto firstMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); - MetricDto secondMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); - db.commit(); - - assertThat(underTest.findByKey(secondMetric.getKey())).extracting(Metric::getKey).isEqualTo(secondMetric.getKey()); - } - - @Test - public void findByKey_filters_out_disabled() { - MetricDto firstMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); - MetricDto secondMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto().setEnabled(false)); - db.commit(); - - assertThat(underTest.findByKey(secondMetric.getKey())).isNull(); - } - - @Test - public void findByKey_doesnt_find_anything() { - MetricDto firstMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); - MetricDto secondMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); - db.commit(); - - assertThat(underTest.findByKey("doesnt exist")).isNull(); - } -} diff --git a/server/sonar-server-common/src/it/java/org/sonar/server/rule/DefaultRuleFinderIT.java b/server/sonar-server-common/src/it/java/org/sonar/server/rule/DefaultRuleFinderIT.java index 619ffd88f91..4c72b72d076 100644 --- a/server/sonar-server-common/src/it/java/org/sonar/server/rule/DefaultRuleFinderIT.java +++ b/server/sonar-server-common/src/it/java/org/sonar/server/rule/DefaultRuleFinderIT.java @@ -25,6 +25,7 @@ import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.Rule; +import org.sonar.api.rules.RuleParam; import org.sonar.api.rules.RuleQuery; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -32,10 +33,12 @@ import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleDto.Scope; +import org.sonar.db.rule.RuleParamDto; import static java.util.Collections.emptySet; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; public class DefaultRuleFinderIT { @@ -124,6 +127,17 @@ public class DefaultRuleFinderIT { assertThat(underTest.findDtoByUuid(rule4.getUuid())).isPresent(); } + @Test + public void should_include_rule_params() { + RuleParamDto ruleParamDto = dbTester.rules().insertRuleParam(rule1, p -> p.setType("type").setName("name").setDescription("desc")); + dbTester.getSession().commit(); + Rule rule = underTest.findByKey("checkstyle", "com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck"); + assertThat(rule).isNotNull(); + assertThat(rule.getParams()) + .extracting(RuleParam::getKey, RuleParam::getType, RuleParam::getDescription) + .containsOnly(tuple("name", "type", "desc")); + } + @Test public void should_fail_find() { assertThat(underTest.findDtoByKey(RuleKey.of("pmd", "unknown"))).isEmpty(); diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/measure/index/ProjectMeasuresDoc.java b/server/sonar-server-common/src/main/java/org/sonar/server/measure/index/ProjectMeasuresDoc.java index 9ab9680f541..0b90f2486c5 100644 --- a/server/sonar-server-common/src/main/java/org/sonar/server/measure/index/ProjectMeasuresDoc.java +++ b/server/sonar-server-common/src/main/java/org/sonar/server/measure/index/ProjectMeasuresDoc.java @@ -32,7 +32,6 @@ import org.sonar.server.permission.index.AuthorizationDoc; import static org.sonar.api.measures.Metric.Level.ERROR; import static org.sonar.api.measures.Metric.Level.OK; -import static org.sonar.api.measures.Metric.Level.WARN; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_ANALYSED_AT; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_KEY; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_LANGUAGES; @@ -51,7 +50,7 @@ import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.TYPE public class ProjectMeasuresDoc extends BaseDoc { - public static final Map QUALITY_GATE_STATUS = ImmutableMap.of(OK.name(), 1, WARN.name(), 2, ERROR.name(), 3); + public static final Map QUALITY_GATE_STATUS = Map.of(OK.name(), 1, ERROR.name(), 3); public ProjectMeasuresDoc() { super(TYPE_PROJECT_MEASURES, new HashMap<>(8)); diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/metric/MetricFinder.java b/server/sonar-server-common/src/main/java/org/sonar/server/metric/MetricFinder.java deleted file mode 100644 index 41e0a620f5b..00000000000 --- a/server/sonar-server-common/src/main/java/org/sonar/server/metric/MetricFinder.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.metric; - -import java.io.Serializable; -import java.util.Collection; -import java.util.List; -import java.util.function.Function; -import java.util.function.Predicate; -import javax.annotation.Nonnull; -import org.sonar.api.measures.Metric; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.metric.MetricDto; - -public class MetricFinder { - - private final DbClient dbClient; - - public MetricFinder(DbClient dbClient) { - this.dbClient = dbClient; - } - - public Metric findByUuid(String uuid) { - try (DbSession session = dbClient.openSession(false)) { - MetricDto dto = dbClient.metricDao().selectByUuid(session, uuid); - if (dto != null && dto.isEnabled()) { - return ToMetric.INSTANCE.apply(dto); - } - return null; - } - } - - public Metric findByKey(String key) { - try (DbSession session = dbClient.openSession(false)) { - MetricDto dto = dbClient.metricDao().selectByKey(session, key); - if (dto != null && dto.isEnabled()) { - return ToMetric.INSTANCE.apply(dto); - } - return null; - } - } - - public Collection findAll(List metricKeys) { - try (DbSession session = dbClient.openSession(false)) { - List dtos = dbClient.metricDao().selectByKeys(session, metricKeys); - return dtos.stream().filter(IsEnabled.INSTANCE).map(ToMetric.INSTANCE).toList(); - } - } - - public Collection findAll() { - try (DbSession session = dbClient.openSession(false)) { - List dtos = dbClient.metricDao().selectEnabled(session); - return dtos.stream().map(ToMetric.INSTANCE).toList(); - } - } - - private enum IsEnabled implements Predicate { - INSTANCE; - @Override - public boolean test(@Nonnull MetricDto dto) { - return dto.isEnabled(); - } - } - - private enum ToMetric implements Function { - INSTANCE; - - @Override - public Metric apply(@Nonnull MetricDto dto) { - Metric metric = new Metric<>(); - metric.setUuid(dto.getUuid()); - metric.setKey(dto.getKey()); - metric.setDescription(dto.getDescription()); - metric.setName(dto.getShortName()); - metric.setBestValue(dto.getBestValue()); - metric.setDomain(dto.getDomain()); - metric.setEnabled(dto.isEnabled()); - metric.setDirection(dto.getDirection()); - metric.setHidden(dto.isHidden()); - metric.setQualitative(dto.isQualitative()); - metric.setType(Metric.ValueType.valueOf(dto.getValueType())); - metric.setOptimizedBestValue(dto.isOptimizedBestValue()); - metric.setWorstValue(dto.getWorstValue()); - return metric; - } - } -} diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/notification/DefaultNotificationManager.java b/server/sonar-server-common/src/main/java/org/sonar/server/notification/DefaultNotificationManager.java index 62d05308fad..13dbe069b99 100644 --- a/server/sonar-server-common/src/main/java/org/sonar/server/notification/DefaultNotificationManager.java +++ b/server/sonar-server-common/src/main/java/org/sonar/server/notification/DefaultNotificationManager.java @@ -28,11 +28,10 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; -import org.sonar.api.notifications.Notification; -import org.sonar.api.notifications.NotificationChannel; -import org.sonar.api.utils.SonarException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.sonar.api.notifications.Notification; +import org.sonar.api.utils.SonarException; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.EmailSubscriberDto; @@ -111,7 +110,8 @@ public class DefaultNotificationManager implements NotificationManager { } @Override - public Set findSubscribedEmailRecipients(String dispatcherKey, String projectKey, SubscriberPermissionsOnProject subscriberPermissionsOnProject) { + public Set findSubscribedEmailRecipients(String dispatcherKey, String projectKey, + SubscriberPermissionsOnProject subscriberPermissionsOnProject) { verifyProjectKey(projectKey); try (DbSession dbSession = dbClient.openSession(false)) { @@ -150,7 +150,8 @@ public class DefaultNotificationManager implements NotificationManager { .collect(Collectors.toSet()); } - private Stream keepAuthorizedEmailSubscribers(DbSession dbSession, String projectKey, Set emailSubscribers, + private Stream keepAuthorizedEmailSubscribers(DbSession dbSession, String projectKey, + Set emailSubscribers, SubscriberPermissionsOnProject requiredPermissions) { if (requiredPermissions.getGlobalSubscribers().equals(requiredPermissions.getProjectSubscribers())) { return keepAuthorizedEmailSubscribers(dbSession, projectKey, emailSubscribers, null, requiredPermissions.getGlobalSubscribers()); @@ -161,7 +162,8 @@ public class DefaultNotificationManager implements NotificationManager { } } - private Stream keepAuthorizedEmailSubscribers(DbSession dbSession, String projectKey, Set emailSubscribers, + private Stream keepAuthorizedEmailSubscribers(DbSession dbSession, String projectKey, + Set emailSubscribers, @Nullable Boolean global, String permission) { Set subscribers = emailSubscribers.stream() .filter(s -> global == null || s.isGlobal() == global) diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationChannel.java b/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationChannel.java new file mode 100644 index 00000000000..50962e9eb77 --- /dev/null +++ b/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationChannel.java @@ -0,0 +1,61 @@ +/* + * SonarQube + * Copyright (C) 2009-2023 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.server.notification; + +import org.sonar.api.notifications.Notification; + +/** + *

+ * This class can be extended to provide implementation on a specific way to deliver notifications. + * + * For example: + *

+ * + */ +public abstract class NotificationChannel { + + /** + * Returns the unique key of this channel. + * + * @return the key + */ + public String getKey() { + return getClass().getSimpleName(); + } + + /** + * Implements the delivery of the given notification to the given user. + * + * @param notification the notification to deliver + * @param userlogin the login of the user who should receive the notification + * @return whether the notification was sent or not + */ + public abstract boolean deliver(Notification notification, String userlogin); + + @Override + public String toString() { + return getKey(); + } + +} \ No newline at end of file diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationDispatcher.java b/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationDispatcher.java index 88178bb2988..024770a703e 100644 --- a/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationDispatcher.java +++ b/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationDispatcher.java @@ -23,7 +23,6 @@ import org.apache.commons.lang.StringUtils; import org.sonar.api.ExtensionPoint; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.notifications.Notification; -import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.server.ServerSide; /** diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationService.java b/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationService.java index e24180532f6..8d8bbe57c0a 100644 --- a/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationService.java +++ b/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationService.java @@ -34,7 +34,6 @@ import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.notifications.Notification; -import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.server.ServerSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java b/server/sonar-server-common/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java index 3c0cf7981b9..d0c6e654101 100644 --- a/server/sonar-server-common/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java +++ b/server/sonar-server-common/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java @@ -34,7 +34,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.config.EmailSettings; import org.sonar.api.notifications.Notification; -import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.user.User; import org.sonar.api.utils.SonarException; import org.sonar.db.DbClient; @@ -42,6 +41,7 @@ import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.server.issue.notification.EmailMessage; import org.sonar.server.issue.notification.EmailTemplate; +import org.sonar.server.notification.NotificationChannel; import static java.util.Objects.requireNonNull; diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/platform/ServerImpl.java b/server/sonar-server-common/src/main/java/org/sonar/server/platform/ServerImpl.java index 3f2ddfc3a35..86063c08384 100644 --- a/server/sonar-server-common/src/main/java/org/sonar/server/platform/ServerImpl.java +++ b/server/sonar-server-common/src/main/java/org/sonar/server/platform/ServerImpl.java @@ -52,11 +52,6 @@ public class ServerImpl extends Server { return config.get(CoreProperties.SERVER_ID).orElse(null); } - @Override - public String getPermanentServerId() { - return getId(); - } - @Override public String getVersion() { return version.get().toString(); @@ -76,9 +71,4 @@ public class ServerImpl extends Server { public String getPublicRootUrl() { return urlSettings.getBaseUrl(); } - - @Override - public boolean isSecured() { - return urlSettings.isSecured(); - } } diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/rule/DefaultRuleFinder.java b/server/sonar-server-common/src/main/java/org/sonar/server/rule/DefaultRuleFinder.java index ddd8886a0f2..fc49479cfbb 100644 --- a/server/sonar-server-common/src/main/java/org/sonar/server/rule/DefaultRuleFinder.java +++ b/server/sonar-server-common/src/main/java/org/sonar/server/rule/DefaultRuleFinder.java @@ -133,7 +133,7 @@ public class DefaultRuleFinder implements ServerRuleFinder { private org.sonar.api.rules.Rule toRule(RuleDto rule, List params) { String severity = rule.getSeverityString(); - org.sonar.api.rules.Rule apiRule = new org.sonar.api.rules.Rule(); + org.sonar.api.rules.Rule apiRule = org.sonar.api.rules.Rule.create(); apiRule .setName(rule.getName()) .setLanguage(rule.getLanguage()) @@ -150,12 +150,13 @@ public class DefaultRuleFinder implements ServerRuleFinder { Optional.ofNullable(ruleDescriptionFormatter.getDescriptionAsHtml(rule)).ifPresent(apiRule::setDescription); - List apiParams = new ArrayList<>(); for (RuleParamDto param : params) { - apiParams.add(new org.sonar.api.rules.RuleParam(apiRule, param.getName(), param.getDescription(), param.getType()) - .setDefaultValue(param.getDefaultValue())); + apiRule.createParameter() + .setType(param.getType()) + .setDescription(param.getDescription()) + .setKey(param.getName()) + .setDefaultValue(param.getDefaultValue()); } - apiRule.setParams(apiParams); return apiRule; } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FpOrWontFixEmailTemplateTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FpOrWontFixEmailTemplateTest.java index 6a6610e0692..f68200ce74a 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FpOrWontFixEmailTemplateTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FpOrWontFixEmailTemplateTest.java @@ -426,10 +426,10 @@ public class FpOrWontFixEmailTemplateTest { Rule rule2 = newRandomNotAHotspotRule("a"); String host = randomAlphabetic(15); List changedIssues = Stream.of( - IntStream.range(0, 39).mapToObj(i -> newChangedIssue("39_" + i, project1, rule1)), - IntStream.range(0, 40).mapToObj(i -> newChangedIssue("40_" + i, project1, rule2)), - IntStream.range(0, 81).mapToObj(i -> newChangedIssue("1-40_41-80_1_" + i, project2, rule2)), - IntStream.range(0, 6).mapToObj(i -> newChangedIssue("6_" + i, project2Branch, rule1))) + IntStream.range(0, 39).mapToObj(i -> newChangedIssue("39_" + i, project1, rule1)), + IntStream.range(0, 40).mapToObj(i -> newChangedIssue("40_" + i, project1, rule2)), + IntStream.range(0, 81).mapToObj(i -> newChangedIssue("1-40_41-80_1_" + i, project2, rule2)), + IntStream.range(0, 6).mapToObj(i -> newChangedIssue("6_" + i, project2Branch, rule1))) .flatMap(t -> t) .collect(toList()); Collections.shuffle(changedIssues); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/notification/DefaultNotificationManagerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/notification/DefaultNotificationManagerTest.java index b22f4290854..87918ca58a2 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/notification/DefaultNotificationManagerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/notification/DefaultNotificationManagerTest.java @@ -32,7 +32,6 @@ import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.sonar.api.notifications.Notification; -import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; @@ -65,7 +64,6 @@ import static org.sonar.server.notification.NotificationManager.SubscriberPermis public class DefaultNotificationManagerTest { - private DefaultNotificationManager underTest; private PropertiesDao propertiesDao = mock(PropertiesDao.class); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationDispatcherTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationDispatcherTest.java index b8d3d6e30fb..145c76c3c52 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationDispatcherTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationDispatcherTest.java @@ -24,7 +24,6 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.sonar.api.notifications.Notification; -import org.sonar.api.notifications.NotificationChannel; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerImplTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerImplTest.java index f21cd25d8e2..62455f66959 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerImplTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerImplTest.java @@ -44,7 +44,6 @@ public class ServerImplTest { assertThat(underTest.getContextPath()).isEqualTo("/foo"); assertThat(underTest.getPublicRootUrl()).isEqualTo("http://localhost:9000/foo"); - assertThat(underTest.isSecured()).isFalse(); } @Test @@ -60,7 +59,6 @@ public class ServerImplTest { settings.setProperty(CoreProperties.SERVER_ID, "foo"); assertThat(underTest.getId()).isEqualTo("foo"); - assertThat(underTest.getPermanentServerId()).isEqualTo("foo"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerLifecycleNotifierTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerLifecycleNotifierTest.java index 48eb439ad61..3791eb5cfbf 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerLifecycleNotifierTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerLifecycleNotifierTest.java @@ -116,14 +116,4 @@ class FakeServer extends Server { public String getPublicRootUrl() { return null; } - - @Override - public boolean isSecured() { - return false; - } - - @Override - public String getPermanentServerId() { - return null; - } } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/notification/QGChangeEmailTemplateTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/notification/QGChangeEmailTemplateTest.java index f5008ae3b13..3cda3cc99d3 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/notification/QGChangeEmailTemplateTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/notification/QGChangeEmailTemplateTest.java @@ -76,7 +76,7 @@ public class QGChangeEmailTemplateTest { @Test public void shouldFormatAlertWithSeveralMessagesOnBranch() { Notification notification = createNotification("Failed", "violations > 4, coverage < 75%", "ERROR", "false") - .setFieldValue("branch", "feature"); + .setFieldValue("branch", "feature"); EmailMessage message = template.format(notification); assertThat(message.getMessageId(), is("alerts/45")); @@ -133,7 +133,7 @@ public class QGChangeEmailTemplateTest { @Test public void shouldFormatNewAlertWithoutVersion() { Notification notification = createNotification("Failed", "violations > 4", "ERROR", "true") - .setFieldValue("projectVersion", null); + .setFieldValue("projectVersion", null); EmailMessage message = template.format(notification); assertThat(message.getMessageId(), is("alerts/45")); @@ -185,7 +185,7 @@ public class QGChangeEmailTemplateTest { @Test public void shouldFormatBackToGreenMessageOnBranch() { Notification notification = createNotification("Passed", "", "OK", "false") - .setFieldValue("branch", "feature"); + .setFieldValue("branch", "feature"); EmailMessage message = template.format(notification); assertThat(message.getMessageId(), is("alerts/45")); @@ -246,18 +246,18 @@ public class QGChangeEmailTemplateTest { private Notification createNotification(String alertName, String alertText, String alertLevel, String isNewAlert) { return new Notification("alerts") - .setFieldValue("projectName", "Foo") - .setFieldValue("projectKey", "org.sonar.foo:foo") - .setFieldValue("projectId", "45") - .setFieldValue("projectVersion", "V1-SNAP") - .setFieldValue("alertName", alertName) - .setFieldValue("alertText", alertText) - .setFieldValue("alertLevel", alertLevel) - .setFieldValue("isNewAlert", isNewAlert) - .setFieldValue("ratingMetrics", "Maintainability Rating,Reliability Rating on New Code," + - "Maintainability Rating on New Code,Reliability Rating," + - "Security Rating on New Code,Security Review Rating," + - "Security Review Rating on New Code,Security Rating"); + .setFieldValue("projectName", "Foo") + .setFieldValue("projectKey", "org.sonar.foo:foo") + .setFieldValue("projectId", "45") + .setFieldValue("projectVersion", "V1-SNAP") + .setFieldValue("alertName", alertName) + .setFieldValue("alertText", alertText) + .setFieldValue("alertLevel", alertLevel) + .setFieldValue("isNewAlert", isNewAlert) + .setFieldValue("ratingMetrics", "Maintainability Rating,Reliability Rating on New Code," + + "Maintainability Rating on New Code,Reliability Rating," + + "Security Rating on New Code,Security Review Rating," + + "Security Review Rating on New Code,Security Rating"); } } diff --git a/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/ProjectsInWarning.java b/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/ProjectsInWarning.java deleted file mode 100644 index 3d7b91bbfb6..00000000000 --- a/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/ProjectsInWarning.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.qualitygate; - -import static com.google.common.base.Preconditions.checkArgument; - -/** - * Store number of projects in warning in order for the web service api/components/search to know if warning value should be return in the quality gate facet. - * The value is updated each time the daemon {@link ProjectsInWarningDaemon} is executed - */ -public class ProjectsInWarning { - - private Long projectsInWarning; - - public void update(long projectsInWarning) { - this.projectsInWarning = projectsInWarning; - } - - public long count() { - checkArgument(isInitialized(), "Initialization has not be done"); - return projectsInWarning; - } - - boolean isInitialized() { - return projectsInWarning != null; - } -} diff --git a/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/package-info.java b/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/package-info.java deleted file mode 100644 index 6a28177f860..00000000000 --- a/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -@ParametersAreNonnullByDefault -package org.sonar.server.qualitygate; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/server/sonar-webserver-api/src/main/java/org/sonar/server/rule/CachingRuleFinder.java b/server/sonar-webserver-api/src/main/java/org/sonar/server/rule/CachingRuleFinder.java index 23f9ecec869..9317ce8578c 100644 --- a/server/sonar-webserver-api/src/main/java/org/sonar/server/rule/CachingRuleFinder.java +++ b/server/sonar-webserver-api/src/main/java/org/sonar/server/rule/CachingRuleFinder.java @@ -162,12 +162,13 @@ public class CachingRuleFinder implements ServerRuleFinder { Optional.ofNullable(ruleDescriptionFormatter.getDescriptionAsHtml(ruleDto)).ifPresent(apiRule::setDescription); Optional.ofNullable(ruleDto.getLanguage()).ifPresent(apiRule::setLanguage); - List apiParams = new ArrayList<>(); for (RuleParamDto param : params) { - apiParams.add(new org.sonar.api.rules.RuleParam(apiRule, param.getName(), param.getDescription(), param.getType()) - .setDefaultValue(param.getDefaultValue())); + apiRule.createParameter() + .setDescription(param.getDescription()) + .setKey(param.getName()) + .setType(param.getType()) + .setDefaultValue(param.getDefaultValue()); } - apiRule.setParams(apiParams); return apiRule; } diff --git a/server/sonar-webserver-api/src/main/java/org/sonar/server/util/LongTypeValidation.java b/server/sonar-webserver-api/src/main/java/org/sonar/server/util/LongTypeValidation.java deleted file mode 100644 index c2908872293..00000000000 --- a/server/sonar-webserver-api/src/main/java/org/sonar/server/util/LongTypeValidation.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.util; - -import java.util.List; -import javax.annotation.Nullable; -import org.sonar.api.PropertyType; -import org.sonar.server.exceptions.BadRequestException; - -import static java.lang.String.format; - -public class LongTypeValidation implements TypeValidation { - @Override - public String key() { - return PropertyType.LONG.name(); - } - - @Override - public void validate(String value, @Nullable List options) { - try { - Long.parseLong(value); - } catch (NumberFormatException e) { - throw BadRequestException.create(format("Value '%s' must be a long.", value)); - } - } -} diff --git a/server/sonar-webserver-api/src/main/java/org/sonar/server/util/MetricLevelTypeValidation.java b/server/sonar-webserver-api/src/main/java/org/sonar/server/util/MetricLevelTypeValidation.java deleted file mode 100644 index 20b0eb87e10..00000000000 --- a/server/sonar-webserver-api/src/main/java/org/sonar/server/util/MetricLevelTypeValidation.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.util; - -import java.util.List; -import javax.annotation.Nullable; -import org.sonar.api.PropertyType; -import org.sonar.api.measures.Metric; -import org.sonar.server.exceptions.BadRequestException; - -import static java.lang.String.format; - -public class MetricLevelTypeValidation implements TypeValidation { - @Override - public String key() { - return PropertyType.METRIC_LEVEL.name(); - } - - @Override - public void validate(String value, @Nullable List options) { - try { - Metric.Level.valueOf(value); - } catch (IllegalArgumentException e) { - throw BadRequestException.create(format("Value '%s' must be one of \"OK\", \"ERROR\".", value)); - } - } -} diff --git a/server/sonar-webserver-api/src/main/java/org/sonar/server/util/TypeValidationModule.java b/server/sonar-webserver-api/src/main/java/org/sonar/server/util/TypeValidationModule.java index a17d25b7eab..5524df04e22 100644 --- a/server/sonar-webserver-api/src/main/java/org/sonar/server/util/TypeValidationModule.java +++ b/server/sonar-webserver-api/src/main/java/org/sonar/server/util/TypeValidationModule.java @@ -31,9 +31,7 @@ public class TypeValidationModule extends Module { BooleanTypeValidation.class, TextTypeValidation.class, StringTypeValidation.class, - StringListTypeValidation.class, - LongTypeValidation.class, - MetricLevelTypeValidation.class + StringListTypeValidation.class ); } } diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/LongTypeValidationTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/LongTypeValidationTest.java deleted file mode 100644 index 6019134db33..00000000000 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/LongTypeValidationTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.util; - -import org.junit.Test; -import org.sonar.api.PropertyType; -import org.sonar.server.exceptions.BadRequestException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class LongTypeValidationTest { - - LongTypeValidation underTest = new LongTypeValidation(); - - @Test - public void key_is_long_type_name() { - assertThat(underTest.key()).isEqualTo(PropertyType.LONG.name()); - } - - @Test - public void do_not_fail_with_long_values() { - underTest.validate("1984", null); - underTest.validate("-1984", null); - } - - @Test - public void fail_when_float() { - assertThatThrownBy(() -> underTest.validate("3.14", null)) - .isInstanceOf(BadRequestException.class) - .hasMessage("Value '3.14' must be a long."); - } - - @Test - public void fail_when_string() { - assertThatThrownBy(() -> underTest.validate("original string", null)) - .isInstanceOf(BadRequestException.class) - .hasMessage("Value 'original string' must be a long."); - } -} diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/TypeValidationModuleTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/TypeValidationModuleTest.java index 03ca1bb05f5..a497034f0a8 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/TypeValidationModuleTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/TypeValidationModuleTest.java @@ -29,6 +29,6 @@ public class TypeValidationModuleTest { public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new TypeValidationModule().configure(container); - assertThat(container.getAddedObjects()).hasSize(9); + assertThat(container.getAddedObjects()).hasSize(7); } } diff --git a/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/CompatibilityRealm.java b/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/CompatibilityRealm.java deleted file mode 100644 index 7a3dbe3b23c..00000000000 --- a/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/CompatibilityRealm.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.user; - -import org.sonar.api.security.LoginPasswordAuthenticator; -import org.sonar.api.security.SecurityRealm; - -/** - * Provides backward compatibility for {@link org.sonar.api.CoreProperties#CORE_AUTHENTICATOR_CLASS}. - * - * @since 2.14 - */ -class CompatibilityRealm extends SecurityRealm { - private final LoginPasswordAuthenticator authenticator; - - public CompatibilityRealm(LoginPasswordAuthenticator authenticator) { - this.authenticator = authenticator; - } - - @Override - public void init() { - authenticator.init(); - } - - @Override - public String getName() { - return "CompatibilityRealm[" + authenticator.getClass().getName() + "]"; - } - - @Override - public LoginPasswordAuthenticator getLoginPasswordAuthenticator() { - return authenticator; - } -} diff --git a/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/SecurityRealmFactory.java b/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/SecurityRealmFactory.java index 748534fd7ed..312363017ce 100644 --- a/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/SecurityRealmFactory.java +++ b/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/SecurityRealmFactory.java @@ -23,10 +23,8 @@ import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.sonar.api.CoreProperties; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; -import org.sonar.api.security.LoginPasswordAuthenticator; import org.sonar.api.security.SecurityRealm; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.SonarException; @@ -47,10 +45,9 @@ public class SecurityRealmFactory implements Startable { private final SecurityRealm realm; @Autowired(required = false) - public SecurityRealmFactory(Configuration config, SecurityRealm[] realms, LoginPasswordAuthenticator[] authenticators) { + public SecurityRealmFactory(Configuration config, SecurityRealm[] realms) { ignoreStartupFailure = config.getBoolean(SONAR_AUTHENTICATOR_IGNORE_STARTUP_FAILURE.getKey()).orElse(false); String realmName = config.get(SONAR_SECURITY_REALM.getKey()).orElse(null); - String className = config.get(CoreProperties.CORE_AUTHENTICATOR_CLASS).orElse(null); if (LDAP_SECURITY_REALM.equals(realmName)) { realm = null; @@ -65,31 +62,14 @@ public class SecurityRealmFactory implements Startable { "Realm '%s' not found. Please check the property '%s' in conf/sonar.properties", realmName, SONAR_SECURITY_REALM.getKey())); } } - if (selectedRealm == null && !StringUtils.isEmpty(className)) { - LoginPasswordAuthenticator authenticator = selectAuthenticator(authenticators, className); - if (authenticator == null) { - throw new SonarException(String.format( - "Authenticator '%s' not found. Please check the property '%s' in conf/sonar.properties", className, CoreProperties.CORE_AUTHENTICATOR_CLASS)); - } - selectedRealm = new CompatibilityRealm(authenticator); - } - realm = selectedRealm; - } - - @Autowired(required = false) - public SecurityRealmFactory(Configuration config, LoginPasswordAuthenticator[] authenticators) { - this(config, new SecurityRealm[0], authenticators); - } + realm = selectedRealm; - @Autowired(required = false) - public SecurityRealmFactory(Configuration config, SecurityRealm[] realms) { - this(config, realms, new LoginPasswordAuthenticator[0]); } @Autowired(required = false) public SecurityRealmFactory(Configuration config) { - this(config, new SecurityRealm[0], new LoginPasswordAuthenticator[0]); + this(config, new SecurityRealm[0]); } @Override @@ -131,14 +111,4 @@ public class SecurityRealmFactory implements Startable { } return null; } - - private static LoginPasswordAuthenticator selectAuthenticator(LoginPasswordAuthenticator[] authenticators, String className) { - for (LoginPasswordAuthenticator lpa : authenticators) { - if (lpa.getClass().getName().equals(className)) { - return lpa; - } - } - return null; - } - } diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/CompatibilityRealmTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/CompatibilityRealmTest.java deleted file mode 100644 index c032f8886f7..00000000000 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/CompatibilityRealmTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.user; - -import org.junit.Test; -import org.sonar.api.security.LoginPasswordAuthenticator; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class CompatibilityRealmTest { - - @Test - public void shouldDelegate() { - LoginPasswordAuthenticator authenticator = mock(LoginPasswordAuthenticator.class); - CompatibilityRealm realm = new CompatibilityRealm(authenticator); - realm.init(); - verify(authenticator).init(); - assertThat(realm.getLoginPasswordAuthenticator()).isSameAs(authenticator); - assertThat(realm.getName()).isEqualTo("CompatibilityRealm[" + authenticator.getClass().getName() + "]"); - } - -} diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/SecurityRealmFactoryTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/SecurityRealmFactoryTest.java index 14b364e0ef9..ff1421f0b27 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/SecurityRealmFactoryTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/SecurityRealmFactoryTest.java @@ -22,7 +22,7 @@ package org.sonar.server.user; import org.junit.Test; import org.sonar.api.CoreProperties; import org.sonar.api.config.internal.MapSettings; -import org.sonar.api.security.LoginPasswordAuthenticator; +import org.sonar.api.security.Authenticator; import org.sonar.api.security.SecurityRealm; import org.sonar.api.utils.SonarException; @@ -30,6 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.sonar.process.ProcessProperties.Property.SONAR_AUTHENTICATOR_IGNORE_STARTUP_FAILURE; public class SecurityRealmFactoryTest { @@ -81,45 +82,11 @@ public class SecurityRealmFactoryTest { } } - @Test - public void should_provide_compatibility_for_authenticator() { - settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_CLASS, FakeAuthenticator.class.getName()); - LoginPasswordAuthenticator authenticator = new FakeAuthenticator(); - - SecurityRealmFactory factory = new SecurityRealmFactory(settings.asConfig(), new LoginPasswordAuthenticator[] {authenticator}); - SecurityRealm realm = factory.getRealm(); - assertThat(realm).isInstanceOf(CompatibilityRealm.class); - } - - @Test - public void should_take_precedence_over_authenticator() { - SecurityRealm realm = new FakeRealm(); - settings.setProperty("sonar.security.realm", realm.getName()); - LoginPasswordAuthenticator authenticator = new FakeAuthenticator(); - settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_CLASS, FakeAuthenticator.class.getName()); - - SecurityRealmFactory factory = new SecurityRealmFactory(settings.asConfig(), new SecurityRealm[] {realm}, - new LoginPasswordAuthenticator[] {authenticator}); - assertThat(factory.getRealm()).isSameAs(realm); - } - - @Test - public void authenticator_not_found() { - settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_CLASS, "Fake"); - - try { - new SecurityRealmFactory(settings.asConfig()); - fail(); - } catch (SonarException e) { - assertThat(e.getMessage()).contains("Authenticator 'Fake' not found."); - } - } - @Test public void ignore_startup_failure() { SecurityRealm realm = spy(new AlwaysFailsRealm()); settings.setProperty("sonar.security.realm", realm.getName()); - settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_IGNORE_STARTUP_FAILURE, true); + settings.setProperty(SONAR_AUTHENTICATOR_IGNORE_STARTUP_FAILURE.getKey(), true); new SecurityRealmFactory(settings.asConfig(), new SecurityRealm[] {realm}).start(); verify(realm).init(); @@ -148,18 +115,8 @@ public class SecurityRealmFactoryTest { private static class FakeRealm extends SecurityRealm { @Override - public LoginPasswordAuthenticator getLoginPasswordAuthenticator() { + public Authenticator doGetAuthenticator() { return null; } } - - private static class FakeAuthenticator implements LoginPasswordAuthenticator { - public void init() { - } - - public boolean authenticate(String login, String password) { - return false; - } - } - } diff --git a/server/sonar-webserver-core/src/main/java/org/sonar/server/qualitygate/ProjectsInWarningDaemon.java b/server/sonar-webserver-core/src/main/java/org/sonar/server/qualitygate/ProjectsInWarningDaemon.java deleted file mode 100644 index 709c2dbf198..00000000000 --- a/server/sonar-webserver-core/src/main/java/org/sonar/server/qualitygate/ProjectsInWarningDaemon.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.qualitygate; - -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import java.util.Optional; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import org.sonar.api.Startable; -import org.sonar.api.config.Configuration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.server.es.SearchOptions; -import org.sonar.server.measure.index.ProjectMeasuresIndex; -import org.sonar.server.measure.index.ProjectMeasuresQuery; -import org.sonar.server.util.GlobalLockManager; - -import static org.sonar.api.measures.Metric.Level.WARN; - -/** - * This class is regularly checking the number of projects in warning state, in order to not return the "Warning" value - * in the quality gate facet of the Projects page when there are no more projects in warning. - * - * @see SONAR-12140 for more information - */ -public class ProjectsInWarningDaemon implements Startable { - - static final String PROJECTS_IN_WARNING_INTERNAL_PROPERTY = "projectsInWarning"; - - private static final Logger LOG = LoggerFactory.getLogger(ProjectsInWarningDaemon.class); - - private static final String FREQUENCY_IN_MILLISECONDS_PROPERTY = "sonar.projectsInWarning.frequencyInMilliseconds"; - private static final int DEFAULT_FREQUENCY_IN_MILLISECONDS = 1000 * 60 * 60 * 24; - private static final String THREAD_NAME_PREFIX = "sq-projects-in-warning-service-"; - - private static final String LOCK_NAME = "ProjectsInWarn"; - private static final int LOCK_DURATION_IN_SECOND = 60 * 60; - - private final DbClient dbClient; - private final ProjectMeasuresIndex projectMeasuresIndex; - private final Configuration config; - private final GlobalLockManager lockManager; - private final ProjectsInWarning projectsInWarning; - - private ScheduledExecutorService executorService; - - public ProjectsInWarningDaemon(DbClient dbClient, ProjectMeasuresIndex projectMeasuresIndex, Configuration config, GlobalLockManager lockManager, - ProjectsInWarning projectsInWarning) { - this.dbClient = dbClient; - this.projectMeasuresIndex = projectMeasuresIndex; - this.config = config; - this.lockManager = lockManager; - this.projectsInWarning = projectsInWarning; - } - - public void notifyStart() { - try (DbSession dbSession = dbClient.openSession(false)) { - Optional internalProperty = dbClient.internalPropertiesDao().selectByKey(dbSession, PROJECTS_IN_WARNING_INTERNAL_PROPERTY); - if (internalProperty.isPresent() && internalProperty.get().equals("0")) { - projectsInWarning.update(0L); - LOG.info("Counting number of projects in warning is not started as there are no projects in this situation."); - return; - } - } - LOG.info("Counting number of projects in warning is enabled."); - executorService = Executors.newSingleThreadScheduledExecutor(newThreadFactory()); - executorService.scheduleWithFixedDelay(countProjectsInWarning(), 0, frequency(), TimeUnit.MILLISECONDS); - } - - private int frequency() { - return config.getInt(FREQUENCY_IN_MILLISECONDS_PROPERTY).orElse(DEFAULT_FREQUENCY_IN_MILLISECONDS); - } - - private Runnable countProjectsInWarning() { - return () -> { - long nbProjectsInWarning = projectMeasuresIndex.search( - new ProjectMeasuresQuery() - .setQualityGateStatus(WARN) - .setIgnoreAuthorization(true), - // We only need the number of projects in warning - new SearchOptions().setLimit(1)).getTotal(); - - try (DbSession dbSession = dbClient.openSession(false)) { - updateProjectsInWarningInDb(dbSession, nbProjectsInWarning); - } catch (Exception e) { - LOG.error("Error updating number of projects in warning: {}", e.getMessage(), e); - } - projectsInWarning.update(nbProjectsInWarning); - if (nbProjectsInWarning == 0L) { - LOG.info("Counting number of projects in warning will be disabled as there are no more projects in warning."); - executorService.shutdown(); - } - }; - } - - private void updateProjectsInWarningInDb(DbSession dbSession, long nbProjectsInWarning) { - // Only one web node should do the update in db to avoid any collision - if (!lockManager.tryLock(LOCK_NAME, LOCK_DURATION_IN_SECOND)) { - return; - } - dbClient.internalPropertiesDao().save(dbSession, PROJECTS_IN_WARNING_INTERNAL_PROPERTY, Long.toString(nbProjectsInWarning)); - dbSession.commit(); - } - - @Override - public void start() { - // Nothing is done here, as this component needs to be started after ES indexing. See PlatformLevelStartup for more info. - } - - @Override - public void stop() { - if (executorService == null) { - return; - } - try { - executorService.shutdown(); - executorService.awaitTermination(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - - private static ThreadFactory newThreadFactory() { - return new ThreadFactoryBuilder() - .setNameFormat(THREAD_NAME_PREFIX + "%d") - .setPriority(Thread.MIN_PRIORITY) - .build(); - } - -} diff --git a/server/sonar-webserver-core/src/main/java/org/sonar/server/qualitygate/ProjectsInWarningModule.java b/server/sonar-webserver-core/src/main/java/org/sonar/server/qualitygate/ProjectsInWarningModule.java deleted file mode 100644 index 45e5a1dca97..00000000000 --- a/server/sonar-webserver-core/src/main/java/org/sonar/server/qualitygate/ProjectsInWarningModule.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.qualitygate; - -import org.sonar.core.platform.Module; - -public class ProjectsInWarningModule extends Module { - @Override - protected void configureModule() { - add( - ProjectsInWarningDaemon.class, - ProjectsInWarning.class - - ); - } -} diff --git a/server/sonar-webserver-core/src/main/java/org/sonar/server/qualitygate/package-info.java b/server/sonar-webserver-core/src/main/java/org/sonar/server/qualitygate/package-info.java deleted file mode 100644 index 6a28177f860..00000000000 --- a/server/sonar-webserver-core/src/main/java/org/sonar/server/qualitygate/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -@ParametersAreNonnullByDefault -package org.sonar.server.qualitygate; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/NotificationChannelTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/NotificationChannelTest.java index edd6354a881..28fe663e044 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/NotificationChannelTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/NotificationChannelTest.java @@ -21,7 +21,6 @@ package org.sonar.server.notification; import org.junit.Test; import org.sonar.api.notifications.Notification; -import org.sonar.api.notifications.NotificationChannel; import static org.assertj.core.api.Assertions.assertThat; diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/NotificationMediumTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/NotificationMediumTest.java index d12143eb3da..a146ddd9173 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/NotificationMediumTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/NotificationMediumTest.java @@ -26,7 +26,6 @@ import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.config.internal.Settings; import org.sonar.api.notifications.Notification; -import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/qualitygate/ProjectsInWarningDaemonTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/qualitygate/ProjectsInWarningDaemonTest.java deleted file mode 100644 index 41c36debff3..00000000000 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/qualitygate/ProjectsInWarningDaemonTest.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.qualitygate; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.slf4j.event.Level; -import org.sonar.api.config.internal.MapSettings; -import org.sonar.api.measures.CoreMetrics; -import org.sonar.api.measures.Metric; -import org.sonar.api.testfixtures.log.LogTester; -import org.sonar.api.utils.System2; -import org.sonar.api.utils.log.LoggerLevel; -import org.sonar.db.DbTester; -import org.sonar.db.component.ProjectData; -import org.sonar.db.metric.MetricDto; -import org.sonar.server.es.EsTester; -import org.sonar.server.measure.index.ProjectMeasuresIndex; -import org.sonar.server.measure.index.ProjectMeasuresIndexer; -import org.sonar.server.permission.index.PermissionIndexerTester; -import org.sonar.server.permission.index.WebAuthorizationTypeSupport; -import org.sonar.server.util.GlobalLockManager; -import org.sonar.server.util.GlobalLockManagerImpl; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.sonar.api.measures.Metric.Level.WARN; -import static org.sonar.db.measure.MeasureTesting.newLiveMeasure; -import static org.sonar.server.qualitygate.ProjectsInWarningDaemon.PROJECTS_IN_WARNING_INTERNAL_PROPERTY; - -public class ProjectsInWarningDaemonTest { - - @Rule - public DbTester db = DbTester.create(); - @Rule - public EsTester es = EsTester.create(); - @Rule - public LogTester logger = new LogTester().setLevel(LoggerLevel.DEBUG); - - private final PermissionIndexerTester authorizationIndexerTester = new PermissionIndexerTester(es, new ProjectMeasuresIndexer(db.getDbClient(), es.client())); - private final ProjectMeasuresIndexer projectMeasuresIndexer = new ProjectMeasuresIndexer(db.getDbClient(), es.client()); - private final ProjectMeasuresIndex projectMeasuresIndex = new ProjectMeasuresIndex(es.client(), new WebAuthorizationTypeSupport(null), System2.INSTANCE); - - private final MapSettings settings = new MapSettings(); - private final GlobalLockManager lockManager = mock(GlobalLockManagerImpl.class); - private final ProjectsInWarning projectsInWarning = new ProjectsInWarning(); - - private final ProjectsInWarningDaemon underTest = new ProjectsInWarningDaemon(db.getDbClient(), projectMeasuresIndex, settings.asConfig(), lockManager, projectsInWarning); - - @Before - public void setUp() { - settings.setProperty("sonar.projectsInWarning.frequencyInMilliseconds", "100"); - } - - @After - public void tearDown() { - underTest.stop(); - } - - @Test - public void store_projects_in_warning() throws InterruptedException { - allowLockToBeAcquired(); - MetricDto qualityGateStatus = insertQualityGateStatusMetric(); - insertProjectInWarning(qualityGateStatus); - insertProjectInWarning(qualityGateStatus); - // Setting does not exist - assertThat(db.getDbClient().internalPropertiesDao().selectByKey(db.getSession(), PROJECTS_IN_WARNING_INTERNAL_PROPERTY)).isEmpty(); - - underTest.notifyStart(); - - assertProjectsInWarningValue(2L); - assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is enabled."); - } - - @Test - public void update_projects_in_warning_when_new_project_in_warning() throws InterruptedException { - allowLockToBeAcquired(); - MetricDto qualityGateStatus = insertQualityGateStatusMetric(); - insertProjectInWarning(qualityGateStatus); - insertProjectInWarning(qualityGateStatus); - // Setting does not exist - assertThat(db.getDbClient().internalPropertiesDao().selectByKey(db.getSession(), PROJECTS_IN_WARNING_INTERNAL_PROPERTY)).isEmpty(); - - underTest.notifyStart(); - // Add a project in warning after the start in order to let the thread do his job - insertProjectInWarning(qualityGateStatus); - - assertProjectsInWarningValue(3L); - assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is enabled."); - } - - @Test - public void stop_thread_when_number_of_projects_in_warning_reach_zero() throws InterruptedException { - allowLockToBeAcquired(); - MetricDto qualityGateStatus = insertQualityGateStatusMetric(); - ProjectData project = insertProjectInWarning(qualityGateStatus); - - underTest.notifyStart(); - assertProjectsInWarningValue(1L); - // Set quality gate status of the project to OK => No more projects in warning - db.getDbClient().liveMeasureDao().insertOrUpdate(db.getSession(), - newLiveMeasure(project.getMainBranchComponent(), qualityGateStatus).setData(Metric.Level.OK.name()).setValue(null)); - db.commit(); - projectMeasuresIndexer.indexOnAnalysis(project.mainBranchUuid()); - - assertProjectsInWarningValue(0L); - assertThat(logger.logs(Level.INFO)) - .contains( - "Counting number of projects in warning is enabled.", - "Counting number of projects in warning will be disabled as there are no more projects in warning."); - } - - @Test - public void update_internal_properties_when_already_exits_and_projects_in_warnings_more_than_zero() throws InterruptedException { - allowLockToBeAcquired(); - MetricDto qualityGateStatus = insertQualityGateStatusMetric(); - insertProjectInWarning(qualityGateStatus); - insertProjectInWarning(qualityGateStatus); - // Setting contains 10, it should be updated with new value - db.getDbClient().internalPropertiesDao().save(db.getSession(), PROJECTS_IN_WARNING_INTERNAL_PROPERTY, "10"); - db.commit(); - - underTest.notifyStart(); - - assertProjectsInWarningValue(2L); - assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is enabled."); - } - - @Test - public void store_zero_projects_in_warning_when_no_projects() throws InterruptedException { - allowLockToBeAcquired(); - assertThat(db.getDbClient().internalPropertiesDao().selectByKey(db.getSession(), PROJECTS_IN_WARNING_INTERNAL_PROPERTY)).isEmpty(); - - underTest.notifyStart(); - - assertProjectsInWarningValue(0L); - assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is enabled."); - } - - @Test - public void do_not_compute_projects_in_warning_when_internal_property_is_zero() throws InterruptedException { - allowLockToBeAcquired(); - MetricDto qualityGateStatus = insertQualityGateStatusMetric(); - insertProjectInWarning(qualityGateStatus); - // Setting contains 0, even if there are projects in warning it will stay 0 (as it's not possible to have new projects in warning) - db.getDbClient().internalPropertiesDao().save(db.getSession(), PROJECTS_IN_WARNING_INTERNAL_PROPERTY, "0"); - db.commit(); - - underTest.notifyStart(); - - assertProjectsInWarningValue(0L); - assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is not started as there are no projects in this situation."); - } - - @Test - public void do_not_store_projects_in_warning_in_db_when_cannot_acquire_lock() throws InterruptedException { - when(lockManager.tryLock(any(), anyInt())).thenReturn(false); - MetricDto qualityGateStatus = insertQualityGateStatusMetric(); - insertProjectInWarning(qualityGateStatus); - - underTest.notifyStart(); - - waitForValueToBeComputed(1L); - assertThat(projectsInWarning.count()).isOne(); - assertThat(countNumberOfProjectsInWarning()).isZero(); - } - - private void waitForValueToBeComputed(long expectedValue) throws InterruptedException { - for (int i = 0; i < 1000; i++) { - if (projectsInWarning.isInitialized() && projectsInWarning.count() == expectedValue) { - break; - } - Thread.sleep(100); - } - } - - private void assertProjectsInWarningValue(long expectedValue) throws InterruptedException { - waitForValueToBeComputed(expectedValue); - assertThat(projectsInWarning.count()).isEqualTo(expectedValue); - assertThat(countNumberOfProjectsInWarning()).isEqualTo(expectedValue); - } - - private long countNumberOfProjectsInWarning() { - return db.getDbClient().internalPropertiesDao().selectByKey(db.getSession(), PROJECTS_IN_WARNING_INTERNAL_PROPERTY) - .map(Long::valueOf) - .orElse(0L); - } - - private ProjectData insertProjectInWarning(MetricDto qualityGateStatus) { - ProjectData project = db.components().insertPrivateProject(); - db.measures().insertLiveMeasure(project, qualityGateStatus, lm -> lm.setData(WARN.name()).setValue(null)); - authorizationIndexerTester.allowOnlyAnyone(project.getProjectDto()); - projectMeasuresIndexer.indexOnAnalysis(project.mainBranchUuid()); - return project; - } - - private MetricDto insertQualityGateStatusMetric() { - return db.measures().insertMetric(m -> m.setKey(CoreMetrics.ALERT_STATUS_KEY).setValueType(Metric.ValueType.LEVEL.name())); - } - - private void allowLockToBeAcquired() { - when(lockManager.tryLock(any(), anyInt())).thenReturn(true); - } - -} diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/qualitygate/ProjectsInWarningModuleTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/qualitygate/ProjectsInWarningModuleTest.java deleted file mode 100644 index 183698ebff7..00000000000 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/qualitygate/ProjectsInWarningModuleTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.qualitygate; - -import org.junit.Test; -import org.sonar.core.platform.ListContainer; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ProjectsInWarningModuleTest { - @Test - public void verify_count_of_added_components() { - ListContainer container = new ListContainer(); - new ProjectsInWarningModule().configure(container); - assertThat(container.getAddedObjects()).hasSize(2); - } -} diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/telemetry/FakeServer.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/telemetry/FakeServer.java index a430652afba..db106740b6a 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/telemetry/FakeServer.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/telemetry/FakeServer.java @@ -44,12 +44,6 @@ class FakeServer extends Server { return this; } - @CheckForNull - @Override - public String getPermanentServerId() { - return null; - } - @Override public String getVersion() { return this.version; @@ -74,10 +68,4 @@ class FakeServer extends Server { public String getPublicRootUrl() { return null; } - - @Override - public boolean isSecured() { - return false; - } - } diff --git a/server/sonar-webserver-es/src/main/java/org/sonar/server/measure/index/ProjectMeasuresIndex.java b/server/sonar-webserver-es/src/main/java/org/sonar/server/measure/index/ProjectMeasuresIndex.java index b213bcfa800..11dd647e800 100644 --- a/server/sonar-webserver-es/src/main/java/org/sonar/server/measure/index/ProjectMeasuresIndex.java +++ b/server/sonar-webserver-es/src/main/java/org/sonar/server/measure/index/ProjectMeasuresIndex.java @@ -55,7 +55,6 @@ import org.elasticsearch.search.aggregations.metrics.Sum; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.NestedSortBuilder; -import org.sonar.api.measures.Metric; import org.sonar.api.resources.Qualifiers; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.System2; @@ -354,13 +353,12 @@ public class ProjectMeasuresIndex { .subAggregation(rangeAgg)); } - private static AbstractAggregationBuilder createQualityGateFacet(ProjectMeasuresQuery projectMeasuresQuery) { + private static AbstractAggregationBuilder createQualityGateFacet() { return filters( ALERT_STATUS_KEY, QUALITY_GATE_STATUS .entrySet() .stream() - .filter(qgs -> !(projectMeasuresQuery.isIgnoreWarning() && qgs.getKey().equals(Metric.Level.WARN.name()))) .map(entry -> new KeyedFilter(entry.getKey(), termQuery(FIELD_QUALITY_GATE_STATUS, entry.getValue()))) .toArray(KeyedFilter[]::new)); } @@ -462,7 +460,7 @@ public class ProjectMeasuresIndex { TermsAggregationBuilder tagFacet = AggregationBuilders.terms(FIELD_TAGS) .field(FIELD_TAGS) - .size(size*page) + .size(size * page) .minDocCount(1) .order(BucketOrder.key(true)); if (textQuery != null) { @@ -480,7 +478,7 @@ public class ProjectMeasuresIndex { Terms aggregation = response.getAggregations().get(FIELD_TAGS); return aggregation.getBuckets().stream() - .skip((page-1) * size) + .skip((page - 1) * size) .map(Bucket::getKeyAsString) .toList(); } @@ -611,7 +609,7 @@ public class ProjectMeasuresIndex { return topAggregationHelper.buildTopAggregation( facet.getName(), facet.getTopAggregationDef(), NO_EXTRA_FILTER, - t -> t.subAggregation(createQualityGateFacet(query))); + t -> t.subAggregation(createQualityGateFacet())); } private static FilterAggregationBuilder buildTagsFacet(Facet facet, ProjectMeasuresQuery query, TopAggregationHelper topAggregationHelper) { diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java index dbcedbbc490..92a6654a190 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java @@ -61,7 +61,6 @@ import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY; import static org.sonar.api.measures.Metric.Level.ERROR; import static org.sonar.api.measures.Metric.Level.OK; -import static org.sonar.api.measures.Metric.Level.WARN; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; @@ -1145,8 +1144,7 @@ public class ProjectMeasuresIndexTest { assertThat(result).containsOnly( entry(ERROR.name(), 4L), - entry(OK.name(), 2L), - entry(WARN.name(), 0L)); + entry(OK.name(), 2L)); } @Test @@ -1169,8 +1167,7 @@ public class ProjectMeasuresIndexTest { // Sticky facet on quality gate does not take into account quality gate filter assertThat(facets.get(ALERT_STATUS_KEY)).containsOnly( entry(OK.name(), 2L), - entry(ERROR.name(), 3L), - entry(WARN.name(), 0L)); + entry(ERROR.name(), 3L)); // But facet on ncloc does well take into into filters assertThat(facets.get(NCLOC)).containsExactly( entry("*-1000.0", 1L), @@ -1201,54 +1198,7 @@ public class ProjectMeasuresIndexTest { assertThat(result).containsOnly( entry(ERROR.name(), 0L), - entry(OK.name(), 2L), - entry(WARN.name(), 0L)); - } - - @Test - public void facet_quality_gate_using_deprecated_warning() { - index( - // 2 docs with QG OK - newDoc().setQualityGateStatus(OK.name()), - newDoc().setQualityGateStatus(OK.name()), - // 3 docs with QG WARN - newDoc().setQualityGateStatus(WARN.name()), - newDoc().setQualityGateStatus(WARN.name()), - newDoc().setQualityGateStatus(WARN.name()), - // 4 docs with QG ERROR - newDoc().setQualityGateStatus(ERROR.name()), - newDoc().setQualityGateStatus(ERROR.name()), - newDoc().setQualityGateStatus(ERROR.name()), - newDoc().setQualityGateStatus(ERROR.name())); - - LinkedHashMap result = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(ALERT_STATUS_KEY)).getFacets().get(ALERT_STATUS_KEY); - - assertThat(result).containsOnly( - entry(ERROR.name(), 4L), - entry(WARN.name(), 3L), - entry(OK.name(), 2L)); - } - - @Test - public void facet_quality_gate_does_not_return_deprecated_warning_when_set_ignore_warning_is_true() { - index( - // 2 docs with QG OK - newDoc().setQualityGateStatus(OK.name()), - newDoc().setQualityGateStatus(OK.name()), - // 4 docs with QG ERROR - newDoc().setQualityGateStatus(ERROR.name()), - newDoc().setQualityGateStatus(ERROR.name()), - newDoc().setQualityGateStatus(ERROR.name()), - newDoc().setQualityGateStatus(ERROR.name())); - - assertThat(underTest.search(new ProjectMeasuresQuery().setIgnoreWarning(true), new SearchOptions().addFacets(ALERT_STATUS_KEY)).getFacets().get(ALERT_STATUS_KEY)).containsOnly( - entry(ERROR.name(), 4L), entry(OK.name(), 2L)); - assertThat(underTest.search(new ProjectMeasuresQuery().setIgnoreWarning(false), new SearchOptions().addFacets(ALERT_STATUS_KEY)).getFacets().get(ALERT_STATUS_KEY)) - .containsOnly( - entry(ERROR.name(), 4L), - entry(WARN.name(), 0L), - entry(OK.name(), 2L)); } @Test @@ -1466,8 +1416,7 @@ public class ProjectMeasuresIndexTest { entry("cpp", 1L)); assertThat(facets.get(ALERT_STATUS_KEY)).containsOnly( entry(OK.name(), 0L), - entry(ERROR.name(), 1L), - entry(WARN.name(), 0L)); + entry(ERROR.name(), 1L)); } @Test diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/badge/ws/MeasureActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/badge/ws/MeasureActionIT.java index 294e1b9dc5c..9faea7038c7 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/badge/ws/MeasureActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/badge/ws/MeasureActionIT.java @@ -64,7 +64,6 @@ import static org.sonar.api.measures.CoreMetrics.SQALE_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_KEY; import static org.sonar.api.measures.Metric.Level.ERROR; import static org.sonar.api.measures.Metric.Level.OK; -import static org.sonar.api.measures.Metric.Level.WARN; import static org.sonar.api.measures.Metric.ValueType.INT; import static org.sonar.api.measures.Metric.ValueType.LEVEL; import static org.sonar.api.measures.Metric.ValueType.PERCENT; @@ -75,7 +74,6 @@ import static org.sonar.db.component.BranchType.BRANCH; import static org.sonar.server.badge.ws.SvgGenerator.Color.DEFAULT; import static org.sonar.server.badge.ws.SvgGenerator.Color.QUALITY_GATE_ERROR; import static org.sonar.server.badge.ws.SvgGenerator.Color.QUALITY_GATE_OK; -import static org.sonar.server.badge.ws.SvgGenerator.Color.QUALITY_GATE_WARN; @RunWith(DataProviderRunner.class) public class MeasureActionIT { @@ -239,23 +237,6 @@ public class MeasureActionIT { } - @Test - public void display_deprecated_warning_quality_gate() { - ProjectData projectData = db.components().insertPublicProject(); - ComponentDto project = projectData.getMainBranchComponent(); - - userSession.registerProjects(projectData.getProjectDto()); - MetricDto metric = createQualityGateMetric(); - db.measures().insertLiveMeasure(project, metric, m -> m.setData(WARN.name())); - - TestResponse response = ws.newRequest() - .setParam("project", project.getKey()) - .setParam("metric", metric.getKey()) - .execute(); - - checkSvg(response, "quality gate", "warning", QUALITY_GATE_WARN); - } - @Test public void measure_on_non_main_branch() { ProjectData projectData = db.components().insertPublicProject(p -> p.setPrivate(false)); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/SearchProjectsActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/SearchProjectsActionIT.java index 2f4556a9672..16d0c715ee7 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/SearchProjectsActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/SearchProjectsActionIT.java @@ -61,7 +61,6 @@ import org.sonar.server.measure.index.ProjectMeasuresIndex; import org.sonar.server.measure.index.ProjectMeasuresIndexer; import org.sonar.server.permission.index.PermissionIndexerTester; import org.sonar.server.permission.index.WebAuthorizationTypeSupport; -import org.sonar.server.qualitygate.ProjectsInWarning; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; @@ -167,18 +166,12 @@ public class SearchProjectsActionIT { private PermissionIndexerTester authorizationIndexerTester = new PermissionIndexerTester(es, new ProjectMeasuresIndexer(dbClient, es.client())); private ProjectMeasuresIndex index = new ProjectMeasuresIndex(es.client(), new WebAuthorizationTypeSupport(userSession), System2.INSTANCE); private ProjectMeasuresIndexer projectMeasuresIndexer = new ProjectMeasuresIndexer(db.getDbClient(), es.client()); - private ProjectsInWarning projectsInWarning = new ProjectsInWarning(); - private WsActionTester ws = new WsActionTester(new SearchProjectsAction(dbClient, index, userSession, projectsInWarning, editionProviderMock, + private WsActionTester ws = new WsActionTester(new SearchProjectsAction(dbClient, index, userSession, editionProviderMock, new IssueIndexSyncProgressChecker(db.getDbClient()))); private RequestBuilder request = SearchProjectsRequest.builder(); - @Before - public void setUp() { - projectsInWarning.update(0L); - } - @Test public void verify_definition() { WebService.Action def = ws.getDef(); @@ -1080,9 +1073,7 @@ public class SearchProjectsActionIT { MetricDto qualityGateStatus = db.measures().insertMetric(c -> c.setKey(ALERT_STATUS_KEY).setValueType(LEVEL.name())); insertProject(new Measure(qualityGateStatus, c -> c.setData(Metric.Level.ERROR.name()).setValue(null))); insertProject(new Measure(qualityGateStatus, c -> c.setData(Metric.Level.ERROR.name()).setValue(null))); - insertProject(new Measure(qualityGateStatus, c -> c.setData(Metric.Level.WARN.name()).setValue(null))); insertProject(new Measure(qualityGateStatus, c -> c.setData(Metric.Level.OK.name()).setValue(null))); - projectsInWarning.update(1L); index(); SearchProjectsWsResponse result = call(request.setFacets(singletonList(ALERT_STATUS_KEY))); @@ -1094,8 +1085,7 @@ public class SearchProjectsActionIT { .extracting(Common.FacetValue::getVal, Common.FacetValue::getCount) .containsOnly( tuple("OK", 1L), - tuple("ERROR", 2L), - tuple("WARN", 1L)); + tuple("ERROR", 2L)); } @Test @@ -1105,7 +1095,6 @@ public class SearchProjectsActionIT { insertProject(new Measure(qualityGateStatus, c -> c.setData(Metric.Level.ERROR.name()).setValue(null))); insertProject(new Measure(qualityGateStatus, c -> c.setData(Metric.Level.ERROR.name()).setValue(null))); insertProject(new Measure(qualityGateStatus, c -> c.setData(Metric.Level.OK.name()).setValue(null))); - projectsInWarning.update(0L); index(); SearchProjectsWsResponse result = call(request.setFacets(singletonList(ALERT_STATUS_KEY))); @@ -1293,25 +1282,6 @@ public class SearchProjectsActionIT { .containsExactlyInAnyOrder(project.getKey()); } - @Test - public void use_deprecated_warning_quality_gate_in_filter() { - userSession.logIn(); - MetricDto qualityGateStatus = db.measures().insertMetric(c -> c.setKey(QUALITY_GATE_STATUS).setValueType(LEVEL.name())); - ComponentDto project1 = insertProject(c -> c.setName("Sonar Java"), new Measure(qualityGateStatus, c -> c.setValue(null).setData("ERROR"))); - ComponentDto project2 = insertProject(c -> c.setName("Sonar Groovy"), new Measure(qualityGateStatus, c -> c.setValue(null).setData("WARN"))); - ComponentDto project3 = insertProject(c -> c.setName("Sonar Markdown"), new Measure(qualityGateStatus, c -> c.setValue(null).setData("WARN"))); - ComponentDto project4 = insertProject(c -> c.setName("Sonar Qube"), new Measure(qualityGateStatus, c -> c.setValue(null).setData("OK"))); - index(); - - List projects = call(request - .setFilter("alert_status = WARN")) - .getComponentsList(); - - assertThat(projects) - .extracting(Component::getKey) - .containsExactly(project2.getKey(), project3.getKey()); - } - @Test public void fail_when_filter_metrics_are_unknown() { userSession.logIn(); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/AddActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/AddActionIT.java index 7e3c51bd701..95daf2d9739 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/AddActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/AddActionIT.java @@ -23,7 +23,6 @@ import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.notifications.Notification; -import org.sonar.api.notifications.NotificationChannel; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; @@ -34,6 +33,7 @@ import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; +import org.sonar.server.notification.NotificationChannel; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/ListActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/ListActionIT.java index 4944278afca..b6980787350 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/ListActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/ListActionIT.java @@ -21,7 +21,6 @@ package org.sonar.server.notification.ws; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; @@ -32,6 +31,7 @@ import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; +import org.sonar.server.notification.NotificationChannel; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/RemoveActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/RemoveActionIT.java index aa0f0100dd1..30a1efc0445 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/RemoveActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/RemoveActionIT.java @@ -22,7 +22,6 @@ package org.sonar.server.notification.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.notifications.Notification; -import org.sonar.api.notifications.NotificationChannel; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; @@ -34,6 +33,7 @@ import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; +import org.sonar.server.notification.NotificationChannel; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.notification.ws.RemoveAction.RemoveRequest; import org.sonar.server.tester.UserSessionRule; diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/ListDefinitionsActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/ListDefinitionsActionIT.java index 4fc97352a34..2566944b320 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/ListDefinitionsActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/ListDefinitionsActionIT.java @@ -226,21 +226,6 @@ public class ListDefinitionsActionIT { assertThat(definition.getFields(1).getOptionsList()).containsExactly("one", "two"); } - @Test - public void return_license_type_in_property_set() { - logIn(); - propertyDefinitions.addComponent(PropertyDefinition - .builder("foo") - .type(PropertyType.PROPERTY_SET) - .fields(PropertyFieldDefinition.build("license").name("License").type(PropertyType.LICENSE).build()) - .build()); - - ListDefinitionsWsResponse result = executeRequest(); - - assertThat(result.getDefinitionsList()).hasSize(1); - assertThat(result.getDefinitions(0).getFieldsList()).extracting(Settings.Field::getKey, Settings.Field::getType).containsOnly(tuple("license", LICENSE)); - } - @Test public void return_global_settings_definitions() { logIn(); @@ -314,19 +299,6 @@ public class ListDefinitionsActionIT { assertThat(result.getDefinitionsList()).isEmpty(); } - @Test - public void return_license_type() { - logInAsAdmin(); - propertyDefinitions.addComponents(asList( - PropertyDefinition.builder("plugin.license.secured").type(PropertyType.LICENSE).build(), - PropertyDefinition.builder("commercial.plugin").type(PropertyType.LICENSE).build())); - - ListDefinitionsWsResponse result = executeRequest(); - - assertThat(result.getDefinitionsList()).extracting(Definition::getKey, Definition::getType) - .containsOnly(tuple("plugin.license.secured", LICENSE), tuple("commercial.plugin", LICENSE)); - } - @Test public void does_not_returned_secured_and_license_settings_when_not_authenticated() { propertyDefinitions.addComponents(asList( diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/SetActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/SetActionIT.java index a7d893ff04e..38700bccd84 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/SetActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/SetActionIT.java @@ -345,27 +345,6 @@ public class SetActionIT { assertThat(settingsChangeNotifier.wasCalled).isFalse(); } - @Test - public void persist_multi_value_with_type_metric() { - definitions.addComponent(PropertyDefinition - .builder("my_key") - .name("foo") - .description("desc") - .category("cat") - .subCategory("subCat") - .type(PropertyType.METRIC) - .defaultValue("default") - .multiValues(true) - .build()); - dbClient.metricDao().insert(dbSession, newMetricDto().setKey("metric_key_1")); - dbClient.metricDao().insert(dbSession, newMetricDto().setKey("metric_key_2")); - dbSession.commit(); - - callForMultiValueGlobalSetting("my_key", List.of("metric_key_1", "metric_key_2")); - - assertGlobalSetting("my_key", "metric_key_1,metric_key_2"); - } - @Test public void persist_multi_value_with_type_logIn() { definitions.addComponent(PropertyDefinition @@ -701,28 +680,6 @@ public class SetActionIT { .hasMessage("Not an integer error message"); } - @Test - public void fail_when_data_and_metric_type_with_invalid_key() { - definitions.addComponent(PropertyDefinition - .builder("my_key") - .name("foo") - .description("desc") - .category("cat") - .subCategory("subCat") - .type(PropertyType.METRIC) - .defaultValue("default") - .multiValues(true) - .build()); - dbClient.metricDao().insert(dbSession, newMetricDto().setKey("metric_key")); - dbClient.metricDao().insert(dbSession, newMetricDto().setKey("metric_disabled_key").setEnabled(false)); - dbSession.commit(); - - List values = List.of("metric_key", "metric_disabled_key"); - assertThatThrownBy(() -> callForMultiValueGlobalSetting("my_key", values)) - .isInstanceOf(BadRequestException.class) - .hasMessage("Error when validating metric setting with key 'my_key' and values [metric_key, metric_disabled_key]. A value is not a valid metric key."); - } - @Test public void fail_when_data_and_login_type_with_invalid_logIn() { definitions.addComponent(PropertyDefinition diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/MeasureAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/MeasureAction.java index ce582924956..71ce0d3d312 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/MeasureAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/MeasureAction.java @@ -59,10 +59,9 @@ import static org.sonar.api.measures.CoreMetrics.SQALE_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_KEY; import static org.sonar.api.measures.CoreMetrics.VULNERABILITIES_KEY; import static org.sonar.api.measures.Metric.Level; -import static org.sonar.api.measures.Metric.ValueType; import static org.sonar.api.measures.Metric.Level.ERROR; import static org.sonar.api.measures.Metric.Level.OK; -import static org.sonar.api.measures.Metric.Level.WARN; +import static org.sonar.api.measures.Metric.ValueType; import static org.sonar.server.badge.ws.ETagUtils.RFC1123_DATE; import static org.sonar.server.badge.ws.ETagUtils.getETag; import static org.sonar.server.badge.ws.SvgFormatter.formatDuration; @@ -97,12 +96,10 @@ public class MeasureAction implements ProjectBadgesWsAction { private static final Map QUALITY_GATE_MESSAGE_BY_STATUS = new EnumMap<>(Map.of( OK, "passed", - WARN, "warning", ERROR, "failed")); private static final Map COLOR_BY_QUALITY_GATE_STATUS = new EnumMap<>(Map.of( OK, Color.QUALITY_GATE_OK, - WARN, Color.QUALITY_GATE_WARN, ERROR, Color.QUALITY_GATE_ERROR)); private static final Map COLOR_BY_RATING = new EnumMap<>(Map.of( diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/SvgGenerator.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/SvgGenerator.java index d6fe8ad0993..162e7bc97c0 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/SvgGenerator.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/SvgGenerator.java @@ -32,7 +32,6 @@ import static java.lang.String.valueOf; import static java.nio.charset.StandardCharsets.UTF_8; import static org.sonar.api.measures.Metric.Level.ERROR; import static org.sonar.api.measures.Metric.Level.OK; -import static org.sonar.api.measures.Metric.Level.WARN; @ServerSide public class SvgGenerator { @@ -132,7 +131,6 @@ public class SvgGenerator { this.badgeTemplate = readTemplate(TEMPLATES_PATH + "/badge.svg"); this.qualityGateTemplates = Map.of( OK, readTemplate(TEMPLATES_PATH + "/quality_gate_passed.svg"), - WARN, readTemplate(TEMPLATES_PATH + "/quality_gate_warn.svg"), ERROR, readTemplate(TEMPLATES_PATH + "/quality_gate_failed.svg")); } @@ -190,7 +188,6 @@ public class SvgGenerator { static class Color { static final Color DEFAULT = new Color("#999999"); static final Color QUALITY_GATE_OK = new Color("#00aa00"); - static final Color QUALITY_GATE_WARN = new Color("#ed7d20"); static final Color QUALITY_GATE_ERROR = new Color("#d4333f"); static final Color RATING_A = new Color("#00aa00"); static final Color RATING_B = new Color("#b0d513"); diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/SearchProjectsAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/SearchProjectsAction.java index 63e8c56a10f..d3ea6366c0f 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/SearchProjectsAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/SearchProjectsAction.java @@ -64,7 +64,6 @@ import org.sonar.server.issue.index.IssueIndexSyncProgressChecker; import org.sonar.server.measure.index.ProjectMeasuresIndex; import org.sonar.server.measure.index.ProjectMeasuresQuery; import org.sonar.server.project.Visibility; -import org.sonar.server.qualitygate.ProjectsInWarning; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Common; import org.sonarqube.ws.Components.Component; @@ -108,16 +107,14 @@ public class SearchProjectsAction implements ComponentsWsAction { private final DbClient dbClient; private final ProjectMeasuresIndex index; private final UserSession userSession; - private final ProjectsInWarning projectsInWarning; private final PlatformEditionProvider editionProvider; private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker; - public SearchProjectsAction(DbClient dbClient, ProjectMeasuresIndex index, UserSession userSession, ProjectsInWarning projectsInWarning, + public SearchProjectsAction(DbClient dbClient, ProjectMeasuresIndex index, UserSession userSession, PlatformEditionProvider editionProvider, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker) { this.dbClient = dbClient; this.index = index; this.userSession = userSession; - this.projectsInWarning = projectsInWarning; this.editionProvider = editionProvider; this.issueIndexSyncProgressChecker = issueIndexSyncProgressChecker; } @@ -231,7 +228,6 @@ public class SearchProjectsAction implements ComponentsWsAction { Set favoriteProjectUuids = loadFavoriteProjectUuids(dbSession); List criteria = FilterParser.parse(firstNonNull(request.getFilter(), "")); ProjectMeasuresQuery query = newProjectMeasuresQuery(criteria, hasFavoriteFilter(criteria) ? favoriteProjectUuids : null) - .setIgnoreWarning(projectsInWarning.count() == 0L) .setSort(request.getSort()) .setAsc(request.getAsc()); diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/AddAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/AddAction.java index a67178a38d9..b88acaeba54 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/AddAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/AddAction.java @@ -21,7 +21,6 @@ package org.sonar.server.notification.ws; import java.util.List; import java.util.Optional; -import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; @@ -32,6 +31,7 @@ import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.issue.notification.MyNewIssuesNotificationHandler; +import org.sonar.server.notification.NotificationChannel; import org.sonar.server.notification.email.EmailNotificationChannel; import org.sonar.server.user.UserSession; import org.sonar.server.ws.KeyExamples; diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/ListAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/ListAction.java index 27a0d0e3f6d..3f19b6571c9 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/ListAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/ListAction.java @@ -29,7 +29,6 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; import java.util.stream.Collectors; -import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; @@ -40,6 +39,7 @@ import org.sonar.db.entity.EntityDto; import org.sonar.db.property.PropertyDto; import org.sonar.db.property.PropertyQuery; import org.sonar.db.user.UserDto; +import org.sonar.server.notification.NotificationChannel; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Notifications.ListResponse; import org.sonarqube.ws.Notifications.Notification; @@ -118,7 +118,8 @@ public class ListAction implements NotificationsWsAction { private UnaryOperator addNotifications(DbSession dbSession, UserDto user) { return response -> { - List properties = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder().setUserUuid(user.getUuid()).build(), dbSession); + List properties = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder().setUserUuid(user.getUuid()).build(), + dbSession); Map entitiesByUuid = searchProjects(dbSession, properties); Predicate isNotification = prop -> prop.getKey().startsWith("notification."); @@ -158,14 +159,16 @@ public class ListAction implements NotificationsWsAction { .map(PropertyDto::getEntityUuid) .filter(Objects::nonNull) .collect(Collectors.toSet()); - Set authorizedProjectUuids = dbClient.authorizationDao().keepAuthorizedEntityUuids(dbSession, entityUuids, userSession.getUuid(), UserRole.USER); + Set authorizedProjectUuids = dbClient.authorizationDao().keepAuthorizedEntityUuids(dbSession, entityUuids, + userSession.getUuid(), UserRole.USER); return dbClient.entityDao().selectByUuids(dbSession, entityUuids) .stream() .filter(c -> authorizedProjectUuids.contains(c.getUuid())) .collect(Collectors.toMap(EntityDto::getUuid, Function.identity())); } - private static Function toWsNotification(Notification.Builder notification, Map projectsByUuid) { + private static Function toWsNotification(Notification.Builder notification, + Map projectsByUuid) { return property -> { notification.clear(); List propertyKey = Splitter.on(".").splitToList(property.getKey()); diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/NotificationCenter.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/NotificationCenter.java index 10023f09c03..a2ca8d78f3f 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/NotificationCenter.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/NotificationCenter.java @@ -23,9 +23,9 @@ import com.google.common.collect.ImmutableList; import java.util.Arrays; import java.util.List; import javax.annotation.Nullable; -import org.sonar.api.notifications.NotificationChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.sonar.server.notification.NotificationChannel; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.springframework.beans.factory.annotation.Autowired; diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/RemoveAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/RemoveAction.java index dd9ee79cf83..19c29bec85d 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/RemoveAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/RemoveAction.java @@ -22,7 +22,6 @@ package org.sonar.server.notification.ws; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; -import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; @@ -32,6 +31,7 @@ import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.issue.notification.MyNewIssuesNotificationHandler; +import org.sonar.server.notification.NotificationChannel; import org.sonar.server.notification.email.EmailNotificationChannel; import org.sonar.server.user.UserSession; import org.sonar.server.ws.KeyExamples; diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingValidations.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingValidations.java index bf30d61bd81..ca9b757c357 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingValidations.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingValidations.java @@ -128,9 +128,7 @@ public class SettingValidations { return; } - if (definition.type() == PropertyType.METRIC) { - validateMetric(data); - } else if (definition.type() == PropertyType.USER_LOGIN) { + if (definition.type() == PropertyType.USER_LOGIN) { validateLogin(data); } else if (definition.type() == PropertyType.JSON) { validateJson(data, definition); diff --git a/server/sonar-webserver-webapi/src/main/resources/org/sonar/server/badge/ws/templates/sonarqube/quality_gate_warn.svg b/server/sonar-webserver-webapi/src/main/resources/org/sonar/server/badge/ws/templates/sonarqube/quality_gate_warn.svg deleted file mode 100644 index a0c22703d15..00000000000 --- a/server/sonar-webserver-webapi/src/main/resources/org/sonar/server/badge/ws/templates/sonarqube/quality_gate_warn.svg +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/SvgGeneratorTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/SvgGeneratorTest.java index 9ebf61ef34e..cb89fd0cb2c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/SvgGeneratorTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/SvgGeneratorTest.java @@ -28,7 +28,6 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.measures.Metric.Level.ERROR; -import static org.sonar.api.measures.Metric.Level.WARN; import static org.sonar.server.badge.ws.SvgGenerator.Color.DEFAULT; public class SvgGeneratorTest { @@ -53,15 +52,6 @@ public class SvgGeneratorTest { checkQualityGate(result, ERROR); } - @Test - public void generate_deprecated_warning_quality_gate() { - initSvgGenerator(); - - String result = underTest.generateQualityGate(WARN); - - assertThat(result).isEqualTo(readTemplate("quality_gate_warn.svg")); - } - @Test public void generate_error() { initSvgGenerator(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/DispatchersImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/DispatchersImplTest.java index 5d500178f0c..b28319dcc35 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/DispatchersImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/DispatchersImplTest.java @@ -20,10 +20,10 @@ package org.sonar.server.notification.ws; import org.junit.Test; -import org.sonar.api.notifications.NotificationChannel; import org.sonar.server.issue.notification.FPOrWontFixNotificationHandler; import org.sonar.server.issue.notification.MyNewIssuesNotificationHandler; import org.sonar.server.issue.notification.NewIssuesNotificationHandler; +import org.sonar.server.notification.NotificationChannel; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.qualitygate.notification.QGChangeNotificationHandler; diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/NotificationCenterTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/NotificationCenterTest.java index a7bbd327456..47b169ddd25 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/NotificationCenterTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/NotificationCenterTest.java @@ -21,7 +21,7 @@ package org.sonar.server.notification.ws; import org.junit.Before; import org.junit.Test; -import org.sonar.api.notifications.NotificationChannel; +import org.sonar.server.notification.NotificationChannel; import org.sonar.server.notification.NotificationDispatcherMetadata; import static org.assertj.core.api.Assertions.assertThat; @@ -41,9 +41,9 @@ public class NotificationCenterTest { NotificationDispatcherMetadata metadata3 = NotificationDispatcherMetadata.create("Dispatcher3").setProperty("global", "FOO").setProperty("on-project", "BAR"); underTest = new NotificationCenter( - new NotificationDispatcherMetadata[] {metadata1, metadata2, metadata3}, - new NotificationChannel[] {emailChannel, gtalkChannel} - ); + new NotificationDispatcherMetadata[] {metadata1, metadata2, metadata3}, + new NotificationChannel[] {emailChannel, gtalkChannel} + ); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/StatusActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/StatusActionTest.java index eb3a91b8867..2079f48131d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/StatusActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/StatusActionTest.java @@ -194,15 +194,5 @@ public class StatusActionTest { public String getPublicRootUrl() { throw new UnsupportedOperationException(); } - - @Override - public boolean isSecured() { - throw new UnsupportedOperationException(); - } - - @Override - public String getPermanentServerId() { - throw new UnsupportedOperationException(); - } } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/util/TypeValidationsTesting.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/util/TypeValidationsTesting.java index 75299650048..c86389c72b0 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/util/TypeValidationsTesting.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/util/TypeValidationsTesting.java @@ -30,11 +30,9 @@ public class TypeValidationsTesting { return new TypeValidations(Arrays.asList( new BooleanTypeValidation(), new IntegerTypeValidation(), - new LongTypeValidation(), new FloatTypeValidation(), new StringTypeValidation(), - new StringListTypeValidation(), - new MetricLevelTypeValidation() + new StringListTypeValidation() )); } } diff --git a/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java b/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java index 6c82a7168cf..9bd052497f4 100644 --- a/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java +++ b/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java @@ -34,10 +34,7 @@ import org.sonar.alm.client.github.config.GithubProvisioningConfigValidator; import org.sonar.alm.client.github.security.GithubAppSecurityImpl; import org.sonar.alm.client.gitlab.GitlabGlobalSettingsValidator; import org.sonar.alm.client.gitlab.GitlabHttpClient; -import org.sonar.api.profiles.XMLProfileParser; -import org.sonar.api.profiles.XMLProfileSerializer; import org.sonar.api.resources.ResourceTypes; -import org.sonar.api.rules.AnnotationRuleParser; import org.sonar.api.server.rule.RulesDefinitionXmlLoader; import org.sonar.auth.bitbucket.BitbucketModule; import org.sonar.auth.github.GitHubModule; @@ -130,7 +127,6 @@ import org.sonar.server.management.DelegatingManagedServices; import org.sonar.server.measure.index.ProjectsEsModule; import org.sonar.server.measure.live.LiveMeasureModule; import org.sonar.server.measure.ws.MeasuresWsModule; -import org.sonar.server.metric.MetricFinder; import org.sonar.server.metric.UnanalyzedLanguageMetrics; import org.sonar.server.metric.ws.MetricsWsModule; import org.sonar.server.monitoring.ComputeEngineMetricStatusTask; @@ -198,7 +194,6 @@ import org.sonar.server.pushapi.ServerPushModule; import org.sonar.server.pushapi.hotspots.HotspotChangeEventServiceImpl; import org.sonar.server.pushapi.issues.IssueChangeEventServiceImpl; import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventServiceImpl; -import org.sonar.server.qualitygate.ProjectsInWarningModule; import org.sonar.server.qualitygate.QualityGateModule; import org.sonar.server.qualitygate.notification.QGChangeNotificationHandler; import org.sonar.server.qualitygate.ws.QualityGateWsModule; @@ -318,8 +313,6 @@ public class PlatformLevel4 extends PlatformLevel { // quality profile BuiltInQProfileRepositoryImpl.class, ActiveRuleIndexer.class, - XMLProfileParser.class, - XMLProfileSerializer.class, QProfileComparison.class, QProfileTreeImpl.class, QProfileRulesImpl.class, @@ -336,7 +329,6 @@ public class PlatformLevel4 extends PlatformLevel { // rule RuleIndexDefinition.class, RuleIndexer.class, - AnnotationRuleParser.class, WebServerRuleFinderImpl.class, RuleDefinitionsLoader.class, RulesDefinitionXmlLoader.class, @@ -366,11 +358,9 @@ public class PlatformLevel4 extends PlatformLevel { // measure new MetricsWsModule(), new MeasuresWsModule(), - MetricFinder.class, UnanalyzedLanguageMetrics.class, new QualityGateModule(), - new ProjectsInWarningModule(), new QualityGateWsModule(), // web services diff --git a/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevelStartup.java b/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevelStartup.java index 3cd30ccb4c3..f25523ff456 100644 --- a/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevelStartup.java +++ b/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevelStartup.java @@ -30,13 +30,12 @@ import org.sonar.server.platform.ServerLifecycleNotifier; import org.sonar.server.platform.web.RegisterServletFilters; import org.sonar.server.plugins.DetectPluginChange; import org.sonar.server.plugins.PluginConsentVerifier; -import org.sonar.server.qualitygate.ProjectsInWarningDaemon; import org.sonar.server.qualitygate.RegisterQualityGates; +import org.sonar.server.qualityprofile.RegisterQualityProfiles; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileInsertImpl; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileLoader; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileUpdateImpl; import org.sonar.server.qualityprofile.builtin.BuiltInQualityProfilesUpdateListener; -import org.sonar.server.qualityprofile.RegisterQualityProfiles; import org.sonar.server.rule.AdvancedRuleDescriptionSectionsGenerator; import org.sonar.server.rule.LegacyHotspotRuleDescriptionSectionsGenerator; import org.sonar.server.rule.LegacyIssueRuleDescriptionSectionsGenerator; @@ -91,7 +90,7 @@ public class PlatformLevelStartup extends PlatformLevel { // RegisterServletFilters makes the WebService engine of Level4 served by the MasterServletFilter, therefore it // must be started after all the other startup tasks RegisterServletFilters.class - ); + ); } /** @@ -126,8 +125,6 @@ public class PlatformLevelStartup extends PlatformLevel { protected void doPrivileged() { PlatformLevelStartup.super.start(); getOptional(IndexerStartupTask.class).ifPresent(IndexerStartupTask::execute); - // Need to be executed after indexing as it executes an ES query - get(ProjectsInWarningDaemon.class).notifyStart(); get(ServerLifecycleNotifier.class).notifyStart(); get(ProcessCommandWrapper.class).notifyOperational(); get(WebServerRuleFinder.class).stopCaching(); diff --git a/sonar-core/src/main/java/org/sonar/core/issue/DefaultIssue.java b/sonar-core/src/main/java/org/sonar/core/issue/DefaultIssue.java index ffe5f42d7b9..abfa4154554 100644 --- a/sonar-core/src/main/java/org/sonar/core/issue/DefaultIssue.java +++ b/sonar-core/src/main/java/org/sonar/core/issue/DefaultIssue.java @@ -42,7 +42,6 @@ import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.sonar.api.code.CodeCharacteristic; import org.sonar.api.issue.Issue; -import org.sonar.api.issue.IssueComment; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.Severity; import org.sonar.api.rules.RuleType; @@ -604,15 +603,6 @@ public class DefaultIssue implements Issue, Trackable, org.sonar.api.ce.measure. return this; } - /** - * @deprecated since 7.2, comments are not more available - */ - @Override - @Deprecated - public List comments() { - return Collections.emptyList(); - } - public List defaultIssueComments() { if (comments == null) { return Collections.emptyList(); diff --git a/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/DefaultRules.java b/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/DefaultRules.java deleted file mode 100644 index 3ee93b19745..00000000000 --- a/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/DefaultRules.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.rule.internal; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import javax.annotation.concurrent.Immutable; -import org.sonar.api.batch.rule.Rule; -import org.sonar.api.batch.rule.Rules; -import org.sonar.api.rule.RuleKey; - -@Immutable -class DefaultRules implements Rules { - private final Map> rulesByRepository; - private final Map>> rulesByRepositoryAndInternalKey; - private final Map rulesByRuleKey; - - DefaultRules(Collection newRules) { - Map> rulesByRepositoryBuilder = new HashMap<>(); - Map>> rulesByRepositoryAndInternalKeyBuilder = new HashMap<>(); - Map rulesByRuleKeyBuilder = new HashMap<>(); - - for (NewRule newRule : newRules) { - DefaultRule r = new DefaultRule(newRule); - rulesByRuleKeyBuilder.put(r.key(), r); - rulesByRepositoryBuilder.computeIfAbsent(r.key().repository(), x -> new ArrayList<>()).add(r); - addToTable(rulesByRepositoryAndInternalKeyBuilder, r); - } - - rulesByRuleKey = Collections.unmodifiableMap(rulesByRuleKeyBuilder); - rulesByRepository = Collections.unmodifiableMap(rulesByRepositoryBuilder); - rulesByRepositoryAndInternalKey = Collections.unmodifiableMap(rulesByRepositoryAndInternalKeyBuilder); - } - - private static void addToTable(Map>> rulesByRepositoryAndInternalKeyBuilder, DefaultRule r) { - if (r.internalKey() == null) { - return; - } - - rulesByRepositoryAndInternalKeyBuilder - .computeIfAbsent(r.key().repository(), x -> new HashMap<>()) - .computeIfAbsent(r.internalKey(), x -> new ArrayList<>()) - .add(r); - } - - @Override - public Rule find(RuleKey ruleKey) { - return rulesByRuleKey.get(ruleKey); - } - - @Override - public Collection findAll() { - return rulesByRepository.values().stream().flatMap(List::stream).collect(Collectors.toList()); - } - - @Override - public Collection findByRepository(String repository) { - return rulesByRepository.getOrDefault(repository, Collections.emptyList()); - } - - @Override - public Collection findByInternalKey(String repository, String internalKey) { - return rulesByRepositoryAndInternalKey - .getOrDefault(repository, Collections.emptyMap()) - .getOrDefault(internalKey, Collections.emptyList()); - } -} diff --git a/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/RulesBuilder.java b/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/RulesBuilder.java deleted file mode 100644 index 9922a6df622..00000000000 --- a/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/RulesBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.rule.internal; - -import java.util.HashMap; -import java.util.Map; -import org.sonar.api.batch.rule.Rules; -import org.sonar.api.rule.RuleKey; - -/** - * For unit testing and internal use only. - * - * @since 4.2 - */ - -public class RulesBuilder { - - private final Map map = new HashMap<>(); - - public NewRule add(RuleKey key) { - if (map.containsKey(key)) { - throw new IllegalStateException(String.format("Rule '%s' already exists", key)); - } - NewRule newRule = new NewRule(key); - map.put(key, newRule); - return newRule; - } - - public Rules build() { - return new DefaultRules(map.values()); - } -} diff --git a/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/rule/internal/DefaultRulesTest.java b/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/rule/internal/DefaultRulesTest.java deleted file mode 100644 index a65933368af..00000000000 --- a/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/rule/internal/DefaultRulesTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.rule.internal; - -import java.util.LinkedList; -import java.util.List; -import org.junit.Test; -import org.sonar.api.rule.RuleKey; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DefaultRulesTest { - @Test - public void testRepeatedInternalKey() { - List newRules = new LinkedList<>(); - newRules.add(createRule("key1", "repo", "internal")); - newRules.add(createRule("key2", "repo", "internal")); - - DefaultRules rules = new DefaultRules(newRules); - assertThat(rules.findByInternalKey("repo", "internal")).hasSize(2); - assertThat(rules.find(RuleKey.of("repo", "key1"))).isNotNull(); - assertThat(rules.find(RuleKey.of("repo", "key2"))).isNotNull(); - assertThat(rules.findByRepository("repo")).hasSize(2); - } - - @Test - public void testNonExistingKey() { - List newRules = new LinkedList<>(); - newRules.add(createRule("key1", "repo", "internal")); - newRules.add(createRule("key2", "repo", "internal")); - - DefaultRules rules = new DefaultRules(newRules); - assertThat(rules.findByInternalKey("xx", "xx")).isEmpty(); - assertThat(rules.find(RuleKey.of("xxx", "xx"))).isNull(); - assertThat(rules.findByRepository("xxxx")).isEmpty(); - } - - @Test - public void testRepeatedRule() { - List newRules = new LinkedList<>(); - newRules.add(createRule("key", "repo", "internal")); - newRules.add(createRule("key", "repo", "internal")); - - DefaultRules rules = new DefaultRules(newRules); - assertThat(rules.find(RuleKey.of("repo", "key"))).isNotNull(); - } - - private NewRule createRule(String key, String repo, String internalKey) { - RuleKey ruleKey = RuleKey.of(repo, key); - NewRule newRule = new NewRule(ruleKey); - newRule.setInternalKey(internalKey); - - return newRule; - } -} diff --git a/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/rule/internal/RulesBuilderTest.java b/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/rule/internal/RulesBuilderTest.java deleted file mode 100644 index c64f6d29f8a..00000000000 --- a/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/rule/internal/RulesBuilderTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.rule.internal; - -import org.junit.Test; -import org.sonar.api.batch.rule.Rule; -import org.sonar.api.batch.rule.Rules; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.RuleStatus; -import org.sonar.api.rule.Severity; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class RulesBuilderTest { - - @Test - public void no_rules() { - RulesBuilder builder = new RulesBuilder(); - Rules rules = builder.build(); - assertThat(rules.findAll()).isEmpty(); - } - - @Test - public void build_rules() { - RulesBuilder builder = new RulesBuilder(); - NewRule newJava1 = builder.add(RuleKey.of("java", "S0001")); - newJava1.setName("Detect bug"); - newJava1.setDescription("Detect potential bug"); - newJava1.setInternalKey("foo=bar"); - newJava1.setSeverity(org.sonar.api.rule.Severity.CRITICAL); - newJava1.setStatus(RuleStatus.BETA); - newJava1.addParam("min"); - newJava1.addParam("max").setDescription("Maximum"); - // most simple rule - builder.add(RuleKey.of("java", "S0002")); - builder.add(RuleKey.of("findbugs", "NPE")); - - Rules rules = builder.build(); - - assertThat(rules.findAll()).hasSize(3); - assertThat(rules.findByRepository("java")).hasSize(2); - assertThat(rules.findByRepository("findbugs")).hasSize(1); - assertThat(rules.findByRepository("unknown")).isEmpty(); - - Rule java1 = rules.find(RuleKey.of("java", "S0001")); - assertThat(java1.key().repository()).isEqualTo("java"); - assertThat(java1.key().rule()).isEqualTo("S0001"); - assertThat(java1.name()).isEqualTo("Detect bug"); - assertThat(java1.description()).isEqualTo("Detect potential bug"); - assertThat(java1.internalKey()).isEqualTo("foo=bar"); - assertThat(java1.status()).isEqualTo(RuleStatus.BETA); - assertThat(java1.severity()).isEqualTo(org.sonar.api.rule.Severity.CRITICAL); - assertThat(java1.params()).hasSize(2); - assertThat(java1.param("min").key()).isEqualTo("min"); - assertThat(java1.param("min").description()).isNull(); - assertThat(java1.param("max").key()).isEqualTo("max"); - assertThat(java1.param("max").description()).isEqualTo("Maximum"); - - Rule java2 = rules.find(RuleKey.of("java", "S0002")); - assertThat(java2.key().repository()).isEqualTo("java"); - assertThat(java2.key().rule()).isEqualTo("S0002"); - assertThat(java2.description()).isNull(); - assertThat(java2.internalKey()).isNull(); - assertThat(java2.status()).isEqualTo(RuleStatus.defaultStatus()); - assertThat(java2.severity()).isEqualTo(Severity.defaultSeverity()); - assertThat(java2.params()).isEmpty(); - } - - @Test - public void fail_to_add_twice_the_same_rule() { - RulesBuilder builder = new RulesBuilder(); - builder.add(RuleKey.of("java", "S0001")); - - assertThatThrownBy(() -> builder.add(RuleKey.of("java", "S0001"))) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Rule 'java:S0001' already exists"); - } - - @Test - public void fail_to_add_twice_the_same_param() { - RulesBuilder builder = new RulesBuilder(); - NewRule newRule = builder.add(RuleKey.of("java", "S0001")); - newRule.addParam("min"); - newRule.addParam("max"); - - assertThatThrownBy(() -> newRule.addParam("min")) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Parameter 'min' already exists on rule 'java:S0001'"); - } -} diff --git a/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/internal/SensorContextTesterTest.java b/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/internal/SensorContextTesterTest.java index 2896242c7b0..7e2ad58c035 100644 --- a/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/internal/SensorContextTesterTest.java +++ b/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/internal/SensorContextTesterTest.java @@ -25,11 +25,9 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; -import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultFileSystem; import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.DefaultTextPointer; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.api.batch.rule.ActiveRules; @@ -194,13 +192,6 @@ public class SensorContextTesterTest { assertThat(tester.measures("foo:src/Foo.java")).hasSize(2); assertThat(tester.measure("foo:src/Foo.java", "ncloc")).isNotNull(); assertThat(tester.measure("foo:src/Foo.java", "lines")).isNotNull(); - tester.newMeasure() - .on(new DefaultInputModule(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()))) - .forMetric(CoreMetrics.DIRECTORIES) - .withValue(4) - .save(); - assertThat(tester.measures("foo")).hasSize(1); - assertThat(tester.measure("foo", "directories")).isNotNull(); } @Test(expected = IllegalStateException.class) diff --git a/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MapSettingsTest.java b/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MapSettingsTest.java index 9816bcae164..9d8b6ec6d12 100644 --- a/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MapSettingsTest.java +++ b/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MapSettingsTest.java @@ -61,7 +61,7 @@ public class MapSettingsTest { @Property(key = "integer", name = "Integer", defaultValue = "12345"), @Property(key = "array", name = "Array", defaultValue = "one,two,three"), @Property(key = "multi_values", name = "Array", defaultValue = "1,2,3", multiValues = true), - @Property(key = "sonar.jira", name = "Jira Server", type = PropertyType.PROPERTY_SET, propertySetKey = "jira"), + @Property(key = "sonar.jira", name = "Jira Server", type = PropertyType.PROPERTY_SET), @Property(key = "newKey", name = "New key", deprecatedKey = "oldKey"), @Property(key = "newKeyWithDefaultValue", name = "New key with default value", deprecatedKey = "oldKeyWithDefaultValue", defaultValue = "default_value"), @Property(key = "new_multi_values", name = "New multi values", defaultValue = "1,2,3", multiValues = true, deprecatedKey = "old_multi_values") diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/platform/DefaultServer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/platform/DefaultServer.java index 64de06bc532..6b3b8c30258 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/platform/DefaultServer.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/platform/DefaultServer.java @@ -72,14 +72,4 @@ public class DefaultServer extends Server { } return StringUtils.removeEnd(baseUrl, "/"); } - - @Override - public boolean isSecured() { - return false; - } - - @Override - public String getPermanentServerId() { - return getId(); - } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/DefaultRulesLoader.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/DefaultRulesLoader.java deleted file mode 100644 index 2402fabcdbb..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/DefaultRulesLoader.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.scanner.rule; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import org.apache.commons.io.IOUtils; -import org.sonar.scanner.bootstrap.DefaultScannerWsClient; -import org.sonarqube.ws.Rules.ListResponse; -import org.sonarqube.ws.Rules.ListResponse.Rule; -import org.sonarqube.ws.client.GetRequest; - -public class DefaultRulesLoader implements RulesLoader { - private static final String RULES_SEARCH_URL = "/api/rules/list.protobuf"; - - private final DefaultScannerWsClient wsClient; - - public DefaultRulesLoader(DefaultScannerWsClient wsClient) { - this.wsClient = wsClient; - } - - @Override - public List load() { - GetRequest getRequest = new GetRequest(RULES_SEARCH_URL); - ListResponse list = loadFromStream(wsClient.call(getRequest).contentStream()); - return list.getRulesList(); - } - - private static ListResponse loadFromStream(InputStream is) { - try { - return ListResponse.parseFrom(is); - } catch (IOException e) { - throw new IllegalStateException("Unable to get rules", e); - } finally { - IOUtils.closeQuietly(is); - } - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/RulesProvider.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/RulesProvider.java deleted file mode 100644 index 22c6d270cc3..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/RulesProvider.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.scanner.rule; - -import java.util.List; -import org.sonar.api.batch.rule.Rules; -import org.sonar.api.batch.rule.internal.NewRule; -import org.sonar.api.batch.rule.internal.RulesBuilder; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.api.utils.log.Profiler; -import org.sonarqube.ws.Rules.ListResponse.Rule; -import org.springframework.context.annotation.Bean; - -public class RulesProvider { - private static final Logger LOG = Loggers.get(RulesProvider.class); - private static final String LOG_MSG = "Load server rules"; - - @Bean("Rules") - public Rules provide(RulesLoader ref) { - Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG); - List loadedRules = ref.load(); - RulesBuilder builder = new RulesBuilder(); - - for (Rule r : loadedRules) { - NewRule newRule = builder.add(RuleKey.of(r.getRepository(), r.getKey())); - newRule.setName(r.getName()); - newRule.setInternalKey(r.getInternalKey()); - } - - profiler.stopInfo(); - return builder.build(); - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/SpringProjectScanContainer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/SpringProjectScanContainer.java index 9cb9d8b509d..70f6b12ae6a 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/SpringProjectScanContainer.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/SpringProjectScanContainer.java @@ -21,6 +21,8 @@ package org.sonar.scanner.scan; import javax.annotation.Nullable; import javax.annotation.Priority; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.FileMetadata; import org.sonar.api.batch.fs.internal.SensorStrategy; @@ -29,8 +31,6 @@ import org.sonar.api.batch.sensor.issue.internal.DefaultNoSonarFilter; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.scan.filesystem.PathResolver; import org.sonar.api.utils.MessageException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.sonar.core.config.ScannerProperties; import org.sonar.core.extension.CoreExtensionsInstaller; import org.sonar.core.language.LanguagesProvider; @@ -104,9 +104,7 @@ import org.sonar.scanner.repository.language.DefaultLanguagesRepository; import org.sonar.scanner.repository.settings.DefaultProjectSettingsLoader; import org.sonar.scanner.rule.ActiveRulesProvider; import org.sonar.scanner.rule.DefaultActiveRulesLoader; -import org.sonar.scanner.rule.DefaultRulesLoader; import org.sonar.scanner.rule.QProfileVerifier; -import org.sonar.scanner.rule.RulesProvider; import org.sonar.scanner.scan.branch.BranchConfiguration; import org.sonar.scanner.scan.branch.BranchConfigurationProvider; import org.sonar.scanner.scan.branch.BranchType; @@ -168,7 +166,6 @@ public class SpringProjectScanContainer extends SpringComponentContainer { ResourceTypes.class, ProjectReactorValidator.class, ProjectInfo.class, - new RulesProvider(), new BranchConfigurationProvider(), new ProjectBranchesProvider(), ProjectRepositoriesProvider.class, @@ -313,7 +310,6 @@ public class SpringProjectScanContainer extends SpringComponentContainer { add(SvnScmSupport.getObjects()); add(DefaultProjectSettingsLoader.class, - DefaultRulesLoader.class, DefaultActiveRulesLoader.class, DefaultQualityProfileLoader.class, DefaultProjectRepositoriesLoader.class); @@ -359,7 +355,6 @@ public class SpringProjectScanContainer extends SpringComponentContainer { getComponentByType(DeprecatedPropertiesWarningGenerator.class).execute(); - getComponentByType(ProjectFileIndexer.class).index(); // Log detected languages and their profiles after FS is indexed and languages detected diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/platform/DefaultServerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/platform/DefaultServerTest.java index 3e2880e7e41..d2cc612ad88 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/platform/DefaultServerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/platform/DefaultServerTest.java @@ -46,10 +46,8 @@ public class DefaultServerTest { assertThat(metadata.getVersion()).isEqualTo("2.2"); assertThat(metadata.getStartedAt()).isNotNull(); assertThat(metadata.getPublicRootUrl()).isEqualTo("http://foo.com"); - assertThat(metadata.getPermanentServerId()).isEqualTo("123"); assertThat(metadata.getContextPath()).isNull(); - assertThat(metadata.isSecured()).isFalse(); } @Test diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/DefaultRulesLoaderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/DefaultRulesLoaderTest.java deleted file mode 100644 index 15f63273ae7..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/DefaultRulesLoaderTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.scanner.rule; - -import com.google.common.io.ByteSource; -import com.google.common.io.Resources; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import org.junit.Test; -import org.sonar.scanner.WsTestUtil; -import org.sonar.scanner.bootstrap.DefaultScannerWsClient; -import org.sonarqube.ws.Rules.ListResponse.Rule; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; - -public class DefaultRulesLoaderTest { - - @Test - public void testParseServerResponse() throws IOException { - DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class); - InputStream is = Resources.asByteSource(this.getClass().getResource("DefaultRulesLoaderTest/response.protobuf")).openBufferedStream(); - WsTestUtil.mockStream(wsClient, is); - DefaultRulesLoader loader = new DefaultRulesLoader(wsClient); - List ruleList = loader.load(); - assertThat(ruleList).hasSize(318); - } - - @Test - public void testError() throws IOException { - DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class); - InputStream is = ByteSource.wrap("trash".getBytes()).openBufferedStream(); - WsTestUtil.mockStream(wsClient, is); - DefaultRulesLoader loader = new DefaultRulesLoader(wsClient); - - assertThatThrownBy(() -> loader.load()) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Unable to get rules"); - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/RulesProviderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/RulesProviderTest.java deleted file mode 100644 index cc9ba79bf8c..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/RulesProviderTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2023 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.scanner.rule; - -import com.google.common.collect.Lists; -import org.junit.Test; -import org.sonar.api.batch.rule.Rules; -import org.sonarqube.ws.Rules.ListResponse.Rule; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class RulesProviderTest { - @Test - public void testRuleTranslation() { - RulesLoader loader = mock(RulesLoader.class); - when(loader.load()).thenReturn(Lists.newArrayList(getTestRule())); - - RulesProvider provider = new RulesProvider(); - - Rules rules = provider.provide(loader); - - assertThat(rules.findAll()).hasSize(1); - assertRule(rules.findAll().iterator().next()); - } - - private static void assertRule(org.sonar.api.batch.rule.Rule r) { - Rule testRule = getTestRule(); - - assertThat(r.name()).isEqualTo(testRule.getName()); - assertThat(r.internalKey()).isEqualTo(testRule.getInternalKey()); - assertThat(r.key().rule()).isEqualTo(testRule.getKey()); - assertThat(r.key().repository()).isEqualTo(testRule.getRepository()); - } - - private static Rule getTestRule() { - Rule.Builder ruleBuilder = Rule.newBuilder(); - ruleBuilder.setKey("key1"); - ruleBuilder.setRepository("repo1"); - ruleBuilder.setName("name"); - ruleBuilder.setInternalKey("key1"); - return ruleBuilder.build(); - - } -}