repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
sonarqube
sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/MainCollectorTest.java
/* * 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.monitoring; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class MainCollectorTest { private final MonitoringTask task1 = mock(MonitoringTask.class); private final MonitoringTask task2 = mock(MonitoringTask.class); private MainCollector underTest; @Before public void before() { MonitoringTask[] tasks = {task1, task2}; for(MonitoringTask task : tasks) { when(task.getDelay()).thenReturn(1L); when(task.getPeriod()).thenReturn(1L); } underTest = new MainCollector(tasks); } @After public void stop() { underTest.stop(); } @Test public void startAndStop_executorServiceIsShutdown() { underTest.start(); assertFalse(underTest.getScheduledExecutorService().isShutdown()); underTest.stop(); assertTrue(underTest.getScheduledExecutorService().isShutdown()); } @Test public void start_givenTwoTasks_callsGetsDelayAndPeriodFromTasks() { underTest.start(); verify(task1, times(1)).getDelay(); verify(task1, times(1)).getPeriod(); verify(task2, times(1)).getDelay(); verify(task2, times(1)).getPeriod(); } }
2,260
28.75
75
java
sonarqube
sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/ServerMonitoringMetricsTest.java
/* * 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.monitoring; import io.prometheus.client.Collector; import io.prometheus.client.CollectorRegistry; import java.util.Collections; import java.util.Enumeration; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; //@Execution(SAME_THREAD) for JUnit5 public class ServerMonitoringMetricsTest { @Before public void before() { CollectorRegistry.defaultRegistry.clear(); } @Test public void creatingClassShouldAddMetricsToRegistry() { assertThat(sizeOfDefaultRegistry()).isNotPositive(); new ServerMonitoringMetrics(); assertThat(sizeOfDefaultRegistry()).isPositive(); } @Test public void setters_setGreenStatusForMetricsInTheMetricsRegistry() { ServerMonitoringMetrics metrics = new ServerMonitoringMetrics(); metrics.setGithubStatusToGreen(); metrics.setGitlabStatusToGreen(); metrics.setAzureStatusToGreen(); metrics.setBitbucketStatusToGreen(); metrics.setComputeEngineStatusToGreen(); metrics.setElasticSearchStatusToGreen(); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_health_integration_github_status")).isPositive(); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_health_integration_gitlab_status")).isPositive(); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_health_integration_bitbucket_status")).isPositive(); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_health_integration_azuredevops_status")).isPositive(); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_health_compute_engine_status")).isPositive(); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_health_elasticsearch_status")).isPositive(); } @Test public void setters_setRedStatusForMetricsInTheMetricsRegistry() { ServerMonitoringMetrics metrics = new ServerMonitoringMetrics(); metrics.setGithubStatusToRed(); metrics.setGitlabStatusToRed(); metrics.setAzureStatusToRed(); metrics.setBitbucketStatusToRed(); metrics.setComputeEngineStatusToRed(); metrics.setElasticSearchStatusToRed(); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_health_integration_github_status")).isZero(); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_health_integration_gitlab_status")).isZero(); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_health_integration_bitbucket_status")).isZero(); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_health_integration_azuredevops_status")).isZero(); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_health_compute_engine_status")).isZero(); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_health_elasticsearch_status")).isZero(); } @Test public void setters_setNumberOfPendingTasks() { ServerMonitoringMetrics metrics = new ServerMonitoringMetrics(); metrics.setNumberOfPendingTasks(10); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_compute_engine_pending_tasks_total")) .isEqualTo(10); } @Test public void setters_setLicenseRelatedMetrics() { ServerMonitoringMetrics metrics = new ServerMonitoringMetrics(); metrics.setLicenseDayUntilExpire(10); metrics.setLinesOfCodeRemaining(20); metrics.setLinesOfCodeAnalyzed(30); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_license_days_before_expiration_total")) .isEqualTo(10); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_license_number_of_lines_remaining_total")) .isEqualTo(20); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_license_number_of_lines_analyzed_total")) .isEqualTo(30); } @Test public void setters_setWebUptimeMetric() { ServerMonitoringMetrics metrics = new ServerMonitoringMetrics(); metrics.setWebUptimeMinutes(10); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_web_uptime_minutes")) .isEqualTo(10); } @Test public void setters_setNumberOfConnectedSonarLintClients() { ServerMonitoringMetrics metrics = new ServerMonitoringMetrics(); metrics.setNumberOfConnectedSonarLintClients(5); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_number_of_connected_sonarlint_clients")) .isEqualTo(5); } @Test public void setters_setElasticsearchMetricsWithLabels() { ServerMonitoringMetrics metrics = new ServerMonitoringMetrics(); String[] labelNames = {"node_name"}; String[] labelValues = {"node_1"}; metrics.setElasticSearchDiskSpaceFreeBytes(labelValues[0], 30); metrics.setElasticSearchDiskSpaceTotalBytes(labelValues[0], 30); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_elasticsearch_disk_space_total_bytes", labelNames, labelValues)) .isEqualTo(30); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_elasticsearch_disk_space_free_bytes", labelNames, labelValues)) .isEqualTo(30); } @Test public void observeComputeEngineTaskDurationTest() { ServerMonitoringMetrics metrics = new ServerMonitoringMetrics(); String[] labelNames = {"task_type", "project_key"}; String[] labelValues = {"REPORT", "projectKey"}; metrics.observeComputeEngineTaskDuration(10, labelValues[0], labelValues[1]); assertThat(CollectorRegistry.defaultRegistry.getSampleValue("sonarqube_compute_engine_tasks_running_duration_seconds_sum", labelNames, labelValues)).isEqualTo(10); } private int sizeOfDefaultRegistry() { Enumeration<Collector.MetricFamilySamples> metrics = CollectorRegistry.defaultRegistry.metricFamilySamples(); return Collections.list(metrics).size(); } }
6,791
39.915663
129
java
sonarqube
sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/SonarLintConnectedClientsTaskTest.java
/* * 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.monitoring; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.server.pushapi.sonarlint.SonarLintClientsRegistry; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class SonarLintConnectedClientsTaskTest { private final ServerMonitoringMetrics metrics = mock(ServerMonitoringMetrics.class); private final SonarLintClientsRegistry sonarLintClientsRegistry = mock(SonarLintClientsRegistry.class); private final SonarLintConnectedClientsTaskTest.DumpMapConfiguration config = new SonarLintConnectedClientsTaskTest.DumpMapConfiguration(); private final SonarLintConnectedClientsTask underTest = new SonarLintConnectedClientsTask(metrics, sonarLintClientsRegistry, config); @Test public void run_when5ConnectedClients_updateWith5() { when(sonarLintClientsRegistry.countConnectedClients()).thenReturn(5L); underTest.run(); verify(metrics).setNumberOfConnectedSonarLintClients(5L); } @Test public void getDelay_returnNumberIfConfigEmpty() { long delay = underTest.getDelay(); assertThat(delay).isPositive(); } @Test public void getDelay_returnNumberFromConfig() { config.put("sonar.server.monitoring.other.initial.delay", "100000"); long delay = underTest.getDelay(); assertThat(delay).isEqualTo(100_000L); } @Test public void getPeriod_returnNumberIfConfigEmpty() { long delay = underTest.getPeriod(); assertThat(delay).isPositive(); } @Test public void getPeriod_returnNumberFromConfig() { config.put("sonar.server.monitoring.other.period", "100000"); long delay = underTest.getPeriod(); assertThat(delay).isEqualTo(100_000L); } private static class DumpMapConfiguration implements Configuration { private final Map<String, String> keyValues = new HashMap<>(); public Configuration put(String key, String value) { keyValues.put(key, value.trim()); return this; } @Override public Optional<String> get(String key) { return Optional.ofNullable(keyValues.get(key)); } @Override public boolean hasKey(String key) { throw new UnsupportedOperationException("hasKey not implemented"); } @Override public String[] getStringArray(String key) { throw new UnsupportedOperationException("getStringArray not implemented"); } } }
3,418
30.953271
141
java
sonarqube
sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/WebUptimeTaskTest.java
/* * 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.monitoring; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.junit.Test; import org.sonar.api.config.Configuration; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class WebUptimeTaskTest { private final ServerMonitoringMetrics metrics = mock(ServerMonitoringMetrics.class); private final DumpMapConfiguration config = new DumpMapConfiguration(); private final WebUptimeTask underTest = new WebUptimeTask(metrics, config); @Test public void run_metricsAreUpdatedAlways() { underTest.run(); verify(metrics, times(1)).setWebUptimeMinutes(anyLong()); } @Test public void getDelay_returnNumberIfConfigEmpty() { long delay = underTest.getDelay(); assertThat(delay).isPositive(); } @Test public void getDelay_returnNumberFromConfig() { config.put("sonar.server.monitoring.webuptime.initial.delay", "100000"); long delay = underTest.getDelay(); assertThat(delay).isEqualTo(100_000L); } @Test public void getPeriod_returnNumberIfConfigEmpty() { long delay = underTest.getPeriod(); assertThat(delay).isPositive(); } @Test public void getPeriod_returnNumberFromConfig() { config.put("sonar.server.monitoring.webuptime.period", "100000"); long delay = underTest.getPeriod(); assertThat(delay).isEqualTo(100_000L); } private static class DumpMapConfiguration implements Configuration { private final Map<String, String> keyValues = new HashMap<>(); public Configuration put(String key, String value) { keyValues.put(key, value.trim()); return this; } @Override public Optional<String> get(String key) { return Optional.ofNullable(keyValues.get(key)); } @Override public boolean hasKey(String key) { throw new UnsupportedOperationException("hasKey not implemented"); } @Override public String[] getStringArray(String key) { throw new UnsupportedOperationException("getStringArray not implemented"); } } }
3,076
28.873786
86
java
sonarqube
sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/ce/ComputeEngineMetricsTaskTest.java
/* * 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.monitoring.ce; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.db.DbClient; import org.sonar.server.monitoring.ServerMonitoringMetrics; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class ComputeEngineMetricsTaskTest { private final ServerMonitoringMetrics metrics = mock(ServerMonitoringMetrics.class); private final DbClient dbClient = mock(DbClient.class); private DumpMapConfiguration config; private ComputeEngineMetricsTask underTest; @Before public void before() { config = new DumpMapConfiguration(); underTest = new ComputeEngineMetricsTask(dbClient, metrics, config) { @Override public void run() { //intentionally empty } }; } @Test public void getDelay_returnNumberIfConfigEmpty() { long delay = underTest.getDelay(); assertThat(delay).isPositive(); } @Test public void getDelay_returnNumberFromConfig() { config.put("sonar.server.monitoring.ce.initial.delay", "100000"); long delay = underTest.getDelay(); assertThat(delay).isEqualTo(100_000L); } @Test public void getPeriod_returnNumberIfConfigEmpty() { long delay = underTest.getPeriod(); assertThat(delay).isPositive(); } @Test public void getPeriod_returnNumberFromConfig() { config.put("sonar.server.monitoring.ce.period", "100000"); long delay = underTest.getPeriod(); assertThat(delay).isEqualTo(100_000L); } private static class DumpMapConfiguration implements Configuration { private final Map<String, String> keyValues = new HashMap<>(); public Configuration put(String key, String value) { keyValues.put(key, value.trim()); return this; } @Override public Optional<String> get(String key) { return Optional.ofNullable(keyValues.get(key)); } @Override public boolean hasKey(String key) { throw new UnsupportedOperationException("hasKey not implemented"); } @Override public String[] getStringArray(String key) { throw new UnsupportedOperationException("getStringArray not implemented"); } } }
3,147
27.880734
86
java
sonarqube
sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/ce/NumberOfTasksInQueueTaskTest.java
/* * 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.monitoring.ce; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.db.DbClient; import org.sonar.db.ce.CeQueueDao; import org.sonar.server.monitoring.ServerMonitoringMetrics; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class NumberOfTasksInQueueTaskTest { private final DbClient dbClient = mock(DbClient.class); private final CeQueueDao ceQueueDao = mock(CeQueueDao.class); private final ServerMonitoringMetrics metrics = mock(ServerMonitoringMetrics.class); private final Configuration config = mock(Configuration.class); @Test public void run_setsValueInMetricsBasedOnValueReturnedFromDatabase() { NumberOfTasksInQueueTask task = new NumberOfTasksInQueueTask(dbClient, metrics, config); when(dbClient.ceQueueDao()).thenReturn(ceQueueDao); when(ceQueueDao.countByStatus(any(), any())).thenReturn(10); task.run(); verify(metrics, times(1)).setNumberOfPendingTasks(10); } }
1,987
37.230769
92
java
sonarqube
sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/ce/RecentTasksDurationTaskTest.java
/* * 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.monitoring.ce; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.ce.CeActivityDao; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.entity.EntityDao; import org.sonar.db.entity.EntityDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.monitoring.ServerMonitoringMetrics; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class RecentTasksDurationTaskTest { private final DbClient dbClient = mock(DbClient.class); private final CeActivityDao ceActivityDao = mock(CeActivityDao.class); private final EntityDao entityDao = mock(EntityDao.class); private final ServerMonitoringMetrics metrics = mock(ServerMonitoringMetrics.class); private final Configuration config = mock(Configuration.class); private final System2 system = mock(System2.class); @Before public void before() { when(dbClient.ceActivityDao()).thenReturn(ceActivityDao); when(dbClient.entityDao()).thenReturn(entityDao); ComponentDto componentDto = new ComponentDto(); componentDto.setKey("key"); } @Test public void run_given5SuccessfulTasks_observeDurationFor5Tasks() { RecentTasksDurationTask task = new RecentTasksDurationTask(dbClient, metrics, config, system); List<CeActivityDto> recentTasks = createTasks(5, 0); when(entityDao.selectByUuids(any(), any())).thenReturn(createEntityDtos(5)); when(ceActivityDao.selectNewerThan(any(), anyLong())).thenReturn(recentTasks); task.run(); verify(metrics, times(5)).observeComputeEngineTaskDuration(anyLong(), any(), any()); } @Test public void run_given1SuccessfulTasksAnd1Failing_observeDurationFor1Tasks() { RecentTasksDurationTask task = new RecentTasksDurationTask(dbClient, metrics, config, system); List<CeActivityDto> recentTasks = createTasks(1, 1); when(entityDao.selectByUuids(any(), any())).thenReturn(createEntityDtos(1)); when(ceActivityDao.selectNewerThan(any(), anyLong())).thenReturn(recentTasks); task.run(); verify(metrics, times(1)).observeComputeEngineTaskDuration(anyLong(), any(), any()); } @Test public void run_givenNullExecutionTime_dontReportMetricData() { RecentTasksDurationTask task = new RecentTasksDurationTask(dbClient, metrics, config, system); List<CeActivityDto> recentTasks = createTasks(1, 0); recentTasks.get(0).setExecutionTimeMs(null); when(entityDao.selectByUuids(any(), any())).thenReturn(createEntityDtos(1)); when(ceActivityDao.selectNewerThan(any(), anyLong())).thenReturn(recentTasks); task.run(); verify(metrics, times(0)).observeComputeEngineTaskDuration(anyLong(), any(), any()); } private List<CeActivityDto> createTasks(int numberOfSuccededTasks, int numberOfFailedTasks) { List<CeActivityDto> dtos = new ArrayList<>(); for (int i=0; i<numberOfSuccededTasks; i++) { dtos.add(newCeActivityTask(CeActivityDto.Status.SUCCESS)); } for (int i=0; i<numberOfFailedTasks; i++) { dtos.add(newCeActivityTask(CeActivityDto.Status.FAILED)); } return dtos; } private List<EntityDto> createEntityDtos(int number) { List<EntityDto> entityDtos = new ArrayList<>(); for(int i=0; i<5; i++) { ProjectDto entity = new ProjectDto(); entity.setUuid(i + ""); entity.setKey(i + ""); entityDtos.add(entity); } return entityDtos; } private CeActivityDto newCeActivityTask(CeActivityDto.Status status) { CeActivityDto dto = new CeActivityDto(new CeQueueDto()); dto.setStatus(status); dto.setEntityUuid("0"); dto.setExecutionTimeMs(1000L); return dto; } }
4,922
34.934307
98
java
sonarqube
sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/devops/AbstractDevOpsMetricsTaskTest.java
/* * 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.monitoring.devops; import java.util.ArrayList; import java.util.List; import org.sonar.db.alm.setting.ALM; import org.sonar.db.alm.setting.AlmSettingDto; public abstract class AbstractDevOpsMetricsTaskTest { protected List<AlmSettingDto> generateDtos(int numberOfDtos, ALM alm) { List<AlmSettingDto> settingDtos = new ArrayList<>(); for(int i=0; i<numberOfDtos; i++) { AlmSettingDto dto = new AlmSettingDto(); dto.setAlm(alm); settingDtos.add(dto); } return settingDtos; } }
1,384
34.512821
75
java
sonarqube
sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/devops/AzureMetricsTaskTest.java
/* * 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.monitoring.devops; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; import org.sonar.alm.client.azure.AzureDevOpsValidator; import org.sonar.api.config.Configuration; import org.sonar.db.DbClient; import org.sonar.db.alm.setting.ALM; import org.sonar.db.alm.setting.AlmSettingDao; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.monitoring.ServerMonitoringMetrics; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class AzureMetricsTaskTest extends AbstractDevOpsMetricsTaskTest { private final ServerMonitoringMetrics metrics = mock(ServerMonitoringMetrics.class); private final AzureDevOpsValidator azureDevOpsValidator = mock(AzureDevOpsValidator.class); private final DbClient dbClient = mock(DbClient.class); private final Configuration config = mock(Configuration.class); private final AlmSettingDao almSettingsDao = mock(AlmSettingDao.class); private final AzureMetricsTask underTest = new AzureMetricsTask(metrics, azureDevOpsValidator, dbClient, config); @Before public void before() { when(dbClient.almSettingDao()).thenReturn(almSettingsDao); } @Test public void run_azureDevOpsValidatorDoesntThrowException_setGreenStatusInMetricsOnce() { List<AlmSettingDto> dtos = generateDtos(5, ALM.AZURE_DEVOPS); when(almSettingsDao.selectByAlm(any(), any())).thenReturn(dtos); underTest.run(); verify(metrics, times(1)).setAzureStatusToGreen(); verify(metrics, times(0)).setAzureStatusToRed(); } @Test public void run_azureDevOpsValidatorDoesntThrowException_setRedStatusInMetricsOnce() { List<AlmSettingDto> dtos = generateDtos(5, ALM.AZURE_DEVOPS); when(almSettingsDao.selectByAlm(any(), any())).thenReturn(dtos); doThrow(new RuntimeException()).when(azureDevOpsValidator).validate(any()); underTest.run(); verify(metrics, times(0)).setAzureStatusToGreen(); verify(metrics, times(1)).setAzureStatusToRed(); } @Test public void run_azureIntegrationNotConfigured_setRedStatusInMetricsOnce() { when(almSettingsDao.selectByAlm(any(), any())).thenReturn(Collections.emptyList()); underTest.run(); verify(metrics, times(0)).setAzureStatusToGreen(); verify(metrics, times(1)).setAzureStatusToRed(); } }
3,371
36.054945
115
java
sonarqube
sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/devops/BitbucketMetricsTaskTest.java
/* * 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.monitoring.devops; import java.util.Collections; import org.junit.Before; import org.junit.Test; import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudValidator; import org.sonar.alm.client.bitbucketserver.BitbucketServerSettingsValidator; import org.sonar.api.config.Configuration; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.setting.ALM; import org.sonar.db.alm.setting.AlmSettingDao; import org.sonar.server.monitoring.ServerMonitoringMetrics; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class BitbucketMetricsTaskTest extends AbstractDevOpsMetricsTaskTest { private final ServerMonitoringMetrics metrics = mock(ServerMonitoringMetrics.class); private final BitbucketCloudValidator bitbucketCloudValidator = mock(BitbucketCloudValidator.class); private final BitbucketServerSettingsValidator bitbucketServerValidator = mock(BitbucketServerSettingsValidator.class); private final DbClient dbClient = mock(DbClient.class); private final Configuration config = mock(Configuration.class); private final AlmSettingDao almSettingsDao = mock(AlmSettingDao.class); private final DbSession dbSession = mock(DbSession.class); private final BitbucketMetricsTask underTest = new BitbucketMetricsTask(metrics, bitbucketCloudValidator, bitbucketServerValidator, dbClient, config); @Before public void before() { when(dbClient.almSettingDao()).thenReturn(almSettingsDao); when(dbClient.openSession(anyBoolean())).thenReturn(dbSession); } @Test public void run_bitbucketValidatorsDontThrowException_setGreenStatusInMetricsOnce() { when(almSettingsDao.selectByAlm(dbSession, ALM.BITBUCKET)).thenReturn(generateDtos(5, ALM.BITBUCKET)); when(almSettingsDao.selectByAlm(dbSession, ALM.BITBUCKET_CLOUD)).thenReturn(generateDtos(5, ALM.BITBUCKET_CLOUD)); underTest.run(); verify(metrics, times(1)).setBitbucketStatusToGreen(); verify(metrics, times(0)).setBitbucketStatusToRed(); } @Test public void run_bitbucketValidatorsDoThrowException_setRedStatusInMetricsOnce() { when(almSettingsDao.selectByAlm(dbSession, ALM.BITBUCKET)).thenReturn(generateDtos(5, ALM.BITBUCKET)); when(almSettingsDao.selectByAlm(dbSession, ALM.BITBUCKET_CLOUD)).thenReturn(generateDtos(5, ALM.BITBUCKET_CLOUD)); doThrow(new RuntimeException()).when(bitbucketCloudValidator).validate(any()); doThrow(new RuntimeException()).when(bitbucketServerValidator).validate(any()); underTest.run(); verify(metrics, times(0)).setBitbucketStatusToGreen(); verify(metrics, times(1)).setBitbucketStatusToRed(); } @Test public void run_bitbucketServerValidatorThrowExceptionCloudDoesNot_setRedStatusInMetricsOnce() { when(almSettingsDao.selectByAlm(dbSession, ALM.BITBUCKET)).thenReturn(generateDtos(5, ALM.BITBUCKET)); when(almSettingsDao.selectByAlm(dbSession, ALM.BITBUCKET_CLOUD)).thenReturn(generateDtos(5, ALM.BITBUCKET_CLOUD)); doThrow(new RuntimeException()).when(bitbucketServerValidator).validate(any()); underTest.run(); verify(metrics, times(0)).setBitbucketStatusToGreen(); verify(metrics, times(1)).setBitbucketStatusToRed(); } @Test public void run_bitbucketServerConfiguredBitbucketCloudNot_setGreenStatusInMetricsOnce() { when(almSettingsDao.selectByAlm(dbSession, ALM.BITBUCKET)).thenReturn(generateDtos(1, ALM.BITBUCKET)); underTest.run(); verify(metrics, times(1)).setBitbucketStatusToGreen(); verify(metrics, times(0)).setBitbucketStatusToRed(); } @Test public void run_bitbucketIntegrationNotConfigured_setRedStatusInMetricsOnce() { when(almSettingsDao.selectByAlm(dbSession, ALM.BITBUCKET)).thenReturn(Collections.emptyList()); when(almSettingsDao.selectByAlm(dbSession, ALM.BITBUCKET_CLOUD)).thenReturn(Collections.emptyList()); underTest.run(); verify(metrics, times(0)).setBitbucketStatusToGreen(); verify(metrics, times(1)).setBitbucketStatusToRed(); } }
5,115
40.593496
121
java
sonarqube
sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/devops/DevOpsMetricsTaskTest.java
/* * 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.monitoring.devops; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.db.DbClient; import org.sonar.server.monitoring.ServerMonitoringMetrics; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DevOpsMetricsTaskTest { private final ServerMonitoringMetrics metrics = mock(ServerMonitoringMetrics.class); private final DbClient dbClient = mock(DbClient.class); private final Configuration config = mock(Configuration.class); private DevOpsMetricsTask underTest; @Before public void before() { underTest = new DevOpsMetricsTask(dbClient, metrics, config) { @Override public void run() { //intentionally empty } }; } @Test public void getDelay_returnNumberIfConfigEmpty() { when(config.get("sonar.server.monitoring.devops.initial.delay")).thenReturn(Optional.empty()); long delay = underTest.getDelay(); assertThat(delay).isPositive(); } @Test public void getDelay_returnNumberFromConfig() { when(config.getLong("sonar.server.monitoring.devops.initial.delay")).thenReturn(Optional.of(100_000L)); long delay = underTest.getDelay(); assertThat(delay).isEqualTo(100_000L); } @Test public void getPeriod_returnNumberIfConfigEmpty() { when(config.get("sonar.server.monitoring.devops.period")).thenReturn(Optional.empty()); long delay = underTest.getPeriod(); assertThat(delay).isPositive(); } @Test public void getPeriod_returnNumberFromConfig() { when(config.getLong("sonar.server.monitoring.devops.period")).thenReturn(Optional.of(100_000L)); long delay = underTest.getPeriod(); assertThat(delay).isEqualTo(100_000L); } }
2,705
30.103448
107
java
sonarqube
sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/devops/GithubMetricsTaskTest.java
/* * 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.monitoring.devops; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; import org.sonar.alm.client.github.GithubGlobalSettingsValidator; import org.sonar.api.config.Configuration; import org.sonar.db.DbClient; import org.sonar.db.alm.setting.ALM; import org.sonar.db.alm.setting.AlmSettingDao; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.monitoring.ServerMonitoringMetrics; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class GithubMetricsTaskTest extends AbstractDevOpsMetricsTaskTest { private final ServerMonitoringMetrics metrics = mock(ServerMonitoringMetrics.class); private final GithubGlobalSettingsValidator githubValidator = mock(GithubGlobalSettingsValidator.class); private final DbClient dbClient = mock(DbClient.class); private final Configuration config = mock(Configuration.class); private final AlmSettingDao almSettingsDao = mock(AlmSettingDao.class); private final GithubMetricsTask underTest = new GithubMetricsTask(metrics, githubValidator, dbClient, config); @Before public void before() { when(dbClient.almSettingDao()).thenReturn(almSettingsDao); } @Test public void run_githubValidatorDoesntThrowException_setGreenStatusInMetricsOnce() { List<AlmSettingDto> dtos = generateDtos(5, ALM.GITHUB); when(almSettingsDao.selectByAlm(any(), any())).thenReturn(dtos); underTest.run(); verify(metrics, times(1)).setGithubStatusToGreen(); verify(metrics, times(0)).setGithubStatusToRed(); } @Test public void run_githubValidatorDoesntThrowException_setRedStatusInMetricsOnce() { List<AlmSettingDto> dtos = generateDtos(5, ALM.GITHUB); when(almSettingsDao.selectByAlm(any(), any())).thenReturn(dtos); doThrow(new RuntimeException()).when(githubValidator).validate(any()); underTest.run(); verify(metrics, times(0)).setGithubStatusToGreen(); verify(metrics, times(1)).setGithubStatusToRed(); } @Test public void run_githubIntegrationNotConfigured_setRedStatusInMetricsOnce() { when(almSettingsDao.selectByAlm(any(), any())).thenReturn(Collections.emptyList()); underTest.run(); verify(metrics, times(0)).setGithubStatusToGreen(); verify(metrics, times(1)).setGithubStatusToRed(); } }
3,372
36.065934
112
java
sonarqube
sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/devops/GitlabMetricsTaskTest.java
/* * 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.monitoring.devops; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; import org.sonar.alm.client.gitlab.GitlabGlobalSettingsValidator; import org.sonar.api.config.Configuration; import org.sonar.db.DbClient; import org.sonar.db.alm.setting.ALM; import org.sonar.db.alm.setting.AlmSettingDao; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.monitoring.ServerMonitoringMetrics; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class GitlabMetricsTaskTest extends AbstractDevOpsMetricsTaskTest { private final ServerMonitoringMetrics metrics = mock(ServerMonitoringMetrics.class); private final GitlabGlobalSettingsValidator gitlabValidator = mock(GitlabGlobalSettingsValidator.class); private final DbClient dbClient = mock(DbClient.class); private final Configuration config = mock(Configuration.class); private final AlmSettingDao almSettingsDao = mock(AlmSettingDao.class); private final GitlabMetricsTask underTest = new GitlabMetricsTask(metrics, gitlabValidator, dbClient, config); @Before public void before() { when(dbClient.almSettingDao()).thenReturn(almSettingsDao); } @Test public void run_gitlabValidatorDoesntThrowException_setGreenStatusInMetricsOnce() { List<AlmSettingDto> dtos = generateDtos(5, ALM.GITLAB); when(almSettingsDao.selectByAlm(any(), any())).thenReturn(dtos); underTest.run(); verify(metrics, times(1)).setGitlabStatusToGreen(); verify(metrics, times(0)).setGitlabStatusToRed(); } @Test public void run_gitlabValidatorDoesntThrowException_setRedStatusInMetricsOnce() { List<AlmSettingDto> dtos = generateDtos(5, ALM.GITLAB); when(almSettingsDao.selectByAlm(any(), any())).thenReturn(dtos); doThrow(new RuntimeException()).when(gitlabValidator).validate(any()); underTest.run(); verify(metrics, times(0)).setGitlabStatusToGreen(); verify(metrics, times(1)).setGitlabStatusToRed(); } @Test public void run_gitlabIntegrationNotConfigured_setRedStatusInMetricsOnce() { when(almSettingsDao.selectByAlm(any(), any())).thenReturn(Collections.emptyList()); underTest.run(); verify(metrics, times(0)).setGitlabStatusToGreen(); verify(metrics, times(1)).setGitlabStatusToRed(); } }
3,372
36.065934
112
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/it/java/org/sonar/server/pushapi/scheduler/purge/PushEventsPurgeSchedulerAndExecutorIT.java
/* * 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.pushapi.scheduler.purge; import java.nio.charset.StandardCharsets; import java.util.Optional; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.pushevent.PushEventDto; import org.sonar.server.util.GlobalLockManagerImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; 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.server.pushapi.scheduler.purge.PushEventsPurgeScheduler.ENQUEUE_DELAY_IN_SECONDS; import static org.sonar.server.pushapi.scheduler.purge.PushEventsPurgeScheduler.INITIAL_DELAY_IN_SECONDS; public class PushEventsPurgeSchedulerAndExecutorIT { private static final String PUSH_EVENT_UUID = "push_event_uuid"; private static final long INITIAL_AND_ENQUE_DELAY_MS = 1L; @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private PushEventsPurgeScheduler pushEventsPurgeScheduler; @Before public void setup() { Configuration configuration = mock(Configuration.class); when(configuration.getLong(INITIAL_DELAY_IN_SECONDS)).thenReturn(Optional.of(INITIAL_AND_ENQUE_DELAY_MS)); when(configuration.getLong(ENQUEUE_DELAY_IN_SECONDS)).thenReturn(Optional.of(INITIAL_AND_ENQUE_DELAY_MS)); GlobalLockManagerImpl lockManager = mock(GlobalLockManagerImpl.class); when(lockManager.tryLock(any(), anyInt())).thenReturn(true); DbClient dbClient = dbTester.getDbClient(); pushEventsPurgeScheduler = new PushEventsPurgeScheduler( dbClient, configuration, lockManager, new PushEventsPurgeExecutorServiceImpl(), System2.INSTANCE ); } @Test public void pushEventsPurgeScheduler_shouldCleanUpPeriodically() throws InterruptedException { insertOldPushEvent(); assertThat(pushEventIsCleanedUp()).isFalse(); pushEventsPurgeScheduler.start(); await() .atMost(3, TimeUnit.SECONDS) .pollDelay(500, TimeUnit.MILLISECONDS) .until(this::pushEventIsCleanedUp); } private void insertOldPushEvent() { PushEventDto pushEventDto = new PushEventDto(); pushEventDto.setUuid(PUSH_EVENT_UUID); pushEventDto.setName("test_event"); pushEventDto.setProjectUuid("test_project_uuid"); pushEventDto.setPayload("payload".getBytes(StandardCharsets.UTF_8)); pushEventDto.setCreatedAt(1656633600); dbTester.getDbClient().pushEventDao().insert(dbTester.getSession(), pushEventDto); dbTester.commit(); } private boolean pushEventIsCleanedUp() { return dbTester.getDbClient().pushEventDao().selectByUuid(dbTester.getSession(), PUSH_EVENT_UUID) == null; } }
3,809
36.352941
110
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/HeartbeatTask.java
/* * 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.pushapi; class HeartbeatTask implements Runnable { private final ServerPushClient serverPushClient; public HeartbeatTask(ServerPushClient serverPushClient) { this.serverPushClient = serverPushClient; } @Override public void run() { synchronized (this) { serverPushClient.writeAndFlush('\r'); serverPushClient.writeAndFlush('\n'); } serverPushClient.scheduleHeartbeat(); } }
1,286
32
75
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/ServerPushAction.java
/* * 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.pushapi; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.sonar.server.ws.ServletRequest; import org.sonar.server.ws.ServletResponse; import org.sonar.server.ws.WsAction; public abstract class ServerPushAction implements WsAction { protected boolean isServerSideEventsRequest(ServletRequest request) { Map<String, String> headers = request.getHeaders(); String accept = headers.get("accept"); if (accept != null) { return accept.contains("text/event-stream"); } return false; } protected void setHeadersForResponse(ServletResponse response) throws IOException { response.stream().setStatus(HttpServletResponse.SC_OK); response.stream().setCharacterEncoding(StandardCharsets.UTF_8.name()); response.stream().setMediaType("text/event-stream"); // By adding this header, and not closing the connection, // we disable HTTP chunking, and we can use write()+flush() // to send data in the text/event-stream protocol response.setHeader("Connection", "close"); response.stream().flushBuffer(); } }
2,031
36.62963
85
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/ServerPushClient.java
/* * 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.pushapi; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.servlet.AsyncContext; import javax.servlet.AsyncListener; import javax.servlet.ServletOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class ServerPushClient { private static final Logger LOG = LoggerFactory.getLogger(ServerPushClient.class); private static final int DEFAULT_HEARTBEAT_PERIOD = 20; protected final AsyncContext asyncContext; private final ScheduledExecutorService executorService; private final HeartbeatTask heartbeatTask; private ScheduledFuture<?> startedHeartbeat; protected ServerPushClient(ScheduledExecutorService executorService, AsyncContext asyncContext) { this.executorService = executorService; this.asyncContext = asyncContext; this.heartbeatTask = new HeartbeatTask(this); } public void scheduleHeartbeat() { startedHeartbeat = executorService.schedule(heartbeatTask, DEFAULT_HEARTBEAT_PERIOD, TimeUnit.SECONDS); } public void writeAndFlush(String payload) throws IOException { payload = ensureCorrectMessageEnding(payload); output().write(payload.getBytes(StandardCharsets.UTF_8)); flush(); } private static String ensureCorrectMessageEnding(String payload) { return payload.endsWith("\n\n") ? payload : (payload + "\n\n"); } public void writeAndFlush(char character) { write(character); flush(); } public synchronized void write(char character) { try { output().write(character); } catch (IOException e) { handleIOException(e); } } public synchronized void flush() { try { output().flush(); } catch (IOException e) { handleIOException(e); } } private void handleIOException(IOException e) { String remoteAddr = asyncContext.getRequest().getRemoteAddr(); LOG.info(String.format("The server push client %s gone without notice, closing the connection (%s)", remoteAddr, e.getMessage())); throw new IllegalStateException(e.getMessage()); } public synchronized void close() { startedHeartbeat.cancel(false); try { asyncContext.complete(); } catch (IllegalStateException ex) { LOG.trace("Push connection was already closed"); } } private ServletOutputStream output() throws IOException { return asyncContext.getResponse().getOutputStream(); } public void addListener(AsyncListener asyncListener) { asyncContext.addListener(asyncListener); } }
3,514
31.247706
134
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/ServerPushModule.java
/* * 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.pushapi; import org.sonar.core.platform.Module; import org.sonar.server.pushapi.scheduler.polling.PushEventPollExecutorServiceImpl; import org.sonar.server.pushapi.scheduler.polling.PushEventPollScheduler; import org.sonar.server.pushapi.scheduler.purge.PushEventsPurgeExecutorServiceImpl; import org.sonar.server.pushapi.scheduler.purge.PushEventsPurgeScheduler; import org.sonar.server.pushapi.sonarlint.SonarLintClientPermissionsValidator; import org.sonar.server.pushapi.sonarlint.SonarLintClientsRegistry; import org.sonar.server.pushapi.sonarlint.SonarLintPushAction; public class ServerPushModule extends Module { @Override protected void configureModule() { add( ServerPushWs.class, SonarLintClientPermissionsValidator.class, SonarLintClientsRegistry.class, SonarLintPushAction.class, PushEventPollExecutorServiceImpl.class, PushEventPollScheduler.class, // Push Events Purge PushEventsPurgeScheduler.class, PushEventsPurgeExecutorServiceImpl.class); } }
1,899
38.583333
83
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/ServerPushWs.java
/* * 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.pushapi; import java.util.List; import org.sonar.api.server.ws.WebService; public class ServerPushWs implements WebService { private final List<ServerPushAction> actions; public ServerPushWs(List<ServerPushAction> actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context .createController("api/push") .setSince("9.4") .setDescription("Endpoints supporting server side events."); actions.forEach(action -> action.define(controller)); controller.done(); } }
1,439
31.727273
75
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/package-info.java
/* * 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. */ @javax.annotation.ParametersAreNonnullByDefault package org.sonar.server.pushapi;
925
41.090909
75
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/hotspots/HotspotChangeEventService.java
/* * 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.pushapi.hotspots; public interface HotspotChangeEventService { void distributeHotspotChangedEvent(String projectUuid, HotspotChangedEvent hotspotEvent); }
1,027
38.538462
91
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/hotspots/HotspotChangeEventServiceImpl.java
/* * 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.pushapi.hotspots; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.sonar.api.server.ServerSide; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.pushevent.PushEventDto; import static java.nio.charset.StandardCharsets.UTF_8; @ServerSide public class HotspotChangeEventServiceImpl implements HotspotChangeEventService { private static final Gson GSON = new GsonBuilder().create(); private static final String EVENT_NAME = "SecurityHotspotChanged"; private final DbClient dbClient; public HotspotChangeEventServiceImpl(DbClient dbClient) { this.dbClient = dbClient; } @Override public void distributeHotspotChangedEvent(String projectUuid, HotspotChangedEvent hotspotEvent) { persistEvent(projectUuid, hotspotEvent); } private void persistEvent(String projectUuid, HotspotChangedEvent hotspotEvent) { try (DbSession dbSession = dbClient.openSession(false)) { PushEventDto eventDto = new PushEventDto() .setName(EVENT_NAME) .setProjectUuid(projectUuid) .setPayload(serializeIssueToPushEvent(hotspotEvent)); dbClient.pushEventDao().insert(dbSession, eventDto); dbSession.commit(); } } private static byte[] serializeIssueToPushEvent(HotspotChangedEvent event) { return GSON.toJson(event).getBytes(UTF_8); } }
2,228
33.292308
99
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/hotspots/HotspotChangedEvent.java
/* * 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.pushapi.hotspots; import java.io.Serializable; import java.util.Date; import javax.annotation.CheckForNull; public class HotspotChangedEvent implements Serializable { private final String key; private final String projectKey; private final Long updateDate; private final String status; private final String assignee; private final String resolution; private final String filePath; private HotspotChangedEvent(Builder builder) { this.key = builder.getKey(); this.projectKey = builder.getProjectKey(); this.updateDate = builder.getUpdateDate() == null ? null : builder.getUpdateDate().getTime(); this.status = builder.getStatus(); this.filePath = builder.getFilePath(); this.resolution = builder.getResolution(); this.assignee = builder.getAssignee(); } public String getKey() { return key; } public String getProjectKey() { return projectKey; } public Long getUpdateDate() { return updateDate; } public String getStatus() { return status; } public String getFilePath() { return filePath; } @CheckForNull public String getResolution() { return resolution; } @CheckForNull public String getAssignee() { return assignee; } public static class Builder { private String key; private String projectKey; private Date updateDate; private String status; private String assignee; private String resolution; private String filePath; public Builder setKey(String key) { this.key = key; return this; } public Builder setProjectKey(String projectKey) { this.projectKey = projectKey; return this; } public Builder setUpdateDate(Date updateDate) { this.updateDate = updateDate; return this; } public Builder setStatus(String status) { this.status = status; return this; } public Builder setAssignee(String assignee) { this.assignee = assignee; return this; } public Builder setResolution(String resolution) { this.resolution = resolution; return this; } public Builder setFilePath(String filePath) { this.filePath = filePath; return this; } public String getKey() { return key; } public String getProjectKey() { return projectKey; } public Date getUpdateDate() { return updateDate; } public String getStatus() { return status; } public String getAssignee() { return assignee; } public String getResolution() { return resolution; } public String getFilePath() { return filePath; } public HotspotChangedEvent build() { return new HotspotChangedEvent(this); } } }
3,629
22.72549
97
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/hotspots/package-info.java
/* * 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. */ @javax.annotation.ParametersAreNonnullByDefault package org.sonar.server.pushapi.hotspots;
934
41.5
75
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/issues/IssueChangeEventService.java
/* * 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.pushapi.issues; import java.util.Collection; import java.util.Map; import javax.annotation.Nullable; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; public interface IssueChangeEventService { void distributeIssueChangeEvent(DefaultIssue issue, @Nullable String severity, @Nullable String type, @Nullable String transitionKey, BranchDto branch, String projectKey); void distributeIssueChangeEvent(Collection<DefaultIssue> issues, Map<String, ComponentDto> projectsByUuid, Map<String, BranchDto> branchesByProjectUuid); }
1,482
40.194444
108
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/issues/IssueChangeEventServiceImpl.java
/* * 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.pushapi.issues; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.server.ServerSide; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.FieldDiffs.Diff; import org.sonar.core.util.issue.Issue; import org.sonar.core.util.issue.IssueChangedEvent; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.pushevent.PushEventDto; import static java.nio.charset.StandardCharsets.UTF_8; import static org.elasticsearch.common.Strings.isNullOrEmpty; import static org.sonar.api.issue.DefaultTransitions.CONFIRM; import static org.sonar.api.issue.DefaultTransitions.FALSE_POSITIVE; import static org.sonar.api.issue.DefaultTransitions.UNCONFIRM; import static org.sonar.api.issue.DefaultTransitions.WONT_FIX; import static org.sonar.db.component.BranchType.BRANCH; @ServerSide public class IssueChangeEventServiceImpl implements IssueChangeEventService { private static final Gson GSON = new GsonBuilder().create(); private static final String EVENT_NAME = "IssueChanged"; private static final String FALSE_POSITIVE_KEY = "FALSE-POSITIVE"; private static final String WONT_FIX_KEY = "WONTFIX"; private static final String RESOLUTION_KEY = "resolution"; private static final String SEVERITY_KEY = "severity"; private static final String TYPE_KEY = "type"; private final DbClient dbClient; public IssueChangeEventServiceImpl(DbClient dbClient) { this.dbClient = dbClient; } @Override public void distributeIssueChangeEvent(DefaultIssue issue, @Nullable String severity, @Nullable String type, @Nullable String transition, BranchDto branch, String projectKey) { Issue changedIssue = new Issue(issue.key(), branch.getKey()); Boolean resolved = isResolved(transition); if (severity == null && type == null && resolved == null) { return; } IssueChangedEvent event = new IssueChangedEvent(projectKey, new Issue[]{changedIssue}, resolved, severity, type); persistEvent(event, branch.getProjectUuid()); } @Override public void distributeIssueChangeEvent(Collection<DefaultIssue> issues, Map<String, ComponentDto> projectsByUuid, Map<String, BranchDto> branchesByProjectUuid) { for (Entry<String, ComponentDto> entry : projectsByUuid.entrySet()) { String projectKey = entry.getValue().getKey(); Set<DefaultIssue> issuesInProject = issues .stream() .filter(i -> i.projectUuid().equals(entry.getKey())) .collect(Collectors.toSet()); Issue[] issueChanges = issuesInProject.stream() .filter(i -> branchesByProjectUuid.get(i.projectUuid()).getBranchType().equals(BRANCH)) .map(i -> new Issue(i.key(), branchesByProjectUuid.get(i.projectUuid()).getKey())) .toArray(Issue[]::new); if (issueChanges.length == 0) { continue; } IssueChangedEvent event = getIssueChangedEvent(projectKey, issuesInProject, issueChanges); if (event != null) { BranchDto branchDto = branchesByProjectUuid.get(entry.getKey()); persistEvent(event, branchDto.getProjectUuid()); } } } @CheckForNull private static IssueChangedEvent getIssueChangedEvent(String projectKey, Set<DefaultIssue> issuesInProject, Issue[] issueChanges) { DefaultIssue firstIssue = issuesInProject.stream().iterator().next(); if (firstIssue.currentChange() == null) { return null; } Boolean resolved = null; String severity = null; String type = null; boolean isRelevantEvent = false; Map<String, Diff> diffs = firstIssue.currentChange().diffs(); if (diffs.containsKey(RESOLUTION_KEY)) { resolved = diffs.get(RESOLUTION_KEY).newValue() == null ? false : isResolved(diffs.get(RESOLUTION_KEY).newValue().toString()); isRelevantEvent = true; } if (diffs.containsKey(SEVERITY_KEY)) { severity = diffs.get(SEVERITY_KEY).newValue() == null ? null : diffs.get(SEVERITY_KEY).newValue().toString(); isRelevantEvent = true; } if (diffs.containsKey(TYPE_KEY)) { type = diffs.get(TYPE_KEY).newValue() == null ? null : diffs.get(TYPE_KEY).newValue().toString(); isRelevantEvent = true; } if (!isRelevantEvent) { return null; } return new IssueChangedEvent(projectKey, issueChanges, resolved, severity, type); } @CheckForNull private static Boolean isResolved(@Nullable String transitionOrStatus) { if (isNullOrEmpty(transitionOrStatus)) { return null; } if (transitionOrStatus.equals(CONFIRM) || transitionOrStatus.equals(UNCONFIRM)) { return null; } return transitionOrStatus.equals(WONT_FIX) || transitionOrStatus.equals(FALSE_POSITIVE) || transitionOrStatus.equals(FALSE_POSITIVE_KEY) || transitionOrStatus.equals(WONT_FIX_KEY); } private void persistEvent(IssueChangedEvent event, String entry) { try (DbSession dbSession = dbClient.openSession(false)) { PushEventDto eventDto = new PushEventDto() .setName(EVENT_NAME) .setProjectUuid(entry) .setPayload(serializeIssueToPushEvent(event)); dbClient.pushEventDao().insert(dbSession, eventDto); dbSession.commit(); } } private static byte[] serializeIssueToPushEvent(IssueChangedEvent event) { return GSON.toJson(event).getBytes(UTF_8); } }
6,511
34.977901
139
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/issues/package-info.java
/* * 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. */ @javax.annotation.ParametersAreNonnullByDefault package org.sonar.server.pushapi.issues;
932
41.409091
75
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/qualityprofile/QualityProfileChangeEventService.java
/* * 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.pushapi.qualityprofile; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; import org.sonar.db.project.ProjectDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.server.qualityprofile.ActiveRuleChange; public interface QualityProfileChangeEventService { void publishRuleActivationToSonarLintClients(ProjectDto project, @Nullable QProfileDto activatedProfile, @Nullable QProfileDto deactivatedProfile); void distributeRuleChangeEvent(Collection<QProfileDto> profiles, List<ActiveRuleChange> activeRuleChanges, String language); }
1,458
40.685714
149
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/qualityprofile/QualityProfileChangeEventServiceImpl.java
/* * 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.pushapi.qualityprofile; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.sonar.api.rule.RuleKey; import org.sonar.api.server.ServerSide; import org.sonar.core.util.ParamChange; import org.sonar.core.util.rule.RuleChange; import org.sonar.core.util.rule.RuleSetChangedEvent; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.pushevent.PushEventDto; import org.sonar.db.qualityprofile.ActiveRuleDto; import org.sonar.db.qualityprofile.ActiveRuleParamDto; import org.sonar.db.qualityprofile.OrgActiveRuleDto; import org.sonar.db.qualityprofile.ProjectQprofileAssociationDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.rule.RuleDto; import org.sonar.server.qualityprofile.ActiveRuleChange; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.emptyList; import static java.util.function.Predicate.not; import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.ACTIVATED; import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.DEACTIVATED; import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.UPDATED; @ServerSide public class QualityProfileChangeEventServiceImpl implements QualityProfileChangeEventService { private static final Gson GSON = new GsonBuilder().create(); private static final String EVENT_NAME = "RuleSetChanged"; private final DbClient dbClient; public QualityProfileChangeEventServiceImpl(DbClient dbClient) { this.dbClient = dbClient; } @Override public void publishRuleActivationToSonarLintClients(ProjectDto project, @Nullable QProfileDto activatedProfile, @Nullable QProfileDto deactivatedProfile) { List<RuleChange> activatedRules = new ArrayList<>(); Set<String> deactivatedRules = new HashSet<>(); if (activatedProfile != null) { activatedRules.addAll(createRuleChanges(activatedProfile)); } if (deactivatedProfile != null) { deactivatedRules.addAll(getRuleKeys(deactivatedProfile)); } if (activatedRules.isEmpty() && deactivatedRules.isEmpty()) { return; } String language = activatedProfile != null ? activatedProfile.getLanguage() : deactivatedProfile.getLanguage(); persistPushEvent(project.getKey(), activatedRules.toArray(new RuleChange[0]), deactivatedRules, language, project.getUuid()); } private List<RuleChange> createRuleChanges(@NotNull QProfileDto profileDto) { List<RuleChange> ruleChanges = new ArrayList<>(); try (DbSession dbSession = dbClient.openSession(false)) { List<OrgActiveRuleDto> activeRuleDtos = dbClient.activeRuleDao().selectByProfile(dbSession, profileDto); List<String> activeRuleUuids = activeRuleDtos.stream().map(ActiveRuleDto::getUuid).toList(); Map<String, List<ActiveRuleParamDto>> paramsByActiveRuleUuid = dbClient.activeRuleDao().selectParamsByActiveRuleUuids(dbSession, activeRuleUuids) .stream().collect(Collectors.groupingBy(ActiveRuleParamDto::getActiveRuleUuid)); Map<String, String> activeRuleUuidByRuleUuid = activeRuleDtos.stream().collect(Collectors.toMap(ActiveRuleDto::getRuleUuid, ActiveRuleDto::getUuid)); List<String> ruleUuids = activeRuleDtos.stream().map(ActiveRuleDto::getRuleUuid).toList(); List<RuleDto> ruleDtos = dbClient.ruleDao().selectByUuids(dbSession, ruleUuids); for (RuleDto ruleDto : ruleDtos) { String activeRuleUuid = activeRuleUuidByRuleUuid.get(ruleDto.getUuid()); List<ActiveRuleParamDto> params = paramsByActiveRuleUuid.getOrDefault(activeRuleUuid, new ArrayList<>()); RuleChange ruleChange = toRuleChange(ruleDto, params); ruleChanges.add(ruleChange); } } return ruleChanges; } private Set<String> getRuleKeys(@NotNull QProfileDto profileDto) { Set<String> ruleKeys = new HashSet<>(); try (DbSession dbSession = dbClient.openSession(false)) { List<OrgActiveRuleDto> activeRuleDtos = dbClient.activeRuleDao().selectByProfile(dbSession, profileDto); List<String> ruleUuids = activeRuleDtos.stream().map(ActiveRuleDto::getRuleUuid).toList(); List<RuleDto> ruleDtos = dbClient.ruleDao().selectByUuids(dbSession, ruleUuids); for (RuleDto ruleDto : ruleDtos) { ruleKeys.add(ruleDto.getKey().toString()); } } return ruleKeys; } @NotNull private RuleChange toRuleChange(RuleDto ruleDto, List<ActiveRuleParamDto> activeRuleParamDtos) { RuleChange ruleChange = new RuleChange(); ruleChange.setKey(ruleDto.getKey().toString()); ruleChange.setLanguage(ruleDto.getLanguage()); ruleChange.setSeverity(ruleDto.getSeverityString()); List<ParamChange> paramChanges = new ArrayList<>(); for (ActiveRuleParamDto activeRuleParam : activeRuleParamDtos) { paramChanges.add(new ParamChange(activeRuleParam.getKey(), activeRuleParam.getValue())); } ruleChange.setParams(paramChanges.toArray(new ParamChange[0])); String templateUuid = ruleDto.getTemplateUuid(); if (templateUuid != null && !"".equals(templateUuid)) { try (DbSession dbSession = dbClient.openSession(false)) { RuleDto templateRule = dbClient.ruleDao().selectByUuid(templateUuid, dbSession) .orElseThrow(() -> new IllegalStateException(String.format("Unknown Template Rule '%s'", templateUuid))); ruleChange.setTemplateKey(templateRule.getKey().toString()); } } return ruleChange; } public void distributeRuleChangeEvent(Collection<QProfileDto> profiles, List<ActiveRuleChange> activeRuleChanges, String language) { if (activeRuleChanges.isEmpty()) { return; } Set<RuleChange> activatedRules = new HashSet<>(); for (ActiveRuleChange arc : activeRuleChanges) { ActiveRuleDto activeRule = arc.getActiveRule(); if (activeRule == null) { continue; } RuleChange ruleChange = new RuleChange(); ruleChange.setKey(activeRule.getRuleKey().toString()); ruleChange.setSeverity(arc.getSeverity()); ruleChange.setLanguage(language); Optional<String> templateKey = templateKey(arc); templateKey.ifPresent(ruleChange::setTemplateKey); // params List<ParamChange> paramChanges = new ArrayList<>(); for (Map.Entry<String, String> entry : arc.getParameters().entrySet()) { paramChanges.add(new ParamChange(entry.getKey(), entry.getValue())); } ruleChange.setParams(paramChanges.toArray(new ParamChange[0])); if (ACTIVATED.equals(arc.getType()) || UPDATED.equals(arc.getType())) { activatedRules.add(ruleChange); } } Set<String> deactivatedRules = activeRuleChanges.stream() .filter(r -> DEACTIVATED.equals(r.getType())) .map(ActiveRuleChange::getActiveRule) .filter(not(Objects::isNull)) .map(ActiveRuleDto::getRuleKey) .map(RuleKey::toString) .collect(Collectors.toSet()); if (activatedRules.isEmpty() && deactivatedRules.isEmpty()) { return; } Map<String, String> projectsUuidByKey = getProjectsUuidByKey(profiles, language); for (Map.Entry<String, String> entry : projectsUuidByKey.entrySet()) { persistPushEvent(entry.getKey(), activatedRules.toArray(new RuleChange[0]), deactivatedRules, language, entry.getValue()); } } private void persistPushEvent(String projectKey, RuleChange[] activatedRules, Set<String> deactivatedRules, String language, String projectUuid) { RuleSetChangedEvent event = new RuleSetChangedEvent(projectKey, activatedRules, deactivatedRules.toArray(new String[0])); try (DbSession dbSession = dbClient.openSession(false)) { PushEventDto eventDto = new PushEventDto() .setName(EVENT_NAME) .setProjectUuid(projectUuid) .setLanguage(language) .setPayload(serializeIssueToPushEvent(event)); dbClient.pushEventDao().insert(dbSession, eventDto); dbSession.commit(); } } private Optional<String> templateKey(ActiveRuleChange arc) { try (DbSession dbSession = dbClient.openSession(false)) { String ruleUuid = arc.getRuleUuid(); RuleDto rule = dbClient.ruleDao().selectByUuid(ruleUuid, dbSession).orElseThrow(() -> new IllegalStateException("unknow rule")); String templateUuid = rule.getTemplateUuid(); if (StringUtils.isNotEmpty(templateUuid)) { RuleDto templateRule = dbClient.ruleDao().selectByUuid(templateUuid, dbSession) .orElseThrow(() -> new IllegalStateException(String.format("Unknown Template Rule '%s'", templateUuid))); return Optional.of(templateRule.getKey().toString()); } } return Optional.empty(); } private Map<String, String> getProjectsUuidByKey(Collection<QProfileDto> profiles, String language) { try (DbSession dbSession = dbClient.openSession(false)) { Map<Boolean, List<QProfileDto>> profilesByDefaultStatus = classifyQualityProfilesByDefaultStatus(dbSession, profiles, language); List<ProjectDto> defaultAssociatedProjects = getDefaultAssociatedQualityProfileProjects(dbSession, profilesByDefaultStatus.get(true), language); List<ProjectDto> manuallyAssociatedProjects = getManuallyAssociatedQualityProfileProjects(dbSession, profilesByDefaultStatus.get(false)); return Stream .concat(manuallyAssociatedProjects.stream(), defaultAssociatedProjects.stream()) .collect(Collectors.toMap(ProjectDto::getKey, ProjectDto::getUuid)); } } private Map<Boolean, List<QProfileDto>> classifyQualityProfilesByDefaultStatus(DbSession dbSession, Collection<QProfileDto> profiles, String language) { String defaultQualityProfileUuid = dbClient.qualityProfileDao().selectDefaultProfileUuid(dbSession, language); Predicate<QProfileDto> isDefaultQualityProfile = profile -> profile.getKee().equals(defaultQualityProfileUuid); return profiles .stream() .collect(Collectors.partitioningBy(isDefaultQualityProfile)); } private List<ProjectDto> getDefaultAssociatedQualityProfileProjects(DbSession dbSession, List<QProfileDto> defaultProfiles, String language) { if (defaultProfiles.isEmpty()) { return emptyList(); } return getDefaultQualityProfileAssociatedProjects(dbSession, language); } private List<ProjectDto> getDefaultQualityProfileAssociatedProjects(DbSession dbSession, String language) { Set<String> associatedProjectUuids = dbClient.projectDao().selectProjectUuidsAssociatedToDefaultQualityProfileByLanguage(dbSession, language); return dbClient.projectDao().selectByUuids(dbSession, associatedProjectUuids); } private List<ProjectDto> getManuallyAssociatedQualityProfileProjects(DbSession dbSession, List<QProfileDto> profiles) { return profiles .stream() .map(profile -> getQualityProfileAssociatedProjects(dbSession, profile)) .flatMap(Collection::stream) .toList(); } private List<ProjectDto> getQualityProfileAssociatedProjects(DbSession dbSession, QProfileDto profile) { Set<String> projectUuids = getQualityProfileAssociatedProjectUuids(dbSession, profile); return dbClient.projectDao().selectByUuids(dbSession, projectUuids); } private Set<String> getQualityProfileAssociatedProjectUuids(DbSession dbSession, QProfileDto profile) { List<ProjectQprofileAssociationDto> associations = dbClient.qualityProfileDao().selectSelectedProjects(dbSession, profile, null); return associations .stream() .map(ProjectQprofileAssociationDto::getProjectUuid) .collect(Collectors.toSet()); } private static byte[] serializeIssueToPushEvent(RuleSetChangedEvent event) { return GSON.toJson(event).getBytes(UTF_8); } }
13,019
41.410423
155
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/qualityprofile/package-info.java
/* * 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. */ @javax.annotation.ParametersAreNonnullByDefault package org.sonar.server.pushapi.qualityprofile;
940
41.772727
75
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/scheduler/package-info.java
/* * 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. */ @javax.annotation.ParametersAreNonnullByDefault package org.sonar.server.pushapi.scheduler;
935
41.545455
75
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/scheduler/polling/PushEventExecutorService.java
/* * 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.pushapi.scheduler.polling; import java.util.concurrent.ScheduledExecutorService; import org.sonar.api.server.ServerSide; @ServerSide public interface PushEventExecutorService extends ScheduledExecutorService { }
1,083
36.37931
76
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/scheduler/polling/PushEventPollExecutorServiceImpl.java
/* * 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.pushapi.scheduler.polling; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.sonar.server.util.AbstractStoppableScheduledExecutorServiceImpl; import static java.lang.Thread.MIN_PRIORITY; import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; public class PushEventPollExecutorServiceImpl extends AbstractStoppableScheduledExecutorServiceImpl<ScheduledExecutorService> implements PushEventExecutorService { public PushEventPollExecutorServiceImpl() { super(newSingleThreadScheduledExecutor(PushEventPollExecutorServiceImpl::createThread)); } static Thread createThread(Runnable r) { Thread thread = Executors.defaultThreadFactory().newThread(r); thread.setName("PushEventPoll-%d"); thread.setPriority(MIN_PRIORITY); thread.setDaemon(true); return thread; } }
1,743
38.636364
111
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/scheduler/polling/PushEventPollScheduler.java
/* * 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.pushapi.scheduler.polling; import java.util.Collection; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.System2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.pushevent.PushEventDto; import org.sonar.server.pushapi.sonarlint.SonarLintClient; import org.sonar.server.pushapi.sonarlint.SonarLintClientsRegistry; import org.sonar.server.pushapi.sonarlint.SonarLintPushEvent; @ServerSide public class PushEventPollScheduler implements Startable { private static final Logger LOG = LoggerFactory.getLogger(PushEventPollScheduler.class); private static final String INITIAL_DELAY_IN_SECONDS = "sonar.pushevents.polling.initial.delay"; private static final String LAST_TIMESTAMP_IN_SECONDS = "sonar.pushevents.polling.last.timestamp"; private static final String PERIOD_IN_SECONDS = "sonar.pushevents.polling.period"; private static final String PAGE_SIZE = "sonar.pushevents.polling.page.size"; private final PushEventExecutorService executorService; private final SonarLintClientsRegistry clientsRegistry; private final DbClient dbClient; private final System2 system2; private final Configuration config; private Long lastPullTimestamp = null; private String lastSeenUuid = null; public PushEventPollScheduler(PushEventExecutorService executorService, SonarLintClientsRegistry clientsRegistry, DbClient dbClient, System2 system2, Configuration config) { this.executorService = executorService; this.clientsRegistry = clientsRegistry; this.dbClient = dbClient; this.system2 = system2; this.config = config; } @Override public void start() { this.executorService.scheduleAtFixedRate(this::tryBroadcastEvents, getInitialDelay(), getPeriod(), TimeUnit.SECONDS); } private void tryBroadcastEvents() { try { doBroadcastEvents(); } catch (Exception e) { LOG.warn("Failed to poll for push events", e); } } private void doBroadcastEvents() { var clients = clientsRegistry.getClients(); if (clients.isEmpty()) { lastPullTimestamp = null; lastSeenUuid = null; return; } if (lastPullTimestamp == null) { lastPullTimestamp = getLastPullTimestamp(); } var projectUuids = getClientsProjectUuids(clients); try (DbSession dbSession = dbClient.openSession(false)) { Deque<PushEventDto> events = getPushEvents(dbSession, projectUuids); LOG.debug("Received {} push events, attempting to broadcast to {} registered clients.", events.size(), clients.size()); events.forEach(pushEventDto -> mapToSonarLintPushEvent(pushEventDto) .ifPresent(clientsRegistry::broadcastMessage)); if (!events.isEmpty()) { var last = events.getLast(); lastPullTimestamp = last.getCreatedAt(); lastSeenUuid = last.getUuid(); } } } private static Optional<SonarLintPushEvent> mapToSonarLintPushEvent(PushEventDto pushEventDto) { return Optional.of(new SonarLintPushEvent(pushEventDto.getName(), pushEventDto.getPayload(), pushEventDto.getProjectUuid(), pushEventDto.getLanguage())); } private static Set<String> getClientsProjectUuids(List<SonarLintClient> clients) { return clients.stream() .map(SonarLintClient::getClientProjectUuids) .flatMap(Collection::stream) .collect(Collectors.toSet()); } private Deque<PushEventDto> getPushEvents(DbSession dbSession, Set<String> projectUuids) { if (projectUuids.isEmpty()) { return new LinkedList<>(); } return dbClient.pushEventDao().selectChunkByProjectUuids(dbSession, projectUuids, lastPullTimestamp, lastSeenUuid, getPageSize()); } public long getInitialDelay() { // two minutes default initial delay return config.getLong(INITIAL_DELAY_IN_SECONDS).orElse(2 * 60L); } public long getPeriod() { // execute every 40 seconds return config.getLong(PERIOD_IN_SECONDS).orElse(40L); } public long getLastPullTimestamp() { // execute every 40 seconds return config.getLong(LAST_TIMESTAMP_IN_SECONDS).orElse(system2.now()); } public long getPageSize() { return config.getLong(PAGE_SIZE).orElse(20L); } @Override public void stop() { // nothing to do } }
5,457
33.544304
134
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/scheduler/polling/package-info.java
/* * 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. */ @javax.annotation.ParametersAreNonnullByDefault package org.sonar.server.pushapi.scheduler.polling;
943
41.909091
75
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/scheduler/purge/PushEventsPurgeExecutorService.java
/* * 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.pushapi.scheduler.purge; import java.util.concurrent.ScheduledExecutorService; import org.sonar.api.server.ServerSide; @ServerSide public interface PushEventsPurgeExecutorService extends ScheduledExecutorService { }
1,086
37.821429
82
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/scheduler/purge/PushEventsPurgeExecutorServiceImpl.java
/* * 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.pushapi.scheduler.purge; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.sonar.server.util.AbstractStoppableScheduledExecutorServiceImpl; public class PushEventsPurgeExecutorServiceImpl extends AbstractStoppableScheduledExecutorServiceImpl<ScheduledExecutorService> implements PushEventsPurgeExecutorService { public PushEventsPurgeExecutorServiceImpl() { super(Executors.newSingleThreadScheduledExecutor(r -> { Thread thread = Executors.defaultThreadFactory().newThread(r); thread.setDaemon(true); thread.setName(String.format("PushEvent-Purge-%d", System.nanoTime())); return thread; })); } }
1,562
39.076923
81
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/scheduler/purge/PushEventsPurgeScheduler.java
/* * 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.pushapi.scheduler.purge; import com.google.common.annotations.VisibleForTesting; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Set; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.System2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.server.util.GlobalLockManager; import static java.util.concurrent.TimeUnit.SECONDS; @ServerSide public class PushEventsPurgeScheduler implements Startable { private static final Logger LOG = LoggerFactory.getLogger(PushEventsPurgeScheduler.class); private static final String LOCK_NAME = "PushPurgeCheck"; @VisibleForTesting static final String INITIAL_DELAY_IN_SECONDS = "sonar.push.events.purge.initial.delay"; @VisibleForTesting static final String ENQUEUE_DELAY_IN_SECONDS = "sonar.push.events.purge.enqueue.delay"; private static final int ENQUEUE_LOCK_DELAY_IN_SECONDS = 60; private final DbClient dbClient; private final Configuration config; private final GlobalLockManager lockManager; private final PushEventsPurgeExecutorService executorService; private final System2 system; public PushEventsPurgeScheduler(DbClient dbClient, Configuration config, GlobalLockManager lockManager, PushEventsPurgeExecutorService executorService, System2 system) { this.dbClient = dbClient; this.executorService = executorService; this.config = config; this.lockManager = lockManager; this.system = system; } @Override public void start() { executorService.scheduleAtFixedRate(this::checks, getInitialDelay(), getEnqueueDelay(), SECONDS); } private void checks() { try { // Avoid enqueueing push events purge task multiple times if (!lockManager.tryLock(LOCK_NAME, ENQUEUE_LOCK_DELAY_IN_SECONDS)) { return; } purgeExpiredPushEvents(); } catch (Exception e) { LOG.error("Error in Push Events Purge scheduler", e); } } private void purgeExpiredPushEvents() { try (DbSession dbSession = dbClient.openSession(false)) { Set<String> uuids = dbClient.pushEventDao().selectUuidsOfExpiredEvents(dbSession, getExpiredTimestamp()); LOG.debug(String.format("%s push events to be deleted...", uuids.size())); dbClient.pushEventDao().deleteByUuids(dbSession, uuids); dbSession.commit(); } } public long getInitialDelay() { return config.getLong(INITIAL_DELAY_IN_SECONDS).orElse(60 * 60L); } public long getEnqueueDelay() { return config.getLong(ENQUEUE_DELAY_IN_SECONDS).orElse(60 * 60L); } private long getExpiredTimestamp() { return Instant.ofEpochMilli(system.now()) .minus(1, ChronoUnit.HOURS) .toEpochMilli(); } @Override public void stop() { // nothing to do } }
3,786
33.117117
111
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/scheduler/purge/package-info.java
/* * 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. */ @javax.annotation.ParametersAreNonnullByDefault package org.sonar.server.pushapi.scheduler.purge;
941
41.818182
75
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/sonarlint/SonarLintClient.java
/* * 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.pushapi.sonarlint; import java.util.Objects; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import javax.servlet.AsyncContext; import org.sonar.server.pushapi.ServerPushClient; public class SonarLintClient extends ServerPushClient { private static final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); private final Set<String> languages; private final Set<String> projectUuids; private final String userUuid; public SonarLintClient(AsyncContext asyncContext, Set<String> projectUuids, Set<String> languages, String userUuid) { super(scheduledExecutorService, asyncContext); this.projectUuids = projectUuids; this.languages = languages; this.userUuid = userUuid; } public Set<String> getLanguages() { return languages; } public Set<String> getClientProjectUuids() { return projectUuids; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SonarLintClient that = (SonarLintClient) o; return languages.equals(that.languages) && projectUuids.equals(that.projectUuids) && asyncContext.equals(that.asyncContext); } @Override public int hashCode() { return Objects.hash(languages, projectUuids); } public String getUserUuid() { return userUuid; } }
2,345
29.868421
120
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/sonarlint/SonarLintClientPermissionsValidator.java
/* * 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.pushapi.sonarlint; import java.util.List; import java.util.Set; import org.sonar.api.server.ServerSide; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.user.UserSession; import org.sonar.server.user.UserSessionFactory; @ServerSide public class SonarLintClientPermissionsValidator { private final DbClient dbClient; private final UserSessionFactory userSessionFactory; public SonarLintClientPermissionsValidator(DbClient dbClient, UserSessionFactory userSessionFactory) { this.dbClient = dbClient; this.userSessionFactory = userSessionFactory; } public List<ProjectDto> validateUserCanReceivePushEventForProjects(UserSession userSession, Set<String> projectKeys) { List<ProjectDto> projectDtos; try (DbSession dbSession = dbClient.openSession(false)) { projectDtos = dbClient.projectDao().selectProjectsByKeys(dbSession, projectKeys); } validateProjectPermissions(userSession, projectDtos); return projectDtos; } public void validateUserCanReceivePushEventForProjectUuids(String userUuid, Set<String> projectUuids) { UserDto userDto; try (DbSession dbSession = dbClient.openSession(false)) { userDto = dbClient.userDao().selectByUuid(dbSession, userUuid); } if (userDto == null) { throw new ForbiddenException("User does not exist"); } UserSession userSession = userSessionFactory.create(userDto); List<ProjectDto> projectDtos; try (DbSession dbSession = dbClient.openSession(false)) { projectDtos = dbClient.projectDao().selectByUuids(dbSession, projectUuids); } validateProjectPermissions(userSession, projectDtos); } private static void validateProjectPermissions(UserSession userSession, List<ProjectDto> projectDtos) { validateUsersDeactivationStatus(userSession); for (ProjectDto projectDto : projectDtos) { userSession.checkEntityPermission(UserRole.USER, projectDto); } } private static void validateUsersDeactivationStatus(UserSession userSession) { if (!userSession.isActive()) { throw new ForbiddenException("User doesn't have rights to requested resource anymore."); } } }
3,209
37.674699
120
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/sonarlint/SonarLintClientsRegistry.java
/* * 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.pushapi.sonarlint; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; import org.sonar.api.server.ServerSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.server.exceptions.ForbiddenException; @ServerSide public class SonarLintClientsRegistry { private static final Logger LOG = LoggerFactory.getLogger(SonarLintClientsRegistry.class); private final SonarLintClientPermissionsValidator sonarLintClientPermissionsValidator; private final List<SonarLintClient> clients = new CopyOnWriteArrayList<>(); public SonarLintClientsRegistry(SonarLintClientPermissionsValidator permissionsValidator) { this.sonarLintClientPermissionsValidator = permissionsValidator; } public void registerClient(SonarLintClient sonarLintClient) { clients.add(sonarLintClient); sonarLintClient.scheduleHeartbeat(); sonarLintClient.addListener(new SonarLintClientEventsListener(sonarLintClient)); LOG.debug("Registering new SonarLint client"); } public void unregisterClient(SonarLintClient client) { client.close(); clients.remove(client); LOG.debug("Removing SonarLint client"); } public List<SonarLintClient> getClients() { return clients; } public long countConnectedClients() { return clients.size(); } public void broadcastMessage(SonarLintPushEvent event) { clients.stream().filter(client -> isRelevantEvent(event, client)) .forEach(c -> { Set<String> clientProjectUuids = new HashSet<>(c.getClientProjectUuids()); clientProjectUuids.retainAll(Set.of(event.getProjectUuid())); try { sonarLintClientPermissionsValidator.validateUserCanReceivePushEventForProjectUuids(c.getUserUuid(), clientProjectUuids); c.writeAndFlush(event.serialize()); } catch (ForbiddenException forbiddenException) { logClientUnauthenticated(forbiddenException); unregisterClient(c); } catch (IllegalStateException | IOException e) { logUnexpectedError(e); unregisterClient(c); } }); } private static boolean isRelevantEvent(SonarLintPushEvent event, SonarLintClient client) { return client.getClientProjectUuids().contains(event.getProjectUuid()) && (!event.getName().equals("RuleSetChanged") || client.getLanguages().contains(event.getLanguage())); } private static void logUnexpectedError(Exception e) { LOG.error("Unable to send message to a client: " + e.getMessage()); } private static void logClientUnauthenticated(ForbiddenException forbiddenException) { LOG.debug("Client is no longer authenticated: " + forbiddenException.getMessage()); } class SonarLintClientEventsListener implements AsyncListener { private final SonarLintClient client; public SonarLintClientEventsListener(SonarLintClient sonarLintClient) { this.client = sonarLintClient; } @Override public void onComplete(AsyncEvent event) { unregisterClient(client); } @Override public void onError(AsyncEvent event) { unregisterClient(client); } @Override public void onStartAsync(AsyncEvent event) { // nothing to do on start } @Override public void onTimeout(AsyncEvent event) { unregisterClient(client); } } }
4,334
33.133858
130
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/sonarlint/SonarLintPushAction.java
/* * 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.pushapi.sonarlint; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.servlet.AsyncContext; import javax.servlet.http.HttpServletResponse; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.server.pushapi.ServerPushAction; import org.sonar.server.user.UserSession; import org.sonar.server.ws.ServletRequest; import org.sonar.server.ws.ServletResponse; public class SonarLintPushAction extends ServerPushAction { private static final String PROJECT_PARAM_KEY = "projectKeys"; private static final String LANGUAGE_PARAM_KEY = "languages"; private final SonarLintClientsRegistry clientsRegistry; private final SonarLintClientPermissionsValidator permissionsValidator; private final UserSession userSession; private final DbClient dbClient; public SonarLintPushAction(SonarLintClientsRegistry sonarLintClientRegistry, UserSession userSession, DbClient dbClient, SonarLintClientPermissionsValidator permissionsValidator) { this.clientsRegistry = sonarLintClientRegistry; this.userSession = userSession; this.dbClient = dbClient; this.permissionsValidator = permissionsValidator; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller .createAction("sonarlint_events") .setInternal(true) .setDescription("Endpoint for listening to server side events. Currently it notifies listener about change to activation of a rule") .setSince("9.4") .setHandler(this); action .createParam(PROJECT_PARAM_KEY) .setDescription("Comma-separated list of projects keys for which events will be delivered") .setRequired(true) .setExampleValue("example-project-key,example-project-key2"); action .createParam(LANGUAGE_PARAM_KEY) .setDescription("Comma-separated list of languages for which events will be delivered") .setRequired(true) .setExampleValue("java,cobol"); } @Override public void handle(Request request, Response response) throws IOException { userSession.checkLoggedIn(); ServletRequest servletRequest = (ServletRequest) request; ServletResponse servletResponse = (ServletResponse) response; var params = new SonarLintPushActionParamsValidator(request); params.validateParams(); List<ProjectDto> projectDtos = permissionsValidator.validateUserCanReceivePushEventForProjects(userSession, params.projectKeys); if (!isServerSideEventsRequest(servletRequest)) { servletResponse.stream().setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); return; } setHeadersForResponse(servletResponse); AsyncContext asyncContext = servletRequest.startAsync(); asyncContext.setTimeout(0); Set<String> projectUuids = projectDtos.stream().map(ProjectDto::getUuid).collect(Collectors.toSet()); SonarLintClient sonarLintClient = new SonarLintClient(asyncContext, projectUuids, params.getLanguages(), userSession.getUuid()); clientsRegistry.registerClient(sonarLintClient); } class SonarLintPushActionParamsValidator { private final Request request; private final Set<String> projectKeys; private final Set<String> languages; SonarLintPushActionParamsValidator(Request request) { this.request = request; this.projectKeys = parseParam(PROJECT_PARAM_KEY); this.languages = parseParam(LANGUAGE_PARAM_KEY); } Set<String> getLanguages() { return languages; } private Set<String> parseParam(String paramKey) { String paramProjectKeys = request.getParam(paramKey).getValue(); if (paramProjectKeys == null) { throw new IllegalArgumentException("Param " + paramKey + " was not provided."); } return Set.of(paramProjectKeys.trim().split(",")); } private void validateParams() { List<ProjectDto> projectDtos; try (DbSession dbSession = dbClient.openSession(false)) { projectDtos = dbClient.projectDao().selectProjectsByKeys(dbSession, projectKeys); } if (projectDtos.size() < projectKeys.size() || projectDtos.isEmpty()) { throw new IllegalArgumentException("Param " + PROJECT_PARAM_KEY + " is invalid."); } } } }
5,331
36.027778
138
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/sonarlint/SonarLintPushEvent.java
/* * 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.pushapi.sonarlint; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static java.nio.charset.StandardCharsets.UTF_8; public class SonarLintPushEvent { private final String name; private final byte[] data; private final String projectUuid; private final String language; public SonarLintPushEvent(String name, byte[] data, String projectUuid, @Nullable String language) { this.name = name; this.data = data; this.projectUuid = projectUuid; this.language = language; } public String getProjectUuid() { return projectUuid; } @CheckForNull public String getLanguage() { return language; } public String getName() { return name; } public byte[] getData() { return data; } public String serialize() { return "event: " + this.name + "\n" + "data: " + new String(this.data, UTF_8); } }
1,762
26.546875
102
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/main/java/org/sonar/server/pushapi/sonarlint/package-info.java
/* * 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. */ @javax.annotation.ParametersAreNonnullByDefault package org.sonar.server.pushapi.sonarlint;
935
41.545455
75
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/HeartbeatTaskTest.java
/* * 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.pushapi; import org.junit.Test; import static org.mockito.ArgumentMatchers.anyChar; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class HeartbeatTaskTest { private final ServerPushClient serverPushClient = mock(ServerPushClient.class); private final HeartbeatTask underTest = new HeartbeatTask(serverPushClient); @Test public void run_reSchedulesHeartBeat() { underTest.run(); verify(serverPushClient, times(2)).writeAndFlush(anyChar()); verify(serverPushClient).scheduleHeartbeat(); } }
1,469
33.186047
81
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/ServerPushClientTest.java
/* * 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.pushapi; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.servlet.AsyncContext; import javax.servlet.AsyncListener; import javax.servlet.ServletOutputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ServerPushClientTest { private final ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); private final AsyncContext asyncContext = mock(AsyncContext.class); private final ServerPushClient underTest = new ServerPushClient(executorService, asyncContext) {}; private final ServletOutputStream outputStream = mock(ServletOutputStream.class); private final ScheduledFuture task = mock(ScheduledFuture.class); private ServletResponse servletResponse; @Before public void before() throws IOException { servletResponse = mock(ServletResponse.class); when(servletResponse.getOutputStream()).thenReturn(outputStream); when(asyncContext.getResponse()).thenReturn(servletResponse); when(asyncContext.getRequest()).thenReturn(mock(ServletRequest.class)); } @Test public void scheduleHeartbeat_oneTaskIsScheduled() { underTest.scheduleHeartbeat(); verify(executorService, Mockito.times(1)) .schedule(any(HeartbeatTask.class), anyLong(), any()); } @Test public void writeAndFlush_payloadAlwaysEndsWithSlashNSlashN() throws IOException { underTest.writeAndFlush("payload"); verify(outputStream, Mockito.times(1)).flush(); verify(outputStream, Mockito.times(1)).write("payload\n\n".getBytes(StandardCharsets.UTF_8)); } @Test public void writeAndFlush_payloadAlwaysEndsWithASingleSlashNSlashN_whenMessageAlreadyContainsIt() throws IOException { underTest.writeAndFlush("payload\n\n"); verify(outputStream, Mockito.times(1)).flush(); verify(outputStream, Mockito.times(1)).write("payload\n\n".getBytes(StandardCharsets.UTF_8)); } @Test public void writeAndFlush_writeIsCalledOnceAndFlushIsCalledOnce() throws IOException { underTest.writeAndFlush('a'); verify(outputStream, Mockito.times(1)).flush(); verify(outputStream, Mockito.times(1)).write('a'); } @Test public void write_writeIsCalledOnceAndDoesntFlush() throws IOException { underTest.write('a'); verify(outputStream, Mockito.never()).flush(); verify(outputStream, Mockito.times(1)).write('a'); } @Test public void flush_streamIsFlushed() throws IOException { underTest.flush(); verify(outputStream, Mockito.only()).flush(); } @Test public void addListener_addsListener() { AsyncListener mock = mock(AsyncListener.class); underTest.addListener(mock); verify(asyncContext).addListener(mock); } @Test public void write_exceptionCausesConnectionToClose() throws IOException { when(servletResponse.getOutputStream()).thenThrow(new IOException("mock exception")); when(executorService.schedule(any(HeartbeatTask.class), anyLong(), any(TimeUnit.class))).thenReturn(task); underTest.scheduleHeartbeat(); assertThatThrownBy(() -> underTest.write('a')) .isInstanceOf(IllegalStateException.class); } @Test public void flush_exceptionIsPropagated() throws IOException { when(servletResponse.getOutputStream()).thenThrow(new IOException("mock exception")); when(executorService.schedule(any(HeartbeatTask.class), anyLong(), any(TimeUnit.class))).thenReturn(task); underTest.scheduleHeartbeat(); assertThatThrownBy(underTest::flush) .isInstanceOf(IllegalStateException.class); } @Test public void close_exceptionOnComplete_doesNotThrowException() { when(executorService.schedule(any(HeartbeatTask.class), anyLong(), any(TimeUnit.class))).thenReturn(task); doThrow(new IllegalStateException()).when(asyncContext).complete(); underTest.scheduleHeartbeat(); Assertions.assertThatCode(underTest::close) .doesNotThrowAnyException(); } }
5,390
34.701987
120
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/ServerPushWsModuleTest.java
/* * 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.pushapi; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class ServerPushWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new ServerPushModule().configure(container); assertThat(container.getAddedObjects()).isNotEmpty(); } }
1,269
34.277778
75
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/ServerPushWsTest.java
/* * 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.pushapi; import java.util.Arrays; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import static org.assertj.core.api.Assertions.assertThat; public class ServerPushWsTest { private DummyServerPushAction dummyServerPushAction = new DummyServerPushAction(); private ServerPushWs underTest = new ServerPushWs(Arrays.asList(dummyServerPushAction)); @Test public void define_ws() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller("api/push"); assertThat(controller).isNotNull(); assertThat(controller.path()).isEqualTo("api/push"); assertThat(controller.since()).isEqualTo("9.4"); assertThat(controller.description()).isNotEmpty(); assertThat(controller.actions()).isNotEmpty(); } private static class DummyServerPushAction extends ServerPushAction { @Override public void define(WebService.NewController context) { context.createAction("foo").setHandler(this); } @Override public void handle(Request request, Response response) { } } }
2,073
32.451613
90
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/hotspots/HotspotChangeEventServiceImplTest.java
/* * 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.pushapi.hotspots; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.Deque; import java.util.Set; import org.junit.Rule; import org.junit.Test; import org.sonar.db.DbTester; import org.sonar.db.pushevent.PushEventDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.test.JsonAssert.assertJson; public class HotspotChangeEventServiceImplTest { @Rule public DbTester db = DbTester.create(); public final HotspotChangeEventServiceImpl underTest = new HotspotChangeEventServiceImpl(db.getDbClient()); @Test public void distributeHotspotChangedEvent_whenCalled_shouldPersistCorrectEventData() { HotspotChangedEvent hotspotChangedEvent = new HotspotChangedEvent.Builder() .setKey("key") .setProjectKey("project-key") .setUpdateDate(new Date(1L)) .setStatus("REVIEWED") .setResolution("ACKNOWLEDGED") .setAssignee("assignee") .setFilePath("path/to/file") .build(); assertPushEventIsPersisted(hotspotChangedEvent); } private void assertPushEventIsPersisted(HotspotChangedEvent hotspotChangedEvent) { underTest.distributeHotspotChangedEvent("project-uuid", hotspotChangedEvent); Deque<PushEventDto> events = db.getDbClient().pushEventDao() .selectChunkByProjectUuids(db.getSession(), Set.of("project-uuid"), 1L, null, 1); assertThat(events).isNotEmpty(); assertThat(events).extracting(PushEventDto::getName, PushEventDto::getProjectUuid) .contains(tuple("SecurityHotspotChanged", "project-uuid")); String payload = new String(events.getLast().getPayload(), StandardCharsets.UTF_8); assertJson(payload).isSimilarTo("{" + "\"key\": \"" + hotspotChangedEvent.getKey() + "\"," + "\"projectKey\": \"" + hotspotChangedEvent.getProjectKey() + "\"," + "\"updateDate\": " + hotspotChangedEvent.getUpdateDate() + "," + "\"status\": \"" + hotspotChangedEvent.getStatus() + "\"," + "\"filePath\": \"" + hotspotChangedEvent.getFilePath() + "\"," + "\"assignee\": \"" + hotspotChangedEvent.getAssignee() + "\"," + "\"resolution\": \"" + hotspotChangedEvent.getResolution() + "\"" + "}"); } }
3,121
39.025641
109
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/issues/IssueChangeEventServiceImplTest.java
/* * 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.pushapi.issues; import java.nio.charset.StandardCharsets; import java.util.Deque; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.rules.RuleType; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.FieldDiffs; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.issue.IssueDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.pushevent.PushEventDto; import org.sonar.db.rule.RuleDto; import org.sonarqube.ws.Common; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.issue.DefaultTransitions.CONFIRM; import static org.sonar.api.issue.DefaultTransitions.FALSE_POSITIVE; import static org.sonar.api.issue.DefaultTransitions.REOPEN; import static org.sonar.api.issue.DefaultTransitions.RESOLVE; import static org.sonar.api.issue.DefaultTransitions.UNCONFIRM; import static org.sonar.api.issue.DefaultTransitions.WONT_FIX; import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonarqube.ws.Common.Severity.BLOCKER; import static org.sonarqube.ws.Common.Severity.CRITICAL; import static org.sonarqube.ws.Common.Severity.MAJOR; public class IssueChangeEventServiceImplTest { @Rule public DbTester db = DbTester.create(); public final IssueChangeEventServiceImpl underTest = new IssueChangeEventServiceImpl(db.getDbClient()); @Test public void distributeIssueChangeEvent_whenSingleIssueChange_shouldChangeSeverity() { ProjectData projectData = db.components().insertPublicProject(); RuleDto rule = db.rules().insert(); IssueDto issue = db.issues().insert(rule, projectData.getMainBranchDto(), projectData.getMainBranchComponent(), i -> i.setSeverity(MAJOR.name())); assertPushEventIsPersisted(projectData.getProjectDto(), projectData.getMainBranchDto(), issue, BLOCKER.name(), null, null, null, 1); } @Test public void distributeIssueChangeEvent_whenSingleIssueChange_shouldChangeType() { ProjectData projectData = db.components().insertPublicProject(); RuleDto rule = db.rules().insert(); IssueDto issue = db.issues().insert(rule, projectData.getMainBranchDto(), projectData.getMainBranchComponent(), i -> i.setSeverity(MAJOR.name())); assertPushEventIsPersisted(projectData.getProjectDto(), projectData.getMainBranchDto(), issue, null, Common.RuleType.BUG.name(), null, null, 1); } @Test public void distributeIssueChangeEvent_whenSingleIssueChange_shouldExecuteTransitionChanges() { ProjectData projectData = db.components().insertPublicProject(); ProjectDto project = projectData.getProjectDto(); BranchDto mainBranch = projectData.getMainBranchDto(); RuleDto rule = db.rules().insert(); IssueDto issue = db.issues().insert(rule, mainBranch, projectData.getMainBranchComponent(), i -> i.setSeverity(MAJOR.name())); assertPushEventIsPersisted(project, mainBranch, issue, null, null, WONT_FIX, true, 1); assertPushEventIsPersisted(project, mainBranch, issue, null, null, REOPEN, false, 2); assertPushEventIsPersisted(project, mainBranch, issue, null, null, FALSE_POSITIVE, true, 3); assertPushEventIsPersisted(project, mainBranch, issue, null, null, REOPEN, false, 4); assertPushEventIsPersisted(project, mainBranch, issue, null, null, RESOLVE, false, 5); assertPushEventIsPersisted(project, mainBranch, issue, null, null, REOPEN, false, 6); assertNoIssueDistribution(project, mainBranch, issue, null, null, CONFIRM, 7); assertNoIssueDistribution(project, mainBranch, issue, null, null, UNCONFIRM, 8); } @Test public void distributeIssueChangeEvent_whenSingleIssueChangeOnABranch_shouldChangeSeverity() { ProjectData projectData = db.components().insertPublicProject(); BranchDto featureBranch = db.components().insertProjectBranch(projectData.getProjectDto(), b -> b.setKey("feature1")); ComponentDto branchComponent = db.components().insertFile(featureBranch); RuleDto rule = db.rules().insert(); IssueDto issue = db.issues().insert(rule, featureBranch, branchComponent, i -> i.setSeverity(MAJOR.name())); assertPushEventIsPersisted(projectData.getProjectDto(), featureBranch, issue, BLOCKER.name(), null, null, null, 1); } @Test public void distributeIssueChangeEvent_whenSingleIssueChange_shouldExecuteSeveralChanges() { ProjectData projectData = db.components().insertPublicProject(); RuleDto rule = db.rules().insert(); IssueDto issue = db.issues().insert(rule, projectData.getMainBranchDto(), projectData.getMainBranchComponent(), i -> i.setSeverity(MAJOR.name())); assertPushEventIsPersisted(projectData.getProjectDto(), projectData.getMainBranchDto(), issue, BLOCKER.name(), Common.RuleType.BUG.name(), WONT_FIX, true, 1); } @Test public void distributeIssueChangeEvent_whenBulkIssueChange_shouldDistributesEvents() { RuleDto rule = db.rules().insert(); ProjectData projectData1 = db.components().insertPublicProject(); ProjectDto project1 = projectData1.getProjectDto(); BranchDto branch1 = projectData1.getMainBranchDto(); ComponentDto componentDto1 = projectData1.getMainBranchComponent(); IssueDto issue1 = db.issues().insert(rule, branch1, componentDto1, i -> i.setSeverity(MAJOR.name()).setType(RuleType.BUG)); ProjectData projectData2 = db.components().insertPublicProject(); ProjectDto project2 = projectData2.getProjectDto(); BranchDto branch2 = projectData2.getMainBranchDto(); ComponentDto componentDto2 = projectData2.getMainBranchComponent(); IssueDto issue2 = db.issues().insert(rule, branch2, componentDto2, i -> i.setSeverity(MAJOR.name()).setType(RuleType.BUG)); ProjectData projectData3 = db.components().insertPublicProject(); ProjectDto project3 = projectData3.getProjectDto(); BranchDto branch3 = projectData3.getMainBranchDto(); ComponentDto componentDto3 = projectData3.getMainBranchComponent(); IssueDto issue3 = db.issues().insert(rule, branch3, componentDto3, i -> i.setSeverity(MAJOR.name()).setType(RuleType.BUG)); DefaultIssue defaultIssue1 = issue1.toDefaultIssue().setCurrentChangeWithoutAddChange(new FieldDiffs() .setDiff("resolution", null, null) .setDiff("severity", MAJOR.name(), CRITICAL.name()) .setDiff("type", RuleType.BUG.name(), CODE_SMELL.name())); DefaultIssue defaultIssue2 = issue2.toDefaultIssue().setCurrentChangeWithoutAddChange(new FieldDiffs() .setDiff("resolution", "OPEN", "FALSE-POSITIVE") .setDiff("severity", MAJOR.name(), CRITICAL.name()) .setDiff("type", RuleType.BUG.name(), CODE_SMELL.name())); Set<DefaultIssue> issues = Set.of(defaultIssue1, defaultIssue2, issue3.toDefaultIssue()); Map<String, ComponentDto> projectsByUuid = new HashMap<>(); projectsByUuid.put(componentDto1.branchUuid(), componentDto1); projectsByUuid.put(componentDto2.branchUuid(), componentDto2); projectsByUuid.put(componentDto3.branchUuid(), componentDto3); Map<String, BranchDto> branchesByProjectUuid = new HashMap<>(); branchesByProjectUuid.put(componentDto1.branchUuid(), branch1); branchesByProjectUuid.put(componentDto2.branchUuid(), branch2); branchesByProjectUuid.put(componentDto3.branchUuid(), branch3); underTest.distributeIssueChangeEvent(issues, projectsByUuid, branchesByProjectUuid); Deque<PushEventDto> issueChangedEvents = db.getDbClient().pushEventDao() .selectChunkByProjectUuids(db.getSession(), Set.of(project1.getUuid(), project2.getUuid()), 1l, null, 3); assertThat(issueChangedEvents).hasSize(2); assertThat(issueChangedEvents) .extracting(PushEventDto::getName, PushEventDto::getProjectUuid) .containsExactlyInAnyOrder( tuple("IssueChanged", project1.getUuid()), tuple("IssueChanged", project2.getUuid())); Optional<PushEventDto> project1Event = issueChangedEvents.stream().filter(e -> e.getProjectUuid().equals(project1.getUuid())).findFirst(); Optional<PushEventDto> project2Event = issueChangedEvents.stream().filter(e -> e.getProjectUuid().equals(project2.getUuid())).findFirst(); assertThat(project1Event).isPresent(); assertThat(project2Event).isPresent(); String firstPayload = new String(project1Event.get().getPayload(), StandardCharsets.UTF_8); assertThat(firstPayload) .contains("\"userSeverity\":\"" + CRITICAL.name() + "\"", "\"userType\":\"" + CODE_SMELL.name() + "\"", "\"resolved\":" + false); String secondPayload = new String(project2Event.get().getPayload(), StandardCharsets.UTF_8); assertThat(secondPayload) .contains("\"userSeverity\":\"" + CRITICAL.name() + "\"", "\"userType\":\"" + CODE_SMELL.name() + "\"", "\"resolved\":" + true); } @Test public void distributeIssueChangeEvent_whenPullRequestIssues_shouldNotDistributeEvents() { RuleDto rule = db.rules().insert(); ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setKey("myBranch1") .setBranchType(BranchType.PULL_REQUEST) .setMergeBranchUuid(project.uuid())); BranchDto branch1 = db.getDbClient().branchDao().selectByUuid(db.getSession(), pullRequest.uuid()).get(); ComponentDto file = db.components().insertComponent(newFileDto(pullRequest)); IssueDto issue1 = db.issues().insert(rule, pullRequest, file, i -> i.setSeverity(MAJOR.name()).setType(RuleType.BUG)); DefaultIssue defaultIssue1 = issue1.toDefaultIssue().setCurrentChangeWithoutAddChange(new FieldDiffs() .setDiff("resolution", null, null) .setDiff("severity", MAJOR.name(), CRITICAL.name()) .setDiff("type", RuleType.BUG.name(), CODE_SMELL.name())); Set<DefaultIssue> issues = Set.of(defaultIssue1); Map<String, ComponentDto> projectsByUuid = new HashMap<>(); projectsByUuid.put(project.branchUuid(), project); Map<String, BranchDto> branchesByProjectUuid = new HashMap<>(); branchesByProjectUuid.put(project.branchUuid(), branch1); underTest.distributeIssueChangeEvent(issues, projectsByUuid, branchesByProjectUuid); Deque<PushEventDto> events = db.getDbClient().pushEventDao() .selectChunkByProjectUuids(db.getSession(), Set.of(project.uuid()), 1l, null, 20); assertThat(events).isEmpty(); } private void assertNoIssueDistribution(ProjectDto project, BranchDto branch, IssueDto issue, @Nullable String severity, @Nullable String type, @Nullable String transition, int page) { underTest.distributeIssueChangeEvent(issue.toDefaultIssue(), severity, type, transition, branch, project.getKey()); Deque<PushEventDto> events = db.getDbClient().pushEventDao() .selectChunkByProjectUuids(db.getSession(), Set.of(project.getUuid()), 1l, null, page); assertThat(events).hasSizeLessThan(page); } private void assertPushEventIsPersisted(ProjectDto project, BranchDto branch, IssueDto issue, @Nullable String severity, @Nullable String type, @Nullable String transition, Boolean resolved, int page) { underTest.distributeIssueChangeEvent(issue.toDefaultIssue(), severity, type, transition, branch, project.getKey()); Deque<PushEventDto> events = db.getDbClient().pushEventDao() .selectChunkByProjectUuids(db.getSession(), Set.of(project.getUuid()), 1l, null, page); assertThat(events).isNotEmpty(); assertThat(events).extracting(PushEventDto::getName, PushEventDto::getProjectUuid) .contains(tuple("IssueChanged", project.getUuid())); String payload = new String(events.getLast().getPayload(), StandardCharsets.UTF_8); if (severity != null) { assertThat(payload).contains("\"userSeverity\":\"" + severity + "\""); } if (type != null) { assertThat(payload).contains("\"userType\":\"" + type + "\""); } if (resolved != null) { assertThat(payload).contains("\"resolved\":" + resolved); } } }
13,188
49.92278
162
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/qualityprofile/QualityProfileChangeEventServiceImplTest.java
/* * 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.pushapi.qualityprofile; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Set; import java.util.function.Consumer; import org.junit.Rule; import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.measure.LiveMeasureDto; import org.sonar.db.metric.MetricDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.pushevent.PushEventDto; import org.sonar.db.qualityprofile.ActiveRuleDto; import org.sonar.db.qualityprofile.ActiveRuleParamDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.qualityprofile.QualityProfileTesting; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleParamDto; import org.sonar.server.qualityprofile.ActiveRuleChange; import org.sonarqube.ws.Common; import static java.util.List.of; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.apache.commons.lang.math.RandomUtils.nextInt; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION_KEY; import static org.sonar.api.measures.Metric.ValueType.STRING; import static org.sonar.db.rule.RuleTesting.newCustomRule; import static org.sonar.db.rule.RuleTesting.newTemplateRule; import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.ACTIVATED; public class QualityProfileChangeEventServiceImplTest { @Rule public DbTester db = DbTester.create(); public final QualityProfileChangeEventServiceImpl underTest = new QualityProfileChangeEventServiceImpl(db.getDbClient()); @Test public void distributeRuleChangeEvent() { QProfileDto qualityProfileDto = QualityProfileTesting.newQualityProfileDto(); RuleDto templateRule = newTemplateRule(RuleKey.of("xoo", "template-key")); db.rules().insert(templateRule); RuleDto rule1 = newCustomRule(templateRule, "<div>line1\nline2</div>") .setLanguage("xoo") .setRepositoryKey("repo") .setRuleKey("ruleKey") .setDescriptionFormat(RuleDto.Format.MARKDOWN); db.rules().insert(rule1); ActiveRuleChange activeRuleChange = changeActiveRule(qualityProfileDto, rule1, "paramChangeKey", "paramChangeValue"); Collection<QProfileDto> profiles = Collections.singleton(qualityProfileDto); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); db.qualityProfiles().associateWithProject(project, qualityProfileDto); underTest.distributeRuleChangeEvent(profiles, of(activeRuleChange), "xoo"); Deque<PushEventDto> events = getProjectEvents(project); assertThat(events).isNotEmpty().hasSize(1); assertThat(events.getFirst()) .extracting(PushEventDto::getName, PushEventDto::getLanguage) .contains("RuleSetChanged", "xoo"); String ruleSetChangedEvent = new String(events.getFirst().getPayload(), StandardCharsets.UTF_8); assertThat(ruleSetChangedEvent) .contains("\"activatedRules\":[{\"key\":\"repo:ruleKey\"," + "\"language\":\"xoo\"," + "\"templateKey\":\"xoo:template-key\"," + "\"params\":[{\"key\":\"paramChangeKey\",\"value\":\"paramChangeValue\"}]}]," + "\"deactivatedRules\":[]"); } @Test public void distributeRuleChangeEvent_when_project_has_only_default_quality_profiles() { String language = "xoo"; ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); RuleDto templateRule = insertTemplateRule(); QProfileDto defaultQualityProfile = insertDefaultQualityProfile(language); RuleDto rule = insertCustomRule(templateRule, language, "<div>line1\nline2</div>"); ActiveRuleChange activeRuleChange = changeActiveRule(defaultQualityProfile, rule, "paramChangeKey", "paramChangeValue"); insertQualityProfileLiveMeasure(mainBranch, projectData.getProjectDto(), language, NCLOC_LANGUAGE_DISTRIBUTION_KEY); db.getSession().commit(); underTest.distributeRuleChangeEvent(List.of(defaultQualityProfile), of(activeRuleChange), language); Deque<PushEventDto> events = getProjectEvents(projectData.getProjectDto()); assertThat(events) .hasSize(1); assertThat(events.getFirst()) .extracting(PushEventDto::getName, PushEventDto::getLanguage) .contains("RuleSetChanged", "xoo"); String ruleSetChangedEvent = new String(events.getFirst().getPayload(), StandardCharsets.UTF_8); assertThat(ruleSetChangedEvent) .contains("\"activatedRules\":[{\"key\":\"repo:ruleKey\"," + "\"language\":\"xoo\"," + "\"templateKey\":\"xoo:template-key\"," + "\"params\":[{\"key\":\"paramChangeKey\",\"value\":\"paramChangeValue\"}]}]," + "\"deactivatedRules\":[]"); } private Deque<PushEventDto> getProjectEvents(ProjectDto projectDto) { return db.getDbClient() .pushEventDao() .selectChunkByProjectUuids(db.getSession(), Set.of(projectDto.getUuid()), 1L, null, 1); } private ActiveRuleChange changeActiveRule(QProfileDto defaultQualityProfile, RuleDto rule, String changeKey, String changeValue) { ActiveRuleDto activeRuleDto = ActiveRuleDto.createFor(defaultQualityProfile, rule); ActiveRuleChange activeRuleChange = new ActiveRuleChange(ACTIVATED, activeRuleDto, rule); return activeRuleChange.setParameter(changeKey, changeValue); } private RuleDto insertCustomRule(RuleDto templateRule, String language, String description) { RuleDto rule = newCustomRule(templateRule, description) .setLanguage(language) .setRepositoryKey("repo") .setRuleKey("ruleKey") .setDescriptionFormat(RuleDto.Format.MARKDOWN); db.rules().insert(rule); return rule; } private QProfileDto insertDefaultQualityProfile(String language) { Consumer<QProfileDto> configureQualityProfile = profile -> profile .setIsBuiltIn(true) .setLanguage(language); QProfileDto defaultQualityProfile = db.qualityProfiles().insert(configureQualityProfile); db.qualityProfiles().setAsDefault(defaultQualityProfile); return defaultQualityProfile; } private RuleDto insertTemplateRule() { RuleKey key = RuleKey.of("xoo", "template-key"); RuleDto templateRule = newTemplateRule(key); db.rules().insert(templateRule); return templateRule; } @Test public void publishRuleActivationToSonarLintClients() { ProjectDto projectDto = new ProjectDto().setUuid("project-uuid"); QProfileDto activatedQualityProfile = QualityProfileTesting.newQualityProfileDto(); activatedQualityProfile.setLanguage("xoo"); db.qualityProfiles().insert(activatedQualityProfile); RuleDto rule1 = db.rules().insert(r -> r.setLanguage("xoo").setRepositoryKey("repo").setRuleKey("ruleKey")); RuleParamDto rule1Param = db.rules().insertRuleParam(rule1); ActiveRuleDto activeRule1 = db.qualityProfiles().activateRule(activatedQualityProfile, rule1); ActiveRuleParamDto activeRuleParam1 = ActiveRuleParamDto.createFor(rule1Param).setValue(randomAlphanumeric(20)); db.getDbClient().activeRuleDao().insertParam(db.getSession(), activeRule1, activeRuleParam1); db.getSession().commit(); QProfileDto deactivatedQualityProfile = QualityProfileTesting.newQualityProfileDto(); db.qualityProfiles().insert(deactivatedQualityProfile); RuleDto rule2 = db.rules().insert(r -> r.setLanguage("xoo").setRepositoryKey("repo2").setRuleKey("ruleKey2")); RuleParamDto rule2Param = db.rules().insertRuleParam(rule2); ActiveRuleDto activeRule2 = db.qualityProfiles().activateRule(deactivatedQualityProfile, rule2); ActiveRuleParamDto activeRuleParam2 = ActiveRuleParamDto.createFor(rule2Param).setValue(randomAlphanumeric(20)); db.getDbClient().activeRuleDao().insertParam(db.getSession(), activeRule2, activeRuleParam2); db.getSession().commit(); underTest.publishRuleActivationToSonarLintClients(projectDto, activatedQualityProfile, deactivatedQualityProfile); Deque<PushEventDto> events = getProjectEvents(projectDto); assertThat(events).isNotEmpty().hasSize(1); assertThat(events.getFirst()) .extracting(PushEventDto::getName, PushEventDto::getLanguage) .contains("RuleSetChanged", "xoo"); String ruleSetChangedEvent = new String(events.getFirst().getPayload(), StandardCharsets.UTF_8); assertThat(ruleSetChangedEvent) .contains("\"activatedRules\":[{\"key\":\"repo:ruleKey\"," + "\"language\":\"xoo\",\"severity\":\"" + Common.Severity.forNumber(rule1.getSeverity()).name() + "\"," + "\"params\":[{\"key\":\"" + activeRuleParam1.getKey() + "\",\"value\":\"" + activeRuleParam1.getValue() + "\"}]}]," + "\"deactivatedRules\":[\"repo2:ruleKey2\"]"); } private void insertQualityProfileLiveMeasure(ComponentDto branch, ProjectDto projectDto, String language, String metricKey) { MetricDto metric = insertMetric(metricKey); Consumer<LiveMeasureDto> configureLiveMeasure = liveMeasure -> liveMeasure .setMetricUuid(metric.getUuid()) .setComponentUuid(branch.uuid()) .setProjectUuid(projectDto.getUuid()) .setData(language + "=" + nextInt(10)); db.measures().insertLiveMeasure(branch, metric, configureLiveMeasure); } private MetricDto insertMetric(String metricKey) { Consumer<MetricDto> configureMetric = metric -> metric .setUuid("uuid") .setValueType(STRING.name()) .setKey(metricKey); return db.measures().insertMetric(configureMetric); } }
10,638
42.781893
133
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/scheduler/polling/PushEventPollExecutorServiceImplTest.java
/* * 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.pushapi.scheduler.polling; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class PushEventPollExecutorServiceImplTest { @Test public void create_executor() { PushEventPollExecutorServiceImpl underTest = new PushEventPollExecutorServiceImpl(); assertThat(underTest.createThread(() -> { })) .extracting(Thread::getPriority, Thread::isDaemon, Thread::getName) .containsExactly(Thread.MIN_PRIORITY, true, "PushEventPoll-%d"); } }
1,371
33.3
88
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/scheduler/polling/PushEventPollSchedulerTest.java
/* * 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.pushapi.scheduler.polling; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbTester; import org.sonar.db.pushevent.PushEventDto; import org.sonar.server.pushapi.sonarlint.SonarLintClient; import org.sonar.server.pushapi.sonarlint.SonarLintClientsRegistry; import org.sonar.server.pushapi.sonarlint.SonarLintPushEvent; import org.sonar.server.util.AbstractStoppableExecutorService; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class PushEventPollSchedulerTest { private final SonarLintClientsRegistry clientsRegistry = mock(SonarLintClientsRegistry.class); private static final long NOW = 1L; private final TestSystem2 system2 = new TestSystem2().setNow(NOW); private final Configuration config = mock(Configuration.class); @Rule public DbTester db = DbTester.create(system2); private final SyncPushEventExecutorService executorService = new SyncPushEventExecutorService(); @Test public void scheduler_should_be_resilient_to_failures() { when(clientsRegistry.getClients()).thenThrow(new RuntimeException("I have a bad feelings about this")); var underTest = new PushEventPollScheduler(executorService, clientsRegistry, db.getDbClient(), system2, config); underTest.start(); assertThatCode(executorService::runCommand) .doesNotThrowAnyException(); verify(clientsRegistry, times(0)).broadcastMessage(any(SonarLintPushEvent.class)); } @Test public void nothing_to_broadcast_when_client_list_is_empty() { when(clientsRegistry.getClients()).thenReturn(emptyList()); var underTest = new PushEventPollScheduler(executorService, clientsRegistry, db.getDbClient(), system2, config); underTest.start(); executorService.runCommand(); verify(clientsRegistry, times(0)).broadcastMessage(any(SonarLintPushEvent.class)); } @Test public void nothing_to_broadcast_when_no_push_events() { var project = db.components().insertPrivateProject().getMainBranchComponent(); var sonarLintClient = mock(SonarLintClient.class); when(sonarLintClient.getClientProjectUuids()).thenReturn(Set.of(project.uuid())); when(clientsRegistry.getClients()).thenReturn(List.of(sonarLintClient)); var underTest = new PushEventPollScheduler(executorService, clientsRegistry, db.getDbClient(), system2, config); underTest.start(); executorService.runCommand(); verify(clientsRegistry, times(0)).broadcastMessage(any(SonarLintPushEvent.class)); } @Test public void nothing_to_broadcast_if_project_key_does_not_exist() { var project = db.components().insertPrivateProject().getMainBranchComponent(); system2.setNow(1L); var sonarLintClient = mock(SonarLintClient.class); when(sonarLintClient.getClientProjectUuids()).thenReturn(Set.of("not-existing-project-uuid")); when(clientsRegistry.getClients()).thenReturn(List.of(sonarLintClient)); var underTest = new PushEventPollScheduler(executorService, clientsRegistry, db.getDbClient(), system2, config); underTest.start(); verify(clientsRegistry, times(0)).broadcastMessage(any(SonarLintPushEvent.class)); system2.tick(); // tick=2 generatePushEvent(project.uuid()); executorService.runCommand(); verify(clientsRegistry, times(0)).broadcastMessage(any(SonarLintPushEvent.class)); } @Test public void broadcast_push_events() { var project = db.components().insertPrivateProject().getMainBranchComponent(); system2.setNow(1L); var sonarLintClient = mock(SonarLintClient.class); when(sonarLintClient.getClientProjectUuids()).thenReturn(Set.of(project.uuid())); when(clientsRegistry.getClients()).thenReturn(List.of(sonarLintClient)); var underTest = new PushEventPollScheduler(executorService, clientsRegistry, db.getDbClient(), system2, config); underTest.start(); executorService.runCommand(); verify(clientsRegistry, times(0)).broadcastMessage(any(SonarLintPushEvent.class)); system2.tick(); // tick=2 generatePushEvent(project.uuid()); generatePushEvent(project.uuid()); system2.tick(); // tick=3 generatePushEvent(project.uuid()); underTest.start(); executorService.runCommand(); verify(clientsRegistry, times(3)).broadcastMessage(any(SonarLintPushEvent.class)); system2.tick(); // tick=4 generatePushEvent(project.uuid()); generatePushEvent(project.uuid()); underTest.start(); executorService.runCommand(); verify(clientsRegistry, times(5)).broadcastMessage(any(SonarLintPushEvent.class)); } @Test public void broadcast_should_stop_polling_for_events_when_all_clients_unregister() { var project = db.components().insertPrivateProject().getMainBranchComponent(); system2.setNow(1L); var sonarLintClient = mock(SonarLintClient.class); when(sonarLintClient.getClientProjectUuids()).thenReturn(Set.of(project.uuid())); when(clientsRegistry.getClients()).thenReturn(List.of(sonarLintClient), emptyList()); var underTest = new PushEventPollScheduler(executorService, clientsRegistry, db.getDbClient(), system2, config); underTest.start(); executorService.runCommand(); verify(clientsRegistry, times(0)).broadcastMessage(any(SonarLintPushEvent.class)); system2.tick(); // tick=2 generatePushEvent(project.uuid()); underTest.start(); executorService.runCommand(); // all clients have been unregistered, nothing to broadcast verify(clientsRegistry, times(0)).broadcastMessage(any(SonarLintPushEvent.class)); } private PushEventDto generatePushEvent(String projectUuid) { var event = db.getDbClient().pushEventDao().insert(db.getSession(), new PushEventDto() .setName("Event") .setUuid(UuidFactoryFast.getInstance().create()) .setProjectUuid(projectUuid) .setPayload("some-event".getBytes(UTF_8))); db.commit(); return event; } private static class SyncPushEventExecutorService extends AbstractStoppableExecutorService<ScheduledExecutorService> implements PushEventExecutorService { private Runnable command; public SyncPushEventExecutorService() { super(null); } public void runCommand() { command.run(); } @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { this.command = command; return null; } @Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return null; } @Override public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { return null; } @Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return null; } } }
8,347
34.828326
118
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/scheduler/purge/PushEventsPurgeExecutorServiceImplTest.java
/* * 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.pushapi.scheduler.purge; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class PushEventsPurgeExecutorServiceImplTest { @Test public void constructor_createsProperDeleagateThatIsReadyToAct() { PushEventsPurgeExecutorServiceImpl pushEventsPurgeExecutorService = new PushEventsPurgeExecutorServiceImpl(); assertThat(pushEventsPurgeExecutorService.isShutdown()).isFalse(); assertThat(pushEventsPurgeExecutorService.isTerminated()).isFalse(); } }
1,374
37.194444
113
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/scheduler/purge/PushEventsPurgeSchedulerTest.java
/* * 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.pushapi.scheduler.purge; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.config.Configuration; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.pushevent.PushEventDao; import org.sonar.server.util.AbstractStoppableExecutorService; 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.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class PushEventsPurgeSchedulerTest { private final DbClient dbClient = mock(DbClient.class); private final DbSession dbSession = mock(DbSession.class); private final GlobalLockManager lockManager = mock(GlobalLockManagerImpl.class); private final PushEventDao pushEventDao = mock(PushEventDao.class); private final PushEventsPurgeExecutorServiceImpl executorService = new PushEventsPurgeExecutorServiceImpl(); private final Configuration configuration = mock(Configuration.class); private final System2 system2 = mock(System2.class); private final PushEventsPurgeScheduler underTest = new PushEventsPurgeScheduler(dbClient, configuration, lockManager, executorService, system2); @Before public void prepare() { when(lockManager.tryLock(any(), anyInt())).thenReturn(true); } @Test public void doNothingIfLocked() { when(lockManager.tryLock(any(), anyInt())).thenReturn(false); underTest.start(); executorService.runCommand(); verifyNoInteractions(dbClient); } @Test public void doNothingIfExceptionIsThrown() { when(lockManager.tryLock(any(), anyInt())).thenThrow(new IllegalArgumentException("Oops")); underTest.start(); executorService.runCommand(); verifyNoInteractions(dbClient); } @Test public void schedulePurgeTaskWhenNotLocked() { when(system2.now()).thenReturn(100000000L); when(dbClient.pushEventDao()).thenReturn(pushEventDao); when(dbClient.openSession(false)).thenReturn(dbSession); when(dbClient.pushEventDao().selectUuidsOfExpiredEvents(any(), anyLong())).thenReturn(Set.of("1", "2")); underTest.start(); executorService.runCommand(); ArgumentCaptor<Set> uuidsCaptor = ArgumentCaptor.forClass(Set.class); verify(pushEventDao).deleteByUuids(any(), uuidsCaptor.capture()); Set<String> uuids = uuidsCaptor.getValue(); assertThat(uuids).containsExactlyInAnyOrder("1", "2"); } private static class PushEventsPurgeExecutorServiceImpl extends AbstractStoppableExecutorService<ScheduledExecutorService> implements PushEventsPurgeExecutorService { private Runnable command; public PushEventsPurgeExecutorServiceImpl() { super(null); } public void runCommand() { command.run(); } @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { this.command = command; return null; } @Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return null; } @Override public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { return null; } @Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return null; } } }
4,790
33.221429
124
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/sonarlint/SonarLintClientPermissionsValidatorTest.java
/* * 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.pushapi.sonarlint; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.sonar.db.DbClient; import org.sonar.db.project.ProjectDao; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDao; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.user.UserSession; import org.sonar.server.user.UserSessionFactory; import static org.assertj.core.api.Assertions.assertThatCode; import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SonarLintClientPermissionsValidatorTest { private final static String USER_UUID = "USER_UUID"; private final Set<String> exampleProjectuuids = Set.of("project1", "project2"); private final List<ProjectDto> projectDtos = List.of(mock(ProjectDto.class), mock(ProjectDto.class)); private final DbClient dbClient = mock(DbClient.class); private final UserSessionFactory userSessionFactory = mock(UserSessionFactory.class); private final UserDao userDao = mock(UserDao.class); private final ProjectDao projectDao = mock(ProjectDao.class); private final UserSession userSession = mock(UserSession.class); private SonarLintClientPermissionsValidator underTest = new SonarLintClientPermissionsValidator(dbClient, userSessionFactory); @Before public void before() { when(dbClient.userDao()).thenReturn(userDao); when(dbClient.projectDao()).thenReturn(projectDao); when(userSessionFactory.create(any())).thenReturn(userSession); when(projectDao.selectProjectsByKeys(any(), any())).thenReturn(projectDtos); when(projectDao.selectByUuids(any(), any())).thenReturn(projectDtos); } @Test public void validate_givenUserActivatedAndWithRequiredPermissions_dontThrowException() { UserDto userDto = new UserDto(); when(userDao.selectByUuid(any(), any())).thenReturn(userDto); when(userSession.isActive()).thenReturn(true); assertThatCode(() -> underTest.validateUserCanReceivePushEventForProjectUuids(USER_UUID, exampleProjectuuids)) .doesNotThrowAnyException(); } @Test public void validate_givenUserNotActivated_throwException() { UserDto userDto = new UserDto(); when(userDao.selectByUuid(any(), any())).thenReturn(userDto); when(userSession.isActive()).thenReturn(false); assertThrows(ForbiddenException.class, () -> underTest.validateUserCanReceivePushEventForProjectUuids(USER_UUID, exampleProjectuuids)); } @Test public void validate_givenUserNotGrantedProjectPermissions_throwException() { UserDto userDto = new UserDto(); when(userDao.selectByUuid(any(), any())).thenReturn(userDto); when(userSession.isActive()).thenReturn(true); when(userSession.checkEntityPermission(any(), any())).thenThrow(ForbiddenException.class); assertThrows(ForbiddenException.class, () -> underTest.validateUserCanReceivePushEventForProjectUuids(USER_UUID, exampleProjectuuids)); } }
3,950
40.589474
128
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/sonarlint/SonarLintClientTest.java
/* * 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.pushapi.sonarlint; import java.util.Set; import javax.servlet.AsyncContext; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class SonarLintClientTest { private final AsyncContext firstContext = mock(AsyncContext.class); private final AsyncContext secondContext = mock(AsyncContext.class); private final String USER_UUID = "userUUID"; @Test public void equals_twoClientsWithSameArgumentsAreEqual() { SonarLintClient first = new SonarLintClient(firstContext, Set.of(), Set.of(), USER_UUID); SonarLintClient second = new SonarLintClient(firstContext, Set.of(), Set.of(), USER_UUID); assertThat(first).isEqualTo(second); } @Test public void equals_twoClientsWithDifferentAsyncObjects() { SonarLintClient first = new SonarLintClient(firstContext, Set.of(), Set.of(), USER_UUID); SonarLintClient second = new SonarLintClient(secondContext, Set.of(), Set.of(), USER_UUID); assertThat(first).isNotEqualTo(second); } @Test public void equals_twoClientsWithDifferentLanguages() { SonarLintClient first = new SonarLintClient(firstContext, Set.of(), Set.of("java"), USER_UUID); SonarLintClient second = new SonarLintClient(firstContext, Set.of(), Set.of("cobol"), USER_UUID); assertThat(first).isNotEqualTo(second); } @Test public void equals_twoClientsWithDifferentProjectUuids() { SonarLintClient first = new SonarLintClient(firstContext, Set.of("project1", "project2"), Set.of(), USER_UUID); SonarLintClient second = new SonarLintClient(firstContext, Set.of("project1"), Set.of(), USER_UUID); assertThat(first).isNotEqualTo(second); } @Test public void equals_secondClientIsNull() { SonarLintClient first = new SonarLintClient(firstContext, Set.of("project1", "project2"), Set.of(), USER_UUID); assertThat(first).isNotEqualTo(null); } @Test public void hashCode_producesSameHashesForEqualObjects() { SonarLintClient first = new SonarLintClient(firstContext, Set.of(), Set.of(), USER_UUID); SonarLintClient second = new SonarLintClient(firstContext, Set.of(), Set.of(), USER_UUID); assertThat(first).hasSameHashCodeAs(second); } }
3,096
36.313253
115
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/sonarlint/SonarLintClientsRegistryTest.java
/* * 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.pushapi.sonarlint; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Set; import javax.servlet.AsyncContext; import javax.servlet.ServletOutputStream; import javax.servlet.ServletResponse; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.server.exceptions.ForbiddenException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anySet; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.test.EventAssert.assertThatEvent; public class SonarLintClientsRegistryTest { private static final String EVENT_NAME = "RuleSetChanged"; private final AsyncContext defaultAsyncContext = mock(AsyncContext.class); private final Set<String> exampleProjectUuids = Set.of("project1", "project2", "project3"); private final Set<String> languageKeys = Set.of("language1", "language2", "language3"); private final String USER_UUID = "userUuid"; private final ServletResponse response = mock(ServletResponse.class); private final ServletOutputStream outputStream = mock(ServletOutputStream.class); private final SonarLintClientPermissionsValidator permissionsValidator = mock(SonarLintClientPermissionsValidator.class); private SonarLintClientsRegistry underTest; @Before public void before() { underTest = new SonarLintClientsRegistry(permissionsValidator); } @Test public void registerClientAndUnregister_changesNumberOfClients_andClosesClient() { SonarLintClient sonarLintClient = mock(SonarLintClient.class); underTest.registerClient(sonarLintClient); assertThat(underTest.countConnectedClients()).isEqualTo(1); assertThat(underTest.getClients()).contains(sonarLintClient); underTest.unregisterClient(sonarLintClient); assertThat(underTest.countConnectedClients()).isZero(); assertThat(underTest.getClients()).isEmpty(); verify(sonarLintClient).close(); } @Test public void registering10Clients_10ClientsAreRegistered() { for (int i = 0; i < 10; i++) { AsyncContext newAsyncContext = mock(AsyncContext.class); SonarLintClient sonarLintClient = new SonarLintClient(newAsyncContext, exampleProjectUuids, languageKeys, USER_UUID); underTest.registerClient(sonarLintClient); } assertThat(underTest.countConnectedClients()).isEqualTo(10); } @Test public void listen_givenOneClientInterestedInJavaEvents_sendAllJavaEvents() throws IOException { Set<String> javaLanguageKey = Set.of("java"); when(defaultAsyncContext.getResponse()).thenReturn(response); when(response.getOutputStream()).thenReturn(outputStream); SonarLintClient sonarLintClient = new SonarLintClient(defaultAsyncContext, exampleProjectUuids, javaLanguageKey, USER_UUID); underTest.registerClient(sonarLintClient); SonarLintPushEvent event1 = new SonarLintPushEvent(EVENT_NAME, "data".getBytes(StandardCharsets.UTF_8), "project1", "java"); SonarLintPushEvent event2 = new SonarLintPushEvent(EVENT_NAME, "data".getBytes(StandardCharsets.UTF_8), "project2", "java"); SonarLintPushEvent event3 = new SonarLintPushEvent(EVENT_NAME, "data".getBytes(StandardCharsets.UTF_8), "project3", "java"); underTest.broadcastMessage(event1); ArgumentCaptor<byte[]> captor = ArgumentCaptor.forClass(byte[].class); verify(outputStream).write(captor.capture()); String message = new String(captor.getValue()); assertThatEvent(message) .hasType(EVENT_NAME); clearInvocations(outputStream); underTest.broadcastMessage(event2); verify(outputStream).write(captor.capture()); message = new String(captor.getValue()); assertThatEvent(message) .hasType(EVENT_NAME); clearInvocations(outputStream); underTest.broadcastMessage(event3); verify(outputStream).write(captor.capture()); message = new String(captor.getValue()); assertThatEvent(message) .hasType(EVENT_NAME); } @Test public void listen_givenOneClientInterestedInJsEventsAndJavaEventGenerated_sendZeroEvents() throws IOException { Set<String> jsLanguageKey = Set.of("js"); when(defaultAsyncContext.getResponse()).thenReturn(response); when(response.getOutputStream()).thenReturn(outputStream); SonarLintClient sonarLintClient = new SonarLintClient(defaultAsyncContext, exampleProjectUuids, jsLanguageKey, USER_UUID); underTest.registerClient(sonarLintClient); SonarLintPushEvent event = new SonarLintPushEvent(EVENT_NAME, "data".getBytes(StandardCharsets.UTF_8), "project1", "java"); underTest.broadcastMessage(event); verifyNoInteractions(outputStream); } @Test public void listen_givenOneClientInterestedInProjA_DontCheckPermissionsForProjB() throws IOException { when(defaultAsyncContext.getResponse()).thenReturn(response); when(response.getOutputStream()).thenReturn(outputStream); SonarLintClient sonarLintClient = new SonarLintClient(defaultAsyncContext, Set.of("projA"), Set.of("java"), USER_UUID); underTest.registerClient(sonarLintClient); SonarLintPushEvent event1 = new SonarLintPushEvent(EVENT_NAME, "data".getBytes(StandardCharsets.UTF_8), "projA", "java"); SonarLintPushEvent event2 = new SonarLintPushEvent(EVENT_NAME, "data".getBytes(StandardCharsets.UTF_8), "projB", "java"); ArgumentCaptor<Set<String>> argument = ArgumentCaptor.forClass(Set.class); underTest.broadcastMessage(event1); underTest.broadcastMessage(event2); verify(permissionsValidator, times(1)).validateUserCanReceivePushEventForProjectUuids(anyString(), argument.capture()); assertThat(argument.getValue()).hasSize(1).contains("projA"); } @Test public void listen_givenUserNotPermittedToReceiveEvent_closeConnection() { SonarLintClient sonarLintClient = createSampleSLClient(); underTest.registerClient(sonarLintClient); doThrow(new ForbiddenException("Access forbidden")).when(permissionsValidator).validateUserCanReceivePushEventForProjectUuids(anyString(), anySet()); SonarLintPushEvent event = new SonarLintPushEvent(EVENT_NAME, "data".getBytes(StandardCharsets.UTF_8), "project1", "java"); underTest.broadcastMessage(event); verify(sonarLintClient).close(); } @Test public void listen_givenUnregisteredClient_closeConnection() throws IOException { SonarLintClient sonarLintClient = createSampleSLClient(); underTest.registerClient(sonarLintClient); doThrow(new IOException("Broken pipe")).when(sonarLintClient).writeAndFlush(anyString()); SonarLintPushEvent event = new SonarLintPushEvent(EVENT_NAME, "data".getBytes(StandardCharsets.UTF_8), "project1", "java"); underTest.broadcastMessage(event); underTest.registerClient(sonarLintClient); doThrow(new IllegalStateException("Things went wrong")).when(sonarLintClient).writeAndFlush(anyString()); underTest.broadcastMessage(event); verify(sonarLintClient, times(2)).close(); } @Test public void broadcast_push_event_to_clients() throws IOException { SonarLintPushEvent event = new SonarLintPushEvent("event", "data".getBytes(StandardCharsets.UTF_8), "project2", null); SonarLintClient sonarLintClient = createSampleSLClient(); underTest.registerClient(sonarLintClient); underTest.broadcastMessage(event); verify(permissionsValidator, times(1)).validateUserCanReceivePushEventForProjectUuids(anyString(), anySet()); verify(sonarLintClient, times(1)).writeAndFlush(anyString()); } @Test public void broadcast_skips_push_if_event_project_does_not_match_with_client() throws IOException { SonarLintPushEvent event = new SonarLintPushEvent("event", "data".getBytes(StandardCharsets.UTF_8), "project4", null); SonarLintClient sonarLintClient = createSampleSLClient(); underTest.registerClient(sonarLintClient); underTest.broadcastMessage(event); verify(permissionsValidator, times(0)).validateUserCanReceivePushEventForProjectUuids(anyString(), anySet()); verify(sonarLintClient, times(0)).close(); verify(sonarLintClient, times(0)).writeAndFlush(anyString()); } @Test public void broadcast_givenUserNotPermittedToReceiveSonarLintPushEvent_closeConnection() { SonarLintPushEvent event = new SonarLintPushEvent("event", "data".getBytes(StandardCharsets.UTF_8), "project1", null); SonarLintClient sonarLintClient = createSampleSLClient(); underTest.registerClient(sonarLintClient); doThrow(new ForbiddenException("Access forbidden")).when(permissionsValidator).validateUserCanReceivePushEventForProjectUuids(anyString(), anySet()); underTest.broadcastMessage(event); verify(sonarLintClient).close(); } @Test public void broadcast_givenUnregisteredClient_closeConnection() throws IOException { SonarLintPushEvent event = new SonarLintPushEvent("event", "data".getBytes(StandardCharsets.UTF_8), "project1", null); SonarLintClient sonarLintClient = createSampleSLClient(); underTest.registerClient(sonarLintClient); doThrow(new IOException("Broken pipe")).when(sonarLintClient).writeAndFlush(anyString()); underTest.broadcastMessage(event); underTest.registerClient(sonarLintClient); doThrow(new IllegalStateException("Things went wrong")).when(sonarLintClient).writeAndFlush(anyString()); underTest.broadcastMessage(event); verify(sonarLintClient, times(2)).close(); } @Test public void registerClient_whenCalledFirstTime_addsAsyncListenerToClient() { SonarLintClient client = mock(SonarLintClient.class); underTest.registerClient(client); verify(client).addListener(any()); } private SonarLintClient createSampleSLClient() { SonarLintClient mock = mock(SonarLintClient.class); when(mock.getLanguages()).thenReturn(Set.of("java")); when(mock.getClientProjectUuids()).thenReturn(exampleProjectUuids); when(mock.getUserUuid()).thenReturn("userUuid"); return mock; } }
11,189
39.690909
153
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/sonarlint/SonarLintPushActionTest.java
/* * 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.pushapi.sonarlint; import java.util.List; import java.util.stream.IntStream; import org.junit.Before; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.project.ProjectDao; import org.sonar.db.project.ProjectDto; import org.sonar.server.pushapi.TestPushRequest; import org.sonar.server.pushapi.WsPushActionTester; import org.sonar.server.user.UserSession; import org.sonar.server.ws.TestResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SonarLintPushActionTest { private final SonarLintClientsRegistry registry = mock(SonarLintClientsRegistry.class); private final UserSession userSession = mock(UserSession.class); private final DbClient dbClient = mock(DbClient.class); private final ProjectDao projectDao = mock(ProjectDao.class); private final SonarLintClientPermissionsValidator permissionsValidator = mock(SonarLintClientPermissionsValidator.class); private final WsPushActionTester ws = new WsPushActionTester(new SonarLintPushAction(registry, userSession, dbClient, permissionsValidator)); @Before public void before() { List<ProjectDto> projectDtos = generateProjectDtos(2); when(projectDao.selectProjectsByKeys(any(), any())).thenReturn(projectDtos); when(dbClient.projectDao()).thenReturn(projectDao); } public List<ProjectDto> generateProjectDtos(int howMany) { return IntStream.rangeClosed(1, howMany).mapToObj(i -> { ProjectDto dto = new ProjectDto(); dto.setKee("project" + i); return dto; }).toList(); } @Test public void defineTest() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("9.4"); assertThat(def.isInternal()).isTrue(); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder(tuple("languages", true), tuple("projectKeys", true)); } @Test public void handle_returnsNoResponseWhenParamsAndHeadersProvided() { TestResponse response = ws.newPushRequest() .setParam("projectKeys", "project1,project2") .setParam("languages", "java") .setHeader("accept", "text/event-stream") .execute(); assertThat(response.getInput()).isEmpty(); } @Test public void handle_whenAcceptHeaderNotProvided_statusCode406() { TestResponse testResponse = ws.newPushRequest().setParam("projectKeys", "project1,project2") .setParam("languages", "java") .execute(); assertThat(testResponse.getStatus()).isEqualTo(406); } @Test public void handle_whenParamsNotProvided_throwException() { TestPushRequest testRequest = ws.newPushRequest() .setHeader("accept", "text/event-stream"); assertThatThrownBy(testRequest::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'projectKeys' parameter is missing"); } @Test public void handle_whenParamProjectKeyNotValid_throwException() { TestPushRequest testRequest = ws.newPushRequest() .setParam("projectKeys", "not-valid-key") .setParam("languages", "java") .setHeader("accept", "text/event-stream"); when(projectDao.selectProjectsByKeys(any(), any())).thenReturn(List.of()); assertThatThrownBy(testRequest::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Param projectKeys is invalid."); } }
4,521
36.371901
143
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/testFixtures/java/org/sonar/server/pushapi/DumbPushResponse.java
/* * 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.pushapi; import com.google.common.base.Throwables; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.annotation.CheckForNull; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.server.ws.Response; import org.sonar.api.utils.text.JsonWriter; import org.sonar.api.utils.text.XmlWriter; import org.sonar.server.http.JavaxHttpResponse; import org.sonar.server.ws.ServletResponse; import org.sonar.server.ws.TestableResponse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DumbPushResponse extends ServletResponse implements TestableResponse { public DumbPushResponse() { super(initMock()); } private static HttpResponse initMock() { JavaxHttpResponse mock = mock(JavaxHttpResponse.class); when(mock.getDelegate()).thenReturn(mock(HttpServletResponse.class)); return mock; } private DumbPushResponse.InMemoryStream stream; private final ByteArrayOutputStream output = new ByteArrayOutputStream(); private Map<String, String> headers = new HashMap<>(); public class InMemoryStream extends ServletStream { private String mediaType; private int status = 200; public InMemoryStream() { super(mock(HttpServletResponse.class)); } @Override public ServletStream setMediaType(String s) { this.mediaType = s; return this; } @Override public ServletStream setStatus(int i) { this.status = i; return this; } @Override public OutputStream output() { return output; } } @Override public JsonWriter newJsonWriter() { return JsonWriter.of(new OutputStreamWriter(output, StandardCharsets.UTF_8)); } @Override public XmlWriter newXmlWriter() { return XmlWriter.of(new OutputStreamWriter(output, StandardCharsets.UTF_8)); } @Override public ServletStream stream() { if (stream == null) { stream = new DumbPushResponse.InMemoryStream(); } return stream; } @Override public Response noContent() { stream().setStatus(HttpURLConnection.HTTP_NO_CONTENT); IOUtils.closeQuietly(output); return this; } @CheckForNull public String mediaType() { return ((DumbPushResponse.InMemoryStream) stream()).mediaType; } public int status() { return ((InMemoryStream) stream()).status; } @Override public Response setHeader(String name, String value) { headers.put(name, value); return this; } public Collection<String> getHeaderNames() { return headers.keySet(); } @CheckForNull public String getHeader(String name) { return headers.get(name); } public byte[] getFlushedOutput() { try { output.flush(); return output.toByteArray(); } catch (IOException e) { throw Throwables.propagate(e); } } }
4,009
25.912752
83
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/testFixtures/java/org/sonar/server/pushapi/TestPushRequest.java
/* * 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.pushapi;/* * SonarQube * Copyright (C) 2009-2021 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. */ import com.google.common.base.Throwables; import java.util.Map; import java.util.Optional; import javax.servlet.AsyncContext; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.ws.ServletRequest; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import static org.mockito.Mockito.mock; public class TestPushRequest extends ServletRequest { private TestRequest testRequest = new TestRequest(); public TestPushRequest() { super(mock(JavaxHttpRequest.class)); } @Override public AsyncContext startAsync() { return mock(AsyncContext.class); } @Override public String method() { return testRequest.method(); } @Override public boolean hasParam(String key) { return testRequest.hasParam(key); } @Override public Map<String, String[]> getParams() { return testRequest.getParams(); } @Override public String readParam(String key) { return testRequest.readParam(key); } @Override public String getMediaType() { return testRequest.getMediaType(); } public TestPushRequest setParam(String key, String value) { testRequest.setParam(key, value); return this; } @Override public Map<String, String> getHeaders() { return testRequest.getHeaders(); } @Override public Optional<String> header(String name) { return testRequest.header(name); } public TestPushRequest setHeader(String name, String value) { testRequest.setHeader(name, value); return this; } public TestResponse execute() { try { DumbPushResponse response = new DumbPushResponse(); action().handler().handle(this, response); return new TestResponse(response); } catch (Exception e) { throw Throwables.propagate(e); } } }
3,508
28.487395
75
java
sonarqube
sonarqube-master/server/sonar-webserver-pushapi/src/testFixtures/java/org/sonar/server/pushapi/WsPushActionTester.java
/* * 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.pushapi;/* * SonarQube * Copyright (C) 2009-2021 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. */ import org.sonar.server.ws.WsAction; import org.sonar.server.ws.WsActionTester; public class WsPushActionTester extends WsActionTester { public WsPushActionTester(WsAction wsAction) { super(wsAction); } public TestPushRequest newPushRequest() { TestPushRequest request = new TestPushRequest(); request.setAction(action); return request; } }
2,087
37.666667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/it/java/org/sonar/server/v2/common/ControllerIT.java
/* * 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.v2.common; import org.junit.Before; import org.junit.runner.RunWith; import org.sonar.server.v2.config.MockConfigForControllers; import org.sonar.server.v2.config.PlatformLevel4WebConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @WebAppConfiguration @ContextConfiguration( classes = {PlatformLevel4WebConfig.class, MockConfigForControllers.class} ) @RunWith(SpringRunner.class) public abstract class ControllerIT { @Autowired protected WebApplicationContext webAppContext; protected MockMvc mockMvc; @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build(); } }
1,885
36.72
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/it/java/org/sonar/server/v2/config/MockConfigForControllers.java
/* * 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.v2.config; import org.sonar.db.DbClient; import org.sonar.server.health.CeStatusNodeCheck; import org.sonar.server.health.DbConnectionNodeCheck; import org.sonar.server.health.EsStatusNodeCheck; import org.sonar.server.health.HealthChecker; import org.sonar.server.health.WebServerStatusNodeCheck; import org.sonar.server.management.ManagedInstanceChecker; import org.sonar.server.platform.NodeInformation; import org.sonar.server.platform.ws.LivenessChecker; import org.sonar.server.user.SystemPasscode; import org.sonar.server.user.UserSession; import org.sonar.server.user.UserUpdater; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.mockito.Mockito.mock; @Configuration public class MockConfigForControllers { @Bean public DbClient dbClient() { return mock(DbClient.class); } @Bean public DbConnectionNodeCheck dbConnectionNodeCheck() { return mock(DbConnectionNodeCheck.class); } @Bean public WebServerStatusNodeCheck webServerStatusNodeCheck() { return mock(WebServerStatusNodeCheck.class); } @Bean public CeStatusNodeCheck ceStatusNodeCheck() { return mock(CeStatusNodeCheck.class); } @Bean public EsStatusNodeCheck esStatusNodeCheck() { return mock(EsStatusNodeCheck.class); } @Bean public LivenessChecker livenessChecker() { return mock(LivenessChecker.class); } @Bean public HealthChecker healthChecker() { return mock(HealthChecker.class); } @Bean public SystemPasscode systemPasscode() { return mock(SystemPasscode.class); } @Bean public NodeInformation nodeInformation() { return mock(NodeInformation.class); } @Bean public UserSession userSession() { return mock(UserSession.class); } @Bean UserUpdater userUpdater() { return mock(UserUpdater.class); } @Bean ManagedInstanceChecker managedInstanceChecker() { return mock(ManagedInstanceChecker.class); } }
2,856
27.009804
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/it/java/org/sonar/server/v2/controller/DefaultLivenessControllerIT.java
/* * 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.v2.controller; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.sonar.server.platform.ws.LivenessChecker; import org.sonar.server.user.SystemPasscode; import org.sonar.server.user.UserSession; import org.sonar.server.v2.common.ControllerIT; import static org.mockito.Mockito.when; import static org.sonar.server.user.SystemPasscodeImpl.PASSCODE_HTTP_HEADER; import static org.sonar.server.v2.WebApiEndpoints.LIVENESS_ENDPOINT; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class DefaultLivenessControllerIT extends ControllerIT { private static final String VALID_PASSCODE = "valid_passcode"; private static final String INVALID_PASSCODE = "invalid_passcode"; @Before public void setup() { super.setup(); when(webAppContext.getBean(LivenessChecker.class).liveness()).thenReturn(true); } @After public void resetUsedMocks() { Mockito.reset(webAppContext.getBean(SystemPasscode.class)); Mockito.reset(webAppContext.getBean(UserSession.class)); } @Test public void getSystemLiveness_whenValidPasscode_shouldSucceed() throws Exception { when(webAppContext.getBean(SystemPasscode.class).isValidPasscode(VALID_PASSCODE)).thenReturn(true); mockMvc.perform(get(LIVENESS_ENDPOINT).header(PASSCODE_HTTP_HEADER, VALID_PASSCODE)) .andExpect(status().isNoContent()); } @Test public void getSystemLiveness_whenAdminCredential_shouldSucceed() throws Exception { when(webAppContext.getBean(UserSession.class).isSystemAdministrator()).thenReturn(true); mockMvc.perform(get(LIVENESS_ENDPOINT)) .andExpect(status().isNoContent()); } @Test public void getSystemLiveness_whenNoUserSessionAndNoPasscode_shouldReturnForbidden() throws Exception { mockMvc.perform(get(LIVENESS_ENDPOINT)) .andExpectAll( status().isForbidden(), content().string("Insufficient privileges")); } @Test public void getSystemLiveness_whenInvalidPasscodeAndNoAdminCredentials_shouldReturnForbidden() throws Exception { when(webAppContext.getBean(SystemPasscode.class).isValidPasscode(INVALID_PASSCODE)).thenReturn(false); when(webAppContext.getBean(UserSession.class).isSystemAdministrator()).thenReturn(false); mockMvc.perform(get(LIVENESS_ENDPOINT).header(PASSCODE_HTTP_HEADER, INVALID_PASSCODE)) .andExpectAll( status().isForbidden(), content().string("Insufficient privileges")); } @Test public void getSystemLiveness_whenLivenessCheckFails_shouldReturnServerError() throws Exception { when(webAppContext.getBean(SystemPasscode.class).isValidPasscode(VALID_PASSCODE)).thenReturn(true); when(webAppContext.getBean(LivenessChecker.class).liveness()).thenReturn(false); mockMvc.perform(get(LIVENESS_ENDPOINT).header(PASSCODE_HTTP_HEADER, VALID_PASSCODE)) .andExpectAll( status().isInternalServerError(), content().string("Liveness check failed")); } }
4,059
39.19802
115
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/it/java/org/sonar/server/v2/controller/HealthControllerIT.java
/* * 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.v2.controller; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.health.Health; import org.sonar.server.health.HealthChecker; import org.sonar.server.platform.NodeInformation; import org.sonar.server.user.SystemPasscode; import org.sonar.server.user.UserSession; import org.sonar.server.v2.common.ControllerIT; import static java.net.HttpURLConnection.HTTP_NOT_IMPLEMENTED; import static org.mockito.Mockito.when; import static org.sonar.server.user.SystemPasscodeImpl.PASSCODE_HTTP_HEADER; import static org.sonar.server.v2.WebApiEndpoints.HEALTH_ENDPOINT; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class HealthControllerIT extends ControllerIT { private static final String VALID_PASSCODE = "valid_passcode"; private static final String INVALID_PASSCODE = "invalid_passcode"; private static final Health HEALTH_RESULT = Health.builder(). setStatus(Health.Status.YELLOW) .addCause("One cause") .build(); @Before public void setup() { super.setup(); when(webAppContext.getBean(HealthChecker.class).checkNode()).thenReturn(HEALTH_RESULT); } @After public void resetUsedMocks() { Mockito.reset(webAppContext.getBean(SystemPasscode.class)); Mockito.reset(webAppContext.getBean(NodeInformation.class)); Mockito.reset(webAppContext.getBean(UserSession.class)); } @Test public void getSystemHealth_whenValidPasscodeAndStandaloneMode_shouldSucceed() throws Exception { when(webAppContext.getBean(SystemPasscode.class).isValidPasscode(VALID_PASSCODE)).thenReturn(true); when(webAppContext.getBean(NodeInformation.class).isStandalone()).thenReturn(true); mockMvc.perform(get(HEALTH_ENDPOINT).header(PASSCODE_HTTP_HEADER, VALID_PASSCODE)) .andExpectAll( status().isOk(), content().json(""" { "status":"YELLOW", "causes":[ "One cause" ] }""")); } @Test public void getSystemHealth_whenAdminCredentialAndStandaloneMode_shouldSucceed() throws Exception { when(webAppContext.getBean(UserSession.class).isSystemAdministrator()).thenReturn(true); when(webAppContext.getBean(NodeInformation.class).isStandalone()).thenReturn(true); mockMvc.perform(get(HEALTH_ENDPOINT)) .andExpectAll( status().isOk(), content().json(""" { "status":"YELLOW", "causes":[ "One cause" ] }""")); } @Test public void getSystemHealth_whenNoCredentials_shouldReturnForbidden() throws Exception { mockMvc.perform(get(HEALTH_ENDPOINT)) .andExpectAll( status().isForbidden(), content().string("Insufficient privileges")); } @Test public void getSystemHealth_whenInvalidPasscodeAndNoAdminCredentials_shouldReturnForbidden() throws Exception { when(webAppContext.getBean(SystemPasscode.class).isValidPasscode(INVALID_PASSCODE)).thenReturn(false); when(webAppContext.getBean(UserSession.class).isSystemAdministrator()).thenReturn(false); mockMvc.perform(get(HEALTH_ENDPOINT).header(PASSCODE_HTTP_HEADER, INVALID_PASSCODE)) .andExpectAll( status().isForbidden(), content().string("Insufficient privileges")); } @Test public void getSystemHealth_whenUnauthorizedExceptionThrown_shouldReturnUnauthorized() throws Exception { when(webAppContext.getBean(UserSession.class).isSystemAdministrator()).thenThrow(new UnauthorizedException("UnauthorizedException")); mockMvc.perform(get(HEALTH_ENDPOINT)) .andExpectAll( status().isUnauthorized(), content().string("UnauthorizedException")); } @Test public void getSystemHealth_whenValidPasscodeAndClusterMode_shouldReturnNotImplemented() throws Exception { when(webAppContext.getBean(SystemPasscode.class).isValidPasscode(VALID_PASSCODE)).thenReturn(true); when(webAppContext.getBean(NodeInformation.class).isStandalone()).thenReturn(false); mockMvc.perform(get(HEALTH_ENDPOINT).header(PASSCODE_HTTP_HEADER, VALID_PASSCODE)) .andExpectAll( status().is(HTTP_NOT_IMPLEMENTED), content().string("Unsupported in cluster mode")); } }
5,396
37.827338
137
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/main/java/org/sonar/server/v2/WebApiEndpoints.java
/* * 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.v2; public class WebApiEndpoints { private static final String SYSTEM_ENDPOINTS = "/system"; public static final String LIVENESS_ENDPOINT = SYSTEM_ENDPOINTS + "/liveness"; public static final String HEALTH_ENDPOINT = SYSTEM_ENDPOINTS + "/health"; private WebApiEndpoints() { } }
1,161
35.3125
80
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/main/java/org/sonar/server/v2/package-info.java
/* * 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.v2; import javax.annotation.ParametersAreNonnullByDefault;
959
39
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/main/java/org/sonar/server/v2/common/RestResponseEntityExceptionHandler.java
/* * 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.v2.common; import java.util.Optional; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.ServerException; import org.sonar.server.exceptions.UnauthorizedException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class RestResponseEntityExceptionHandler { @ExceptionHandler(IllegalStateException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) protected ResponseEntity<Object> handleIllegalStateException(IllegalStateException illegalStateException) { return new ResponseEntity<>(illegalStateException.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(ForbiddenException.class) @ResponseStatus(HttpStatus.FORBIDDEN) protected ResponseEntity<Object> handleForbiddenException(ForbiddenException forbiddenException) { return handleServerException(forbiddenException); } @ExceptionHandler(UnauthorizedException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) protected ResponseEntity<Object> handleUnauthorizedException(UnauthorizedException unauthorizedException) { return handleServerException(unauthorizedException); } @ExceptionHandler(ServerException.class) protected ResponseEntity<Object> handleServerException(ServerException serverException) { return new ResponseEntity<>(serverException.getMessage(), Optional.ofNullable(HttpStatus.resolve(serverException.httpCode())).orElse(HttpStatus.INTERNAL_SERVER_ERROR)); } }
2,579
42.728814
172
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/main/java/org/sonar/server/v2/common/package-info.java
/* * 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.v2.common; import javax.annotation.ParametersAreNonnullByDefault;
966
39.291667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/main/java/org/sonar/server/v2/config/CommonWebConfig.java
/* * 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.v2.config; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import org.sonar.server.v2.common.RestResponseEntityExceptionHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration @EnableWebMvc @ComponentScan(basePackages = {"org.springdoc"}) @PropertySource("classpath:springdoc.properties") public class CommonWebConfig { @Bean public RestResponseEntityExceptionHandler restResponseEntityExceptionHandler() { return new RestResponseEntityExceptionHandler(); } @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info( new Info() .title("SonarQube Web API") .version("0.0.1 alpha") .description("Documentation of SonarQube Web API") ); } }
1,900
34.203704
82
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/main/java/org/sonar/server/v2/config/PlatformLevel4WebConfig.java
/* * 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.v2.config; import javax.annotation.Nullable; import org.sonar.server.health.CeStatusNodeCheck; import org.sonar.server.health.DbConnectionNodeCheck; import org.sonar.server.health.EsStatusNodeCheck; import org.sonar.server.health.HealthChecker; import org.sonar.server.health.WebServerStatusNodeCheck; import org.sonar.server.platform.NodeInformation; import org.sonar.server.platform.ws.LivenessChecker; import org.sonar.server.platform.ws.LivenessCheckerImpl; import org.sonar.server.user.SystemPasscode; import org.sonar.server.user.UserSession; import org.sonar.server.v2.controller.DefautLivenessController; import org.sonar.server.v2.controller.HealthController; import org.sonar.server.v2.controller.LivenessController; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import(CommonWebConfig.class) public class PlatformLevel4WebConfig { @Bean public LivenessChecker livenessChecker(DbConnectionNodeCheck dbConnectionNodeCheck, WebServerStatusNodeCheck webServerStatusNodeCheck, CeStatusNodeCheck ceStatusNodeCheck, @Nullable EsStatusNodeCheck esStatusNodeCheck) { return new LivenessCheckerImpl(dbConnectionNodeCheck, webServerStatusNodeCheck, ceStatusNodeCheck, esStatusNodeCheck); } @Bean public LivenessController livenessController(LivenessChecker livenessChecker, UserSession userSession, SystemPasscode systemPasscode) { return new DefautLivenessController(livenessChecker, systemPasscode, userSession); } @Bean public HealthController healthController(HealthChecker healthChecker, SystemPasscode systemPasscode, NodeInformation nodeInformation, UserSession userSession) { return new HealthController(healthChecker, systemPasscode, nodeInformation, userSession); } }
2,726
43.704918
173
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/main/java/org/sonar/server/v2/config/SafeModeWebConfig.java
/* * 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.v2.config; import org.sonar.server.health.DbConnectionNodeCheck; import org.sonar.server.health.HealthChecker; import org.sonar.server.platform.ws.LivenessChecker; import org.sonar.server.platform.ws.SafeModeLivenessCheckerImpl; import org.sonar.server.user.SystemPasscode; import org.sonar.server.v2.controller.DefautLivenessController; import org.sonar.server.v2.controller.HealthController; import org.sonar.server.v2.controller.LivenessController; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration @EnableWebMvc @Import(CommonWebConfig.class) public class SafeModeWebConfig { @Bean public LivenessChecker livenessChecker(DbConnectionNodeCheck dbConnectionNodeCheck) { return new SafeModeLivenessCheckerImpl(dbConnectionNodeCheck); } @Bean public LivenessController livenessController(LivenessChecker livenessChecker, SystemPasscode systemPasscode) { return new DefautLivenessController(livenessChecker, systemPasscode, null); } @Bean public HealthController healthController(HealthChecker healthChecker, SystemPasscode systemPasscode) { return new HealthController(healthChecker, systemPasscode); } }
2,211
39.218182
112
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/main/java/org/sonar/server/v2/config/package-info.java
/* * 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.v2.config; import javax.annotation.ParametersAreNonnullByDefault;
966
39.291667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/main/java/org/sonar/server/v2/controller/DefautLivenessController.java
/* * 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.v2.controller; import javax.annotation.Nullable; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.platform.ws.LivenessChecker; import org.sonar.server.user.SystemPasscode; import org.sonar.server.user.UserSession; import org.springframework.web.bind.annotation.RestController; @RestController public class DefautLivenessController implements LivenessController { private final LivenessChecker livenessChecker; private final UserSession userSession; private final SystemPasscode systemPasscode; public DefautLivenessController(LivenessChecker livenessChecker, SystemPasscode systemPasscode, @Nullable UserSession userSession) { this.livenessChecker = livenessChecker; this.userSession = userSession; this.systemPasscode = systemPasscode; } @Override public void livenessCheck(String requestPassCode) { if (systemPasscode.isValidPasscode(requestPassCode) || isSystemAdmin()) { if (livenessChecker.liveness()) { return; } throw new IllegalStateException("Liveness check failed"); } throw new ForbiddenException("Insufficient privileges"); } private boolean isSystemAdmin() { if (userSession == null) { return false; } return userSession.isSystemAdministrator(); } }
2,155
34.933333
134
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/main/java/org/sonar/server/v2/controller/HealthController.java
/* * 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.v2.controller; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.ServerException; import org.sonar.server.health.Health; import org.sonar.server.health.HealthChecker; import org.sonar.server.platform.NodeInformation; import org.sonar.server.user.SystemPasscode; import org.sonar.server.user.UserSession; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static java.net.HttpURLConnection.HTTP_NOT_IMPLEMENTED; import static org.sonar.server.v2.WebApiEndpoints.HEALTH_ENDPOINT; /* This controller does not support the cluster mode. This is not the final implementation, as we have to first define what are endpoint contracts. */ @RestController @RequestMapping(HEALTH_ENDPOINT) public class HealthController { private final HealthChecker healthChecker; private final SystemPasscode systemPasscode; private final NodeInformation nodeInformation; private final UserSession userSession; public HealthController(HealthChecker healthChecker, SystemPasscode systemPasscode, NodeInformation nodeInformation, UserSession userSession) { this.healthChecker = healthChecker; this.systemPasscode = systemPasscode; this.nodeInformation = nodeInformation; this.userSession = userSession; } public HealthController(HealthChecker healthChecker, SystemPasscode systemPasscode) { this(healthChecker, systemPasscode, null, null); } @GetMapping public Health getHealth(@RequestHeader(value = "X-Sonar-Passcode", required = false) String requestPassCode) { if (systemPasscode.isValidPasscode(requestPassCode) || isSystemAdmin()) { return getHealth(); } throw new ForbiddenException("Insufficient privileges"); } private Health getHealth() { if (nodeInformation == null || nodeInformation.isStandalone()) { return healthChecker.checkNode(); } throw new ServerException(HTTP_NOT_IMPLEMENTED, "Unsupported in cluster mode"); } private boolean isSystemAdmin() { if (userSession == null) { return false; } return userSession.isSystemAdministrator(); } }
3,156
36.583333
118
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/main/java/org/sonar/server/v2/controller/LivenessController.java
/* * 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.v2.controller; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import static org.sonar.server.v2.WebApiEndpoints.LIVENESS_ENDPOINT; @RequestMapping(LIVENESS_ENDPOINT) public interface LivenessController { @GetMapping @ResponseStatus(HttpStatus.NO_CONTENT) @Operation(summary = "Provide liveness of SonarQube, meant to be used as a liveness probe on Kubernetes", description = """ Require 'Administer System' permission or authentication with passcode. When SonarQube is fully started, liveness check for database connectivity, Compute Engine status, and, except for DataCenter Edition, if ElasticSearch is Green or Yellow. When SonarQube is on Safe Mode (for example when a database migration is running), liveness check only for database connectivity """) @ApiResponses(value = { @ApiResponse(responseCode = "204", description = "This SonarQube node is alive"), @ApiResponse(description = "This SonarQube node is not alive and should be rescheduled"), }) void livenessCheck( @Parameter(description = "Passcode can be provided, see SonarQube documentation") @RequestHeader(value = "X-Sonar-Passcode", required = false) String requestPassCode); }
2,526
46.679245
176
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi-v2/src/main/java/org/sonar/server/v2/controller/package-info.java
/* * 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.v2.controller; import javax.annotation.ParametersAreNonnullByDefault;
970
39.458333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/CheckPatActionIT.java
/* * 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.almintegration.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.azure.AzureDevOpsHttpClient; import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient; import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient; import org.sonar.alm.client.gitlab.GitlabHttpClient; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; 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.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; public class CheckPatActionIT { public static final String PAT_SECRET = "pat-secret"; @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final AzureDevOpsHttpClient azureDevOpsPrHttpClient = mock(AzureDevOpsHttpClient.class); private final BitbucketCloudRestClient bitbucketCloudRestClient = mock(BitbucketCloudRestClient.class); private final BitbucketServerRestClient bitbucketServerRestClient = mock(BitbucketServerRestClient.class); private final GitlabHttpClient gitlabPrHttpClient = mock(GitlabHttpClient.class); private final WsActionTester ws = new WsActionTester(new CheckPatAction(db.getDbClient(), userSession, azureDevOpsPrHttpClient, bitbucketCloudRestClient, bitbucketServerRestClient, gitlabPrHttpClient)); @Test public void check_pat_for_github() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); TestRequest request = ws.newRequest().setParam("almSetting", almSetting.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("unsupported DevOps Platform GITHUB"); } @Test public void check_pat_for_azure_devops() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); dto.setPersonalAccessToken(PAT_SECRET); }); ws.newRequest() .setParam("almSetting", almSetting.getKey()) .execute(); assertThat(almSetting.getUrl()).isNotNull(); verify(azureDevOpsPrHttpClient).checkPAT(almSetting.getUrl(), PAT_SECRET); } @Test public void check_pat_for_bitbucket() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); dto.setPersonalAccessToken(PAT_SECRET); }); ws.newRequest() .setParam("almSetting", almSetting.getKey()) .execute(); assertThat(almSetting.getUrl()).isNotNull(); verify(bitbucketServerRestClient).getRecentRepo(almSetting.getUrl(), PAT_SECRET); } @Test public void check_pat_for_gitlab() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); dto.setPersonalAccessToken(PAT_SECRET); }); ws.newRequest() .setParam("almSetting", almSetting.getKey()) .execute(); assertThat(almSetting.getUrl()).isNotNull(); verify(gitlabPrHttpClient).searchProjects(almSetting.getUrl(), PAT_SECRET, null, null, null); } @Test public void check_pat_for_bitbucketcloud() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); dto.setPersonalAccessToken(PAT_SECRET); }); ws.newRequest() .setParam("almSetting", almSetting.getKey()) .execute(); assertThat(almSetting.getAppId()).isNotNull(); verify(bitbucketCloudRestClient).validateAppPassword(PAT_SECRET, almSetting.getAppId()); } @Test public void fail_when_personal_access_token_is_invalid_for_bitbucket() { when(bitbucketServerRestClient.getRecentRepo(any(), any())).thenThrow(new IllegalArgumentException("Invalid personal access token")); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); TestRequest request = ws.newRequest().setParam("almSetting", almSetting.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Invalid personal access token"); } @Test public void fail_when_personal_access_token_is_invalid_for_gitlab() { when(gitlabPrHttpClient.searchProjects(any(), any(), any(), any(), any())) .thenThrow(new IllegalArgumentException("Invalid personal access token")); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); TestRequest request = ws.newRequest().setParam("almSetting", almSetting.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Invalid personal access token"); } @Test public void fail_when_personal_access_token_is_invalid_for_bitbucketcloud() { doThrow(new IllegalArgumentException("Invalid personal access token")) .when(bitbucketCloudRestClient).validateAppPassword(anyString(), anyString()); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); TestRequest request = ws.newRequest().setParam("almSetting", almSetting.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Invalid personal access token"); } @Test public void fail_when_not_logged_in() { TestRequest request = ws.newRequest().setParam("almSetting", "anyvalue"); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_no_creation_project_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); TestRequest request = ws.newRequest().setParam("almSetting", "anyvalue"); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void check_pat_is_missing() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketAlmSetting(); TestRequest request = ws.newRequest().setParam("almSetting", almSetting.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("personal access token for '" + almSetting.getKey() + "' is missing"); } @Test public void fail_check_pat_alm_setting_not_found() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmPatDto almPatDto = newAlmPatDto(); db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null); TestRequest request = ws.newRequest().setParam("almSetting", "testKey"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("DevOps Platform Setting 'testKey' not found"); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.2"); assertThat(def.isPost()).isFalse(); assertThat(def.isInternal()).isTrue(); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder(tuple("almSetting", true)); } }
10,667
38.657993
137
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/ImportHelperIT.java
/* * 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.almintegration.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.component.ProjectTesting; import org.sonar.db.project.ProjectDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.tester.UserSessionRule; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.almsettings.AlmSettingsTesting.newGithubAlmSettingDto; import static org.sonarqube.ws.Projects.CreateWsResponse; public class ImportHelperIT { private static final AlmSettingDto ALM_SETTING_WITH_WEBHOOK_SECRET = newGithubAlmSettingDto().setWebhookSecret("webhook_secret"); private final System2 system2 = System2.INSTANCE; private final ProjectDto projectDto = ProjectTesting.newPublicProjectDto(); private final Request request = mock(Request.class); @Rule public final DbTester db = DbTester.create(system2); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private final ImportHelper underTest = new ImportHelper(db.getDbClient(), userSession); @Test public void it_throws_exception_when_provisioning_project_without_permission() { assertThatThrownBy(() -> underTest.checkProvisionProjectPermission()) .isInstanceOf(UnauthorizedException.class) .hasMessage("Authentication is required"); } @Test public void it_throws_exception_on_get_alm_setting_when_key_is_empty() { assertThatThrownBy(() -> underTest.getAlmSetting(request)) .isInstanceOf(NotFoundException.class); } @Test public void it_throws_exception_on_get_alm_setting_when_key_is_not_found() { when(request.mandatoryParam(ImportHelper.PARAM_ALM_SETTING)).thenReturn("key"); assertThatThrownBy(() -> underTest.getAlmSetting(request)) .isInstanceOf(NotFoundException.class) .hasMessage("DevOps Platform Setting 'key' not found"); } @Test public void it_throws_exception_when_user_uuid_is_null() { assertThatThrownBy(() -> underTest.getUserUuid()) .isInstanceOf(NullPointerException.class) .hasMessage("User UUID cannot be null"); } @Test public void it_returns_create_response() { CreateWsResponse response = ImportHelper.toCreateResponse(projectDto); CreateWsResponse.Project project = response.getProject(); assertThat(project).extracting(CreateWsResponse.Project::getKey, CreateWsResponse.Project::getName, CreateWsResponse.Project::getQualifier) .containsExactly(projectDto.getKey(), projectDto.getName(), projectDto.getQualifier()); } @Test public void getAlmSetting_whenAlmSettingExists_shouldReturnActualAlmSetting(){ AlmSettingDto almSettingDto = db.almSettings().insertAzureAlmSetting(); when( request.mandatoryParam(ImportHelper.PARAM_ALM_SETTING)).thenReturn(almSettingDto.getKey()); AlmSettingDto result = underTest.getAlmSetting(request); assertThat(result.getUuid()).isEqualTo(almSettingDto.getUuid()); } }
4,143
38.466667
131
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/SetPatActionIT.java
/* * 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.almintegration.ws; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.ALM; import org.sonar.db.alm.setting.AlmSettingDto; 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.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; public class SetPatActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final WsActionTester ws = new WsActionTester(new SetPatAction(db.getDbClient(), userSession)); @Test public void set_new_azuredevops_pat() { UserDto user = db.users().insertUser(); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("pat", "12345678987654321") .execute(); Optional<AlmPatDto> actualAlmPat = db.getDbClient().almPatDao().selectByUserAndAlmSetting(db.getSession(), user.getUuid(), almSetting); assertThat(actualAlmPat).isPresent(); assertThat(actualAlmPat.get().getPersonalAccessToken()).isEqualTo("12345678987654321"); assertThat(actualAlmPat.get().getUserUuid()).isEqualTo(user.getUuid()); assertThat(actualAlmPat.get().getAlmSettingUuid()).isEqualTo(almSetting.getUuid()); } @Test public void set_new_bitbucketserver_pat() { UserDto user = db.users().insertUser(); AlmSettingDto almSetting = db.almSettings().insertBitbucketAlmSetting(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("pat", "12345678987654321") .execute(); Optional<AlmPatDto> actualAlmPat = db.getDbClient().almPatDao().selectByUserAndAlmSetting(db.getSession(), user.getUuid(), almSetting); assertThat(actualAlmPat).isPresent(); assertThat(actualAlmPat.get().getPersonalAccessToken()).isEqualTo("12345678987654321"); assertThat(actualAlmPat.get().getUserUuid()).isEqualTo(user.getUuid()); assertThat(actualAlmPat.get().getAlmSettingUuid()).isEqualTo(almSetting.getUuid()); } @Test public void set_new_bitbucketcloud_pat() { UserDto user = db.users().insertUser(); AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); String pat = "12345678987654321"; String username = "test-user"; ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("pat", pat) .setParam("username", username) .execute(); Optional<AlmPatDto> actualAlmPat = db.getDbClient().almPatDao().selectByUserAndAlmSetting(db.getSession(), user.getUuid(), almSetting); assertThat(actualAlmPat).isPresent(); assertThat(actualAlmPat.get().getPersonalAccessToken()).isEqualTo(CredentialsEncoderHelper.encodeCredentials(ALM.BITBUCKET_CLOUD, pat, username)); assertThat(actualAlmPat.get().getUserUuid()).isEqualTo(user.getUuid()); assertThat(actualAlmPat.get().getAlmSettingUuid()).isEqualTo(almSetting.getUuid()); } @Test public void set_new_gitlab_pat() { UserDto user = db.users().insertUser(); AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("pat", "12345678987654321") .execute(); Optional<AlmPatDto> actualAlmPat = db.getDbClient().almPatDao().selectByUserAndAlmSetting(db.getSession(), user.getUuid(), almSetting); assertThat(actualAlmPat).isPresent(); assertThat(actualAlmPat.get().getPersonalAccessToken()).isEqualTo("12345678987654321"); assertThat(actualAlmPat.get().getUserUuid()).isEqualTo(user.getUuid()); assertThat(actualAlmPat.get().getAlmSettingUuid()).isEqualTo(almSetting.getUuid()); } @Test public void set_existing_pat() { UserDto user = db.users().insertUser(); AlmSettingDto almSetting = db.almSettings().insertBitbucketAlmSetting(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); db.almPats().insert(p -> p.setUserUuid(user.getUuid()), p -> p.setAlmSettingUuid(almSetting.getUuid())); ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("pat", "newtoken") .execute(); Optional<AlmPatDto> actualAlmPat = db.getDbClient().almPatDao().selectByUserAndAlmSetting(db.getSession(), user.getUuid(), almSetting); assertThat(actualAlmPat).isPresent(); assertThat(actualAlmPat.get().getPersonalAccessToken()).isEqualTo("newtoken"); assertThat(actualAlmPat.get().getUserUuid()).isEqualTo(user.getUuid()); assertThat(actualAlmPat.get().getAlmSettingUuid()).isEqualTo(almSetting.getUuid()); } @Test public void fail_when_bitbucketcloud_without_username() { UserDto user = db.users().insertUser(); AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); assertThatThrownBy(() -> { ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("pat", "12345678987654321") .execute(); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Username cannot be null for Bitbucket Cloud"); } @Test public void fail_when_alm_setting_unknow() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); assertThatThrownBy(() -> { ws.newRequest() .setParam("almSetting", "notExistingKey") .setParam("pat", "12345678987654321") .execute(); }) .isInstanceOf(NotFoundException.class) .hasMessage("DevOps Platform Setting 'notExistingKey' not found"); } @Test public void fail_when_alm_setting_not_bitbucket_server_nor_gitlab() { UserDto user = db.users().insertUser(); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); assertThatThrownBy(() -> { ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("pat", "12345678987654321") .execute(); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Only Azure DevOps, Bitbucket Server, GitLab and Bitbucket Cloud Settings are supported."); } @Test public void fail_when_not_logged_in() { assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_no_creation_project_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.2"); assertThat(def.isPost()).isTrue(); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder(tuple("almSetting", true), tuple("pat", true), tuple("username", false)); } }
8,730
38.506787
150
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/azure/ImportAzureProjectActionIT.java
/* * 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.almintegration.ws.azure; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.azure.AzureDevOpsHttpClient; import org.sonar.alm.client.azure.GsonAzureProject; import org.sonar.alm.client.azure.GsonAzureRepo; import org.sonar.api.config.internal.Encryption; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.core.platform.EditionProvider; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.component.BranchDto; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.almintegration.ws.ImportHelper; import org.sonar.server.almintegration.ws.ProjectKeyGenerator; import org.sonar.server.component.ComponentUpdater; import org.sonar.server.es.TestIndexers; 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.favorite.FavoriteUpdater; import org.sonar.server.l18n.I18nRule; import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver; import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.project.DefaultBranchNameResolver; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.project.Visibility; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Projects; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; import static org.sonar.db.newcodeperiod.NewCodePeriodType.NUMBER_OF_DAYS; import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.db.permission.GlobalPermission.SCAN; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE; public class ImportAzureProjectActionIT { private static final String GENERATED_PROJECT_KEY = "TEST_PROJECT_KEY"; @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); @Rule public final I18nRule i18n = new I18nRule(); private final AzureDevOpsHttpClient azureDevOpsHttpClient = mock(AzureDevOpsHttpClient.class); private final DefaultBranchNameResolver defaultBranchNameResolver = mock(DefaultBranchNameResolver.class); private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), i18n, System2.INSTANCE, mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestIndexers(), new SequenceUuidFactory(), defaultBranchNameResolver, true); private final Encryption encryption = mock(Encryption.class); private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession); private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class); private final ProjectKeyGenerator projectKeyGenerator = mock(ProjectKeyGenerator.class); private PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class); private NewCodeDefinitionResolver newCodeDefinitionResolver = new NewCodeDefinitionResolver(db.getDbClient(), editionProvider); private final ImportAzureProjectAction importAzureProjectAction = new ImportAzureProjectAction(db.getDbClient(), userSession, azureDevOpsHttpClient, projectDefaultVisibility, componentUpdater, importHelper, projectKeyGenerator, newCodeDefinitionResolver, defaultBranchNameResolver); private final WsActionTester ws = new WsActionTester(importAzureProjectAction); @Before public void before() { when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE); when(projectKeyGenerator.generateUniqueProjectKey(any(), any())).thenReturn(GENERATED_PROJECT_KEY); when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn(DEFAULT_MAIN_BRANCH_NAME); } @Test public void import_project() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setPersonalAccessToken(almSetting.getDecryptedPersonalAccessToken(encryption)); dto.setUserUuid(user.getUuid()); }); GsonAzureRepo repo = getGsonAzureRepo(); when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getDecryptedPersonalAccessToken(encryption), "project-name", "repo-name")) .thenReturn(repo); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectName", "project-name") .setParam("repositoryName", "repo-name") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY); assertThat(result.getName()).isEqualTo(repo.getName()); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); Optional<ProjectAlmSettingDto> projectAlmSettingDto = db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get()); assertThat(projectAlmSettingDto.get().getAlmRepo()).isEqualTo("repo-name"); assertThat(projectAlmSettingDto.get().getAlmSettingUuid()).isEqualTo(almSetting.getUuid()); assertThat(projectAlmSettingDto.get().getAlmSlug()).isEqualTo("project-name"); Optional<BranchDto> mainBranch = db.getDbClient() .branchDao() .selectByProject(db.getSession(), projectDto.get()) .stream() .filter(BranchDto::isMain) .findFirst(); assertThat(mainBranch).isPresent(); assertThat(mainBranch.get().getKey()).hasToString("repo-default-branch"); verify(projectKeyGenerator).generateUniqueProjectKey(repo.getProject().getName(), repo.getName()); } @Test public void import_project_with_NCD_developer_edition() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setPersonalAccessToken(almSetting.getDecryptedPersonalAccessToken(encryption)); dto.setUserUuid(user.getUuid()); }); GsonAzureRepo repo = getGsonAzureRepo(); when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getDecryptedPersonalAccessToken(encryption), "project-name", "repo-name")) .thenReturn(repo); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectName", "project-name") .setParam("repositoryName", "repo-name") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS") .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid) .containsExactly(NUMBER_OF_DAYS, "30", null); } @Test public void import_project_with_NCD_community_edition() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setPersonalAccessToken(almSetting.getDecryptedPersonalAccessToken(encryption)); dto.setUserUuid(user.getUuid()); }); GsonAzureRepo repo = getGsonAzureRepo(); when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getDecryptedPersonalAccessToken(encryption), "project-name", "repo-name")) .thenReturn(repo); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectName", "project-name") .setParam("repositoryName", "repo-name") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS") .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); String projectUuid = projectDto.get().getUuid(); assertThat(db.getDbClient().newCodePeriodDao().selectByBranch(db.getSession(), projectUuid, projectUuid)) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid) .containsExactly(NUMBER_OF_DAYS, "30", projectUuid); } @Test public void import_project_throw_IAE_when_newCodeDefinitionValue_provided_and_no_newCodeDefinitionType() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setPersonalAccessToken(almSetting.getDecryptedPersonalAccessToken(encryption)); dto.setUserUuid(user.getUuid()); }); GsonAzureRepo repo = getGsonAzureRepo(); when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getDecryptedPersonalAccessToken(encryption), "project-name", "repo-name")) .thenReturn(repo); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectName", "project-name") .setParam("repositoryName", "repo-name") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS") .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid) .containsExactly(NUMBER_OF_DAYS, "30", null); } @Test public void import_project_reference_branch_ncd_no_default_branch_name() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setPersonalAccessToken(almSetting.getDecryptedPersonalAccessToken(encryption)); dto.setUserUuid(user.getUuid()); }); GsonAzureRepo repo = getEmptyGsonAzureRepo(); when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getDecryptedPersonalAccessToken(encryption), "project-name", "repo-name")) .thenReturn(repo); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectName", "project-name") .setParam("repositoryName", "repo-name") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "REFERENCE_BRANCH") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue) .containsExactly(REFERENCE_BRANCH, DEFAULT_MAIN_BRANCH_NAME); } @Test public void import_project_reference_branch_ncd() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setPersonalAccessToken(almSetting.getDecryptedPersonalAccessToken(encryption)); dto.setUserUuid(user.getUuid()); }); GsonAzureRepo repo = getGsonAzureRepo(); when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getDecryptedPersonalAccessToken(encryption), "project-name", "repo-name")) .thenReturn(repo); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectName", "project-name") .setParam("repositoryName", "repo-name") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "REFERENCE_BRANCH") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue) .containsExactly(REFERENCE_BRANCH, "repo-default-branch"); } @Test public void import_project_from_empty_repo() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setPersonalAccessToken(almSetting.getDecryptedPersonalAccessToken(encryption)); dto.setUserUuid(user.getUuid()); }); GsonAzureRepo repo = getEmptyGsonAzureRepo(); when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getDecryptedPersonalAccessToken(encryption), "project-name", "repo-name")) .thenReturn(repo); TestRequest request = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectName", "project-name") .setParam("repositoryName", "repo-name") .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30"); assertThatThrownBy(() -> request.executeProtobuf(Projects.CreateWsResponse.class)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("New code definition type is required when new code definition value is provided"); } @Test public void fail_when_not_logged_in() { TestRequest request = ws.newRequest() .setParam("almSetting", "azure") .setParam("projectName", "project-name") .setParam("repositoryName", "repo-name"); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_missing_project_creator_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(SCAN); TestRequest request = ws.newRequest() .setParam("almSetting", "azure") .setParam("projectName", "project-name") .setParam("repositoryName", "repo-name"); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void check_pat_is_missing() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); TestRequest request = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectName", "project-name") .setParam("repositoryName", "repo-name"); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("personal access token for '" + almSetting.getKey() + "' is missing"); } @Test public void fail_check_alm_setting_not_found() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmPatDto almPatDto = newAlmPatDto(); db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null); TestRequest request = ws.newRequest() .setParam("almSetting", "testKey"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("DevOps Platform Setting 'testKey' not found"); } @Test public void fail_project_already_exists() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setPersonalAccessToken(almSetting.getDecryptedPersonalAccessToken(encryption)); dto.setUserUuid(user.getUuid()); }); GsonAzureRepo repo = getGsonAzureRepo(); db.components().insertPublicProject(p -> p.setKey(GENERATED_PROJECT_KEY)).getMainBranchComponent(); when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getDecryptedPersonalAccessToken(encryption), "project-name", "repo-name")).thenReturn(repo); TestRequest request = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectName", "project-name") .setParam("repositoryName", "repo-name"); assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Could not create Project with key: \"%s\". A similar key already exists: \"%s\"", GENERATED_PROJECT_KEY, GENERATED_PROJECT_KEY); } @Test public void define() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.6"); assertThat(def.isPost()).isTrue(); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("almSetting", true), tuple("projectName", true), tuple("repositoryName", true), tuple(PARAM_NEW_CODE_DEFINITION_TYPE, false), tuple(PARAM_NEW_CODE_DEFINITION_VALUE, false)); } private GsonAzureRepo getGsonAzureRepo() { return new GsonAzureRepo("repo-id", "repo-name", "repo-url", new GsonAzureProject("project-name", "project-description"), "refs/heads/repo-default-branch"); } private GsonAzureRepo getEmptyGsonAzureRepo() { return new GsonAzureRepo("repo-id", "repo-name", "repo-url", new GsonAzureProject("project-name", "project-description"), null); } }
21,720
43.878099
132
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/azure/ListAzureProjectsActionIT.java
/* * 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.almintegration.ws.azure; import com.google.common.collect.ImmutableList; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.azure.AzureDevOpsHttpClient; import org.sonar.alm.client.azure.GsonAzureProject; import org.sonar.alm.client.azure.GsonAzureProjectList; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; 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.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.AlmIntegrations.AzureProject; import org.sonarqube.ws.AlmIntegrations.ListAzureProjectsWsResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; public class ListAzureProjectsActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final AzureDevOpsHttpClient azureDevOpsHttpClient = mock(AzureDevOpsHttpClient.class); private final WsActionTester ws = new WsActionTester(new ListAzureProjectsAction(db.getDbClient(), userSession, azureDevOpsHttpClient)); @Before public void before() { mockClient(ImmutableList.of(new GsonAzureProject("name", "description"), new GsonAzureProject("name", null))); } private void mockClient(List<GsonAzureProject> projects) { GsonAzureProjectList projectList = new GsonAzureProjectList(); projectList.setValues(projects); when(azureDevOpsHttpClient.getProjects(anyString(), anyString())).thenReturn(projectList); } @Test public void list_projects() { AlmSettingDto almSetting = insertAlmSetting(); ListAzureProjectsWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(ListAzureProjectsWsResponse.class); assertThat(response.getProjectsCount()).isEqualTo(2); assertThat(response.getProjectsList()) .extracting(AzureProject::getName, AzureProject::getDescription) .containsExactly(tuple("name", "description"), tuple("name", "")); } @Test public void list_projects_alphabetically_sorted() { mockClient(ImmutableList.of(new GsonAzureProject("BBB project", "BBB project description"), new GsonAzureProject("AAA project 1", "AAA project description"), new GsonAzureProject("zzz project", "zzz project description"), new GsonAzureProject("aaa project", "aaa project description"))); AlmSettingDto almSetting = insertAlmSetting(); ListAzureProjectsWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(ListAzureProjectsWsResponse.class); assertThat(response.getProjectsCount()).isEqualTo(4); assertThat(response.getProjectsList()) .extracting(AzureProject::getName, AzureProject::getDescription) .containsExactly(tuple("aaa project", "aaa project description"), tuple("AAA project 1", "AAA project description"), tuple("BBB project", "BBB project description"), tuple("zzz project", "zzz project description")); } @Test public void check_pat_is_missing() { insertUser(); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); TestRequest request = ws.newRequest() .setParam("almSetting", almSetting.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("No personal access token found"); } @Test public void fail_check_alm_setting_not_found() { UserDto user = insertUser(); AlmPatDto almPatDto = newAlmPatDto(); db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null); TestRequest request = ws.newRequest() .setParam("almSetting", "testKey"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("DevOps Platform Setting 'testKey' not found"); } @Test public void fail_when_not_logged_in() { TestRequest request = ws.newRequest() .setParam("almSetting", "anyvalue"); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_no_creation_project_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); TestRequest request = ws.newRequest() .setParam("almSetting", "anyvalue"); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.6"); assertThat(def.isPost()).isFalse(); assertThat(def.responseExampleFormat()).isEqualTo("json"); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder(tuple("almSetting", true)); } private UserDto insertUser() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); return user; } private AlmSettingDto insertAlmSetting() { UserDto user = insertUser(); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); return almSetting; } }
6,942
36.733696
138
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/azure/SearchAzureReposActionIT.java
/* * 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.almintegration.ws.azure; import com.google.common.collect.ImmutableList; import org.jetbrains.annotations.NotNull; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.azure.AzureDevOpsHttpClient; import org.sonar.alm.client.azure.GsonAzureProject; import org.sonar.alm.client.azure.GsonAzureRepo; import org.sonar.alm.client.azure.GsonAzureRepoList; import org.sonar.api.config.internal.Encryption; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.project.ProjectDto; 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.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonarqube.ws.AlmIntegrations.AzureRepo; import static org.sonarqube.ws.AlmIntegrations.SearchAzureReposWsResponse; public class SearchAzureReposActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final AzureDevOpsHttpClient azureDevOpsHttpClient = mock(AzureDevOpsHttpClient.class); private final Encryption encryption = mock(Encryption.class); private final WsActionTester ws = new WsActionTester(new SearchAzureReposAction(db.getDbClient(), userSession, azureDevOpsHttpClient)); @Before public void before() { mockClient(new GsonAzureRepoList(ImmutableList.of(getGsonAzureRepo("project-1", "repoName-1"), getGsonAzureRepo("project-2", "repoName-2")))); } @Test public void define() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.6"); assertThat(def.isPost()).isFalse(); assertThat(def.responseExampleFormat()).isEqualTo("json"); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("almSetting", true), tuple("projectName", false), tuple("searchQuery", false)); } @Test public void search_repos() { AlmSettingDto almSetting = insertAlmSetting(); SearchAzureReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchAzureReposWsResponse.class); assertThat(response.getRepositoriesList()) .extracting(AzureRepo::getName, AzureRepo::getProjectName) .containsExactlyInAnyOrder( tuple("repoName-1", "project-1"), tuple("repoName-2", "project-2")); } @Test public void search_repos_alphabetically_sorted() { mockClient(new GsonAzureRepoList(ImmutableList.of(getGsonAzureRepo("project-1", "Z-repo"), getGsonAzureRepo("project-1", "A-repo-1"), getGsonAzureRepo("project-1", "a-repo"), getGsonAzureRepo("project-1", "b-repo")))); AlmSettingDto almSetting = insertAlmSetting(); SearchAzureReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchAzureReposWsResponse.class); assertThat(response.getRepositoriesList()) .extracting(AzureRepo::getName, AzureRepo::getProjectName) .containsExactly( tuple("a-repo", "project-1"), tuple("A-repo-1", "project-1"), tuple("b-repo", "project-1"), tuple("Z-repo", "project-1")); } @Test public void search_repos_with_project_already_set_up() { AlmSettingDto almSetting = insertAlmSetting(); ProjectDto projectDto2 = insertProject(almSetting, "repoName-2", "project-2"); SearchAzureReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchAzureReposWsResponse.class); assertThat(response.getRepositoriesCount()).isEqualTo(2); assertThat(response.getRepositoriesList()) .extracting(AzureRepo::getName, AzureRepo::getProjectName, AzureRepo::getSqProjectKey, AzureRepo::getSqProjectName) .containsExactlyInAnyOrder( tuple("repoName-1", "project-1", "", ""), tuple("repoName-2", "project-2", projectDto2.getKey(), projectDto2.getName())); } @Test public void search_repos_with_project_already_set_u_and_collision_is_handled() { AlmSettingDto almSetting = insertAlmSetting(); ProjectDto projectDto2 = insertProject(almSetting, "repoName-2", "project-2"); insertProject(almSetting, "repoName-2", "project-2"); SearchAzureReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchAzureReposWsResponse.class); assertThat(response.getRepositoriesCount()).isEqualTo(2); assertThat(response.getRepositoriesList()) .extracting(AzureRepo::getName, AzureRepo::getProjectName, AzureRepo::getSqProjectKey, AzureRepo::getSqProjectName) .containsExactlyInAnyOrder( tuple("repoName-1", "project-1", "", ""), tuple("repoName-2", "project-2", projectDto2.getKey(), projectDto2.getName())); } @Test public void search_repos_with_projects_already_set_up_and_no_collision() { mockClient(new GsonAzureRepoList(ImmutableList.of(getGsonAzureRepo("project-1", "repoName-1"), getGsonAzureRepo("project", "1-repoName-1")))); AlmSettingDto almSetting = insertAlmSetting(); ProjectDto projectDto1 = insertProject(almSetting, "repoName-1", "project-1"); ProjectDto projectDto2 = insertProject(almSetting, "1-repoName-1", "project"); SearchAzureReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchAzureReposWsResponse.class); assertThat(response.getRepositoriesCount()).isEqualTo(2); assertThat(response.getRepositoriesList()) .extracting(AzureRepo::getName, AzureRepo::getProjectName, AzureRepo::getSqProjectKey, AzureRepo::getSqProjectName) .containsExactlyInAnyOrder( tuple("repoName-1", "project-1", projectDto1.getKey(), projectDto1.getName()), tuple("1-repoName-1", "project", projectDto2.getKey(), projectDto2.getName())); } @Test public void search_repos_with_same_name_and_different_project() { mockClient(new GsonAzureRepoList(ImmutableList.of(getGsonAzureRepo("project-1", "repoName-1"), getGsonAzureRepo("project-2", "repoName-1")))); AlmSettingDto almSetting = insertAlmSetting(); ProjectDto projectDto1 = insertProject(almSetting, "repoName-1", "project-1"); ProjectDto projectDto2 = insertProject(almSetting, "repoName-1", "project-2"); SearchAzureReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchAzureReposWsResponse.class); assertThat(response.getRepositoriesCount()).isEqualTo(2); assertThat(response.getRepositoriesList()) .extracting(AzureRepo::getName, AzureRepo::getProjectName, AzureRepo::getSqProjectKey, AzureRepo::getSqProjectName) .containsExactlyInAnyOrder( tuple("repoName-1", "project-1", projectDto1.getKey(), projectDto1.getName()), tuple("repoName-1", "project-2", projectDto2.getKey(), projectDto2.getName())); } @Test public void search_repos_with_project_name() { AlmSettingDto almSetting = insertAlmSetting(); SearchAzureReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectName", "project-1") .executeProtobuf(SearchAzureReposWsResponse.class); assertThat(response.getRepositoriesList()) .extracting(AzureRepo::getName, AzureRepo::getProjectName) .containsExactlyInAnyOrder( tuple("repoName-1", "project-1"), tuple("repoName-2", "project-2")); } @Test public void search_repos_with_project_name_and_empty_criteria() { AlmSettingDto almSetting = insertAlmSetting(); SearchAzureReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectName", "project-1") .setParam("searchQuery", "") .executeProtobuf(SearchAzureReposWsResponse.class); assertThat(response.getRepositoriesList()) .extracting(AzureRepo::getName, AzureRepo::getProjectName) .containsExactlyInAnyOrder( tuple("repoName-1", "project-1"), tuple("repoName-2", "project-2")); } @Test public void search_and_filter_repos_with_repo_name() { AlmSettingDto almSetting = insertAlmSetting(); SearchAzureReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("searchQuery", "repoName-2") .executeProtobuf(SearchAzureReposWsResponse.class); assertThat(response.getRepositoriesList()) .extracting(AzureRepo::getName, AzureRepo::getProjectName) .containsExactlyInAnyOrder(tuple("repoName-2", "project-2")); } @Test public void search_and_filter_repos_with_matching_repo_and_project_name() { mockClient(new GsonAzureRepoList(ImmutableList.of(getGsonAzureRepo("big-project", "repo-1"), getGsonAzureRepo("big-project", "repo-2"), getGsonAzureRepo("big-project", "big-repo"), getGsonAzureRepo("project", "big-repo"), getGsonAzureRepo("project", "small-repo")))); AlmSettingDto almSetting = insertAlmSetting(); SearchAzureReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("searchQuery", "big") .executeProtobuf(SearchAzureReposWsResponse.class); assertThat(response.getRepositoriesList()) .extracting(AzureRepo::getName, AzureRepo::getProjectName) .containsExactlyInAnyOrder(tuple("repo-1", "big-project"), tuple("repo-2", "big-project"), tuple("big-repo", "big-project"), tuple("big-repo", "project")); } @Test public void return_empty_list_when_there_are_no_azure_repos() { when(azureDevOpsHttpClient.getRepos(any(), any(), any())).thenReturn(new GsonAzureRepoList(emptyList())); AlmSettingDto almSetting = insertAlmSetting(); SearchAzureReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchAzureReposWsResponse.class); assertThat(response.getRepositoriesList()).isEmpty(); } @Test public void check_pat_is_missing() { insertUser(); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); TestRequest request = ws.newRequest() .setParam("almSetting", almSetting.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("No personal access token found"); } @Test public void fail_check_pat_alm_setting_not_found() { UserDto user = insertUser(); AlmPatDto almPatDto = newAlmPatDto(); db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null); TestRequest request = ws.newRequest() .setParam("almSetting", "testKey"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("DevOps Platform Setting 'testKey' not found"); } @Test public void fail_when_not_logged_in() { TestRequest request = ws.newRequest() .setParam("almSetting", "anyvalue"); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_no_creation_project_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); TestRequest request = ws.newRequest() .setParam("almSetting", "anyvalue"); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } private ProjectDto insertProject(AlmSettingDto almSetting, String repoName, String projectName) { ProjectDto projectDto1 = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertAzureProjectAlmSetting(almSetting, projectDto1, projectAlmSettingDto -> projectAlmSettingDto.setAlmRepo(repoName), projectAlmSettingDto -> projectAlmSettingDto.setAlmSlug(projectName)); return projectDto1; } private void mockClient(GsonAzureRepoList repoList) { when(azureDevOpsHttpClient.getRepos(any(), any(), any())).thenReturn(repoList); } private AlmSettingDto insertAlmSetting() { UserDto user = insertUser(); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); dto.setPersonalAccessToken(almSetting.getDecryptedPersonalAccessToken(encryption)); }); return almSetting; } @NotNull private UserDto insertUser() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); return user; } private GsonAzureRepo getGsonAzureRepo(String projectName, String repoName) { GsonAzureProject project = new GsonAzureProject(projectName, "the best project ever"); return new GsonAzureRepo("repo-id", repoName, "url", project, "repo-default-branch"); } }
14,645
38.583784
141
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/bitbucketcloud/ImportBitbucketCloudRepoActionIT.java
/* * 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.almintegration.ws.bitbucketcloud; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient; import org.sonar.alm.client.bitbucket.bitbucketcloud.MainBranch; import org.sonar.alm.client.bitbucket.bitbucketcloud.Project; import org.sonar.alm.client.bitbucket.bitbucketcloud.Repository; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.core.platform.EditionProvider; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.component.BranchDto; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.almintegration.ws.ImportHelper; import org.sonar.server.almintegration.ws.ProjectKeyGenerator; import org.sonar.server.component.ComponentUpdater; import org.sonar.server.es.TestIndexers; 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.favorite.FavoriteUpdater; import org.sonar.server.l18n.I18nRule; import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver; import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.project.DefaultBranchNameResolver; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.project.Visibility; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Projects; import static java.util.Objects.requireNonNull; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto; import static org.sonar.db.newcodeperiod.NewCodePeriodType.NUMBER_OF_DAYS; import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.db.permission.GlobalPermission.SCAN; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE; public class ImportBitbucketCloudRepoActionIT { private static final String GENERATED_PROJECT_KEY = "TEST_PROJECT_KEY"; @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); @Rule public final I18nRule i18n = new I18nRule(); private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class); private final BitbucketCloudRestClient bitbucketCloudRestClient = mock(BitbucketCloudRestClient.class); DefaultBranchNameResolver defaultBranchNameResolver = mock(DefaultBranchNameResolver.class); private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), i18n, System2.INSTANCE, mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestIndexers(), new SequenceUuidFactory(), defaultBranchNameResolver, true); private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession); private final ProjectKeyGenerator projectKeyGenerator = mock(ProjectKeyGenerator.class); private PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class); private NewCodeDefinitionResolver newCodeDefinitionResolver = new NewCodeDefinitionResolver(db.getDbClient(), editionProvider); private final WsActionTester ws = new WsActionTester(new ImportBitbucketCloudRepoAction(db.getDbClient(), userSession, bitbucketCloudRestClient, projectDefaultVisibility, componentUpdater, importHelper, projectKeyGenerator, newCodeDefinitionResolver, defaultBranchNameResolver)); @Before public void before() { when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE); when(projectKeyGenerator.generateUniqueProjectKey(any(), any())).thenReturn(GENERATED_PROJECT_KEY); } @Test public void import_project() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Repository repo = getGsonBBCRepo(); when(bitbucketCloudRestClient.getRepo(any(), any(), any())).thenReturn(repo); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("repositorySlug", "repo-slug-1") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY); assertThat(result.getName()).isEqualTo(repo.getName()); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); Optional<ProjectAlmSettingDto> projectAlmSettingDto = db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get()); assertThat(projectAlmSettingDto).isPresent(); assertThat(projectAlmSettingDto.get().getAlmRepo()).isEqualTo("repo-slug-1"); Optional<BranchDto> branchDto = db.getDbClient().branchDao().selectByBranchKey(db.getSession(), projectDto.get().getUuid(), "develop"); assertThat(branchDto).isPresent(); assertThat(branchDto.get().isMain()).isTrue(); verify(projectKeyGenerator).generateUniqueProjectKey(requireNonNull(almSetting.getAppId()), repo.getSlug()); assertThat(db.getDbClient().newCodePeriodDao().selectAll(db.getSession())) .isEmpty(); } @Test public void import_project_with_NCD_developer_edition() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Repository repo = getGsonBBCRepo(); when(bitbucketCloudRestClient.getRepo(any(), any(), any())).thenReturn(repo); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("repositorySlug", "repo-slug-1") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS") .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY); assertThat(result.getName()).isEqualTo(repo.getName()); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid) .containsExactly(NUMBER_OF_DAYS, "30", null); } @Test public void import_project_with_NCD_community_edition() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Repository repo = getGsonBBCRepo(); when(bitbucketCloudRestClient.getRepo(any(), any(), any())).thenReturn(repo); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("repositorySlug", "repo-slug-1") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS") .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY); assertThat(result.getName()).isEqualTo(repo.getName()); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); String projectUuid = projectDto.get().getUuid(); assertThat(db.getDbClient().newCodePeriodDao().selectByBranch(db.getSession(), projectUuid, projectUuid)) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid) .containsExactly(NUMBER_OF_DAYS, "30", projectUuid); } @Test public void import_project_reference_branch_ncd_no_default_branch_name() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn("default-branch"); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Repository repo = getGsonBBCRepoWithNoMainBranchName(); when(bitbucketCloudRestClient.getRepo(any(), any(), any())).thenReturn(repo); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("repositorySlug", "repo-slug-1") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "REFERENCE_BRANCH") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY); assertThat(result.getName()).isEqualTo(repo.getName()); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue) .containsExactly(REFERENCE_BRANCH, "default-branch"); } @Test public void import_project_reference_branch_NCD() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Repository repo = getGsonBBCRepo(); when(bitbucketCloudRestClient.getRepo(any(), any(), any())).thenReturn(repo); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("repositorySlug", "repo-slug-1") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "REFERENCE_BRANCH") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY); assertThat(result.getName()).isEqualTo(repo.getName()); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue) .containsExactly(REFERENCE_BRANCH, "develop"); } @Test public void import_project_throw_IAE_when_newCodeDefinitionValue_provided_and_no_newCodeDefinitionType() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Repository repo = getGsonBBCRepo(); when(bitbucketCloudRestClient.getRepo(any(), any(), any())).thenReturn(repo); TestRequest request = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("repositorySlug", "repo-slug-1") .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30"); assertThatThrownBy(() -> request.executeProtobuf(Projects.CreateWsResponse.class)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("New code definition type is required when new code definition value is provided"); } @Test public void fail_project_already_exist() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Repository repo = getGsonBBCRepo(); db.components().insertPublicProject(p -> p.setKey(GENERATED_PROJECT_KEY)).getMainBranchComponent(); when(bitbucketCloudRestClient.getRepo(any(), any(), any())).thenReturn(repo); TestRequest request = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("repositorySlug", "repo-slug-1"); assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Could not create Project with key: \"%s\". A similar key already exists: \"%s\"", GENERATED_PROJECT_KEY, GENERATED_PROJECT_KEY); } @Test public void fail_when_not_logged_in() { TestRequest request = ws.newRequest() .setParam("almSetting", "sdgfdshfjztutz") .setParam("projectKey", "projectKey") .setParam("repositorySlug", "repo-slug"); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_missing_project_creator_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(SCAN); TestRequest request = ws.newRequest() .setParam("almSetting", "sdgfdshfjztutz") .setParam("projectKey", "projectKey") .setParam("repositorySlug", "repo-slug"); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } @Test public void check_pat_is_missing() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); TestRequest request = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("repositorySlug", "repo"); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Username and App Password for '" + almSetting.getKey() + "' is missing"); } @Test public void fail_check_alm_setting_not_found() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmPatDto almPatDto = newAlmPatDto(); db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null); TestRequest request = ws.newRequest() .setParam("almSetting", "testKey") .setParam("repositorySlug", "repo"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessageContaining("DevOps Platform Setting 'testKey' not found"); } @Test public void fail_when_no_creation_project_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); TestRequest request = ws.newRequest() .setParam("almSetting", "anyvalue"); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("9.0"); assertThat(def.isPost()).isTrue(); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("almSetting", true), tuple("repositorySlug", true), tuple(PARAM_NEW_CODE_DEFINITION_TYPE, false), tuple(PARAM_NEW_CODE_DEFINITION_VALUE, false)); } private Repository getGsonBBCRepo() { Project project1 = new Project("PROJECT-UUID-ONE", "projectKey1", "projectName1"); MainBranch mainBranch = new MainBranch("branch", "develop"); return new Repository("REPO-UUID-ONE", "repo-slug-1", "repoName1", project1, mainBranch); } private Repository getGsonBBCRepoWithNoMainBranchName() { Project project1 = new Project("PROJECT-UUID-ONE", "projectKey1", "projectName1"); MainBranch mainBranch = new MainBranch("branch", null); return new Repository("REPO-UUID-ONE", "repo-slug-1", "repoName1", project1, mainBranch); } }
19,260
43.793023
164
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/bitbucketcloud/SearchBitbucketCloudReposActionIT.java
/* * 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.almintegration.ws.bitbucketcloud; import org.jetbrains.annotations.NotNull; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient; import org.sonar.alm.client.bitbucket.bitbucketcloud.Project; import org.sonar.alm.client.bitbucket.bitbucketcloud.Repository; import org.sonar.alm.client.bitbucket.bitbucketcloud.RepositoryList; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.project.ProjectDto; 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.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.AlmIntegrations.BBCRepo; import org.sonarqube.ws.AlmIntegrations.SearchBitbucketcloudReposWsResponse; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; public class SearchBitbucketCloudReposActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final BitbucketCloudRestClient bitbucketCloudRestClient = mock(BitbucketCloudRestClient.class); private final WsActionTester ws = new WsActionTester( new SearchBitbucketCloudReposAction(db.getDbClient(), userSession, bitbucketCloudRestClient)); @Test public void list_repos() { when(bitbucketCloudRestClient.searchRepos(any(), any(), any(), any(), any())).thenReturn(getRepositoryList()); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setPersonalAccessToken("abc:xyz"); dto.setUserUuid(user.getUuid()); }); ProjectDto projectDto = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertBitbucketCloudProjectAlmSetting(almSetting, projectDto, s -> s.setAlmRepo("repo-slug-2")); SearchBitbucketcloudReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("p", "1") .setParam("ps", "100") .executeProtobuf(SearchBitbucketcloudReposWsResponse.class); assertThat(response.getIsLastPage()).isFalse(); assertThat(response.getPaging().getPageIndex()).isOne(); assertThat(response.getPaging().getPageSize()).isEqualTo(100); assertThat(response.getRepositoriesList()) .extracting(BBCRepo::getUuid, BBCRepo::getName, BBCRepo::getSlug, BBCRepo::getProjectKey, BBCRepo::getSqProjectKey, BBCRepo::getWorkspace) .containsExactlyInAnyOrder( tuple("REPO-UUID-ONE", "repoName1", "repo-slug-1", "projectKey1", "", almSetting.getAppId()), tuple("REPO-UUID-TWO", "repoName2", "repo-slug-2", "projectKey2", projectDto.getKey(), almSetting.getAppId())); } @Test public void use_projectKey_to_disambiguate_when_multiple_projects_are_binded_on_one_bitbucket_repo() { when(bitbucketCloudRestClient.searchRepos(any(), any(), any(), any(), any())).thenReturn(getRepositoryList()); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); ProjectDto project1 = db.components().insertPrivateProject(p -> p.setKey("B")).getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject(p -> p.setKey("A")).getProjectDto(); db.almSettings().insertBitbucketProjectAlmSetting(almSetting, project1, s -> s.setAlmRepo("repo-slug-2")); db.almSettings().insertBitbucketProjectAlmSetting(almSetting, project2, s -> s.setAlmRepo("repo-slug-2")); SearchBitbucketcloudReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchBitbucketcloudReposWsResponse.class); assertThat(response.getRepositoriesList()) .extracting(BBCRepo::getUuid, BBCRepo::getName, BBCRepo::getSlug, BBCRepo::getProjectKey, BBCRepo::getSqProjectKey) .containsExactlyInAnyOrder( tuple("REPO-UUID-ONE", "repoName1", "repo-slug-1", "projectKey1", ""), tuple("REPO-UUID-TWO", "repoName2", "repo-slug-2", "projectKey2", "A")); } @Test public void return_empty_list_when_no_bbs_repo() { RepositoryList repositoryList = new RepositoryList(null, emptyList(), 1, 100); when(bitbucketCloudRestClient.searchRepos(any(), any(), any(), any(), any())).thenReturn(repositoryList); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setPersonalAccessToken("abc:xyz"); dto.setUserUuid(user.getUuid()); }); ProjectDto projectDto = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertBitbucketCloudProjectAlmSetting(almSetting, projectDto, s -> s.setAlmRepo("repo-slug-2")); SearchBitbucketcloudReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchBitbucketcloudReposWsResponse.class); assertThat(response.getIsLastPage()).isTrue(); assertThat(response.getRepositoriesList()).isEmpty(); } @Test public void fail_check_pat_alm_setting_not_found() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmPatDto almPatDto = newAlmPatDto(); db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null); TestRequest request = ws.newRequest().setParam("almSetting", "testKey"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessageContaining("DevOps Platform Setting 'testKey' not found"); } @Test public void fail_when_not_logged_in() { TestRequest request = ws.newRequest().setParam("almSetting", "anyvalue"); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_no_creation_project_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); TestRequest request = ws.newRequest().setParam("almSetting", "anyvalue"); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("9.0"); assertThat(def.isPost()).isFalse(); assertThat(def.responseExampleFormat()).isEqualTo("json"); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("almSetting", true), tuple("repositoryName", false), tuple(PAGE, false), tuple(PAGE_SIZE, false)); } @NotNull private RepositoryList getRepositoryList() { return new RepositoryList( "http://next.url", asList(getBBCRepo1(), getBBCRepo2()), 1, 100); } private Repository getBBCRepo1() { Project project1 = new Project("PROJECT-UUID-ONE", "projectKey1", "projectName1"); return new Repository("REPO-UUID-ONE", "repo-slug-1", "repoName1", project1, null); } private Repository getBBCRepo2() { Project project2 = new Project("PROJECT-UUID-TWO", "projectKey2", "projectName2"); return new Repository("REPO-UUID-TWO", "repo-slug-2", "repoName2", project2, null); } }
9,542
42.976959
144
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/bitbucketserver/ImportBitbucketServerProjectActionIT.java
/* * 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.almintegration.ws.bitbucketserver; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient; import org.sonar.alm.client.bitbucketserver.Branch; import org.sonar.alm.client.bitbucketserver.BranchesList; import org.sonar.alm.client.bitbucketserver.Project; import org.sonar.alm.client.bitbucketserver.Repository; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.core.platform.EditionProvider; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.component.BranchDto; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.almintegration.ws.ImportHelper; import org.sonar.server.almintegration.ws.ProjectKeyGenerator; import org.sonar.server.component.ComponentUpdater; import org.sonar.server.es.TestIndexers; 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.favorite.FavoriteUpdater; import org.sonar.server.l18n.I18nRule; import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver; import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.project.DefaultBranchNameResolver; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.project.Visibility; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Projects; import static java.util.Objects.requireNonNull; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.apache.commons.lang.math.JVMRandom.nextLong; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; import static org.sonar.db.newcodeperiod.NewCodePeriodType.NUMBER_OF_DAYS; import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.db.permission.GlobalPermission.SCAN; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE; public class ImportBitbucketServerProjectActionIT { private static final String GENERATED_PROJECT_KEY = "TEST_PROJECT_KEY"; @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); @Rule public final I18nRule i18n = new I18nRule(); private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class); private final BitbucketServerRestClient bitbucketServerRestClient = mock(BitbucketServerRestClient.class); private final DefaultBranchNameResolver defaultBranchNameResolver = mock(DefaultBranchNameResolver.class); private PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class); private NewCodeDefinitionResolver newCodeDefinitionResolver = new NewCodeDefinitionResolver(db.getDbClient(), editionProvider); private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), i18n, System2.INSTANCE, mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestIndexers(), new SequenceUuidFactory(), defaultBranchNameResolver, true); private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession); private final ProjectKeyGenerator projectKeyGenerator = mock(ProjectKeyGenerator.class); private final WsActionTester ws = new WsActionTester(new ImportBitbucketServerProjectAction(db.getDbClient(), userSession, bitbucketServerRestClient, projectDefaultVisibility, componentUpdater, importHelper, projectKeyGenerator, newCodeDefinitionResolver, defaultBranchNameResolver)); private static BranchesList defaultBranchesList; @BeforeClass public static void beforeAll() { Branch defaultBranch = new Branch("default", true); defaultBranchesList = new BranchesList(Collections.singletonList(defaultBranch)); } @Before public void before() { when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE); when(projectKeyGenerator.generateUniqueProjectKey(any(), any())).thenReturn(GENERATED_PROJECT_KEY); when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn(DEFAULT_MAIN_BRANCH_NAME); } @Test public void import_project() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Project project = getGsonBBSProject(); Repository repo = getGsonBBSRepo(project); when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo); when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(defaultBranchesList); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectKey", "projectKey") .setParam("repositorySlug", "repo-slug") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY); assertThat(result.getName()).isEqualTo(repo.getName()); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent(); verify(projectKeyGenerator).generateUniqueProjectKey(requireNonNull(project.getKey()), repo.getSlug()); } @Test public void import_project_with_NCD_developer_edition_sets_project_NCD() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Project project = getGsonBBSProject(); Repository repo = getGsonBBSRepo(project); when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo); when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(defaultBranchesList); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectKey", "projectKey") .setParam("repositorySlug", "repo-slug") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS") .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY); assertThat(result.getName()).isEqualTo(repo.getName()); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent(); verify(projectKeyGenerator).generateUniqueProjectKey(requireNonNull(project.getKey()), repo.getSlug()); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid) .containsExactly(NUMBER_OF_DAYS, "30", null); } @Test public void import_project_with_NCD_community_edition_sets_branch_NCD() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Project project = getGsonBBSProject(); Repository repo = getGsonBBSRepo(project); when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo); when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(defaultBranchesList); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectKey", "projectKey") .setParam("repositorySlug", "repo-slug") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS") .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); String projectUuid = projectDto.get().getUuid(); assertThat(db.getDbClient().newCodePeriodDao().selectByBranch(db.getSession(), projectUuid, projectUuid)) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid) .containsExactly(NUMBER_OF_DAYS, "30", projectUuid); } @Test public void import_project_reference_branch_ncd_no_default_branch() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn("default-branch"); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Project project = getGsonBBSProject(); Repository repo = getGsonBBSRepo(project); when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo); when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(new BranchesList()); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectKey", "projectKey") .setParam("repositorySlug", "repo-slug") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "REFERENCE_BRANCH") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); String projectUuid = projectDto.get().getUuid(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectUuid)) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue) .containsExactly(REFERENCE_BRANCH, "default-branch"); } @Test public void import_project_reference_branch_ncd() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Project project = getGsonBBSProject(); Repository repo = getGsonBBSRepo(project); when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo); when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(defaultBranchesList); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectKey", "projectKey") .setParam("repositorySlug", "repo-slug") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "REFERENCE_BRANCH") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); String projectUuid = projectDto.get().getUuid(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectUuid)) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue) .containsExactly(REFERENCE_BRANCH, "default"); } @Test public void fail_project_already_exist() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Project project = getGsonBBSProject(); Repository repo = getGsonBBSRepo(project); db.components().insertPublicProject(p -> p.setKey(GENERATED_PROJECT_KEY)).getMainBranchComponent(); assertThatThrownBy(() -> { when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo); when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(defaultBranchesList); ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectKey", "projectKey") .setParam("repositorySlug", "repo-slug") .execute(); }) .isInstanceOf(BadRequestException.class) .hasMessage("Could not create Project with key: \"%s\". A similar key already exists: \"%s\"", GENERATED_PROJECT_KEY, GENERATED_PROJECT_KEY); } @Test public void fail_when_not_logged_in() { assertThatThrownBy(() -> { ws.newRequest() .setParam("almSetting", "sdgfdshfjztutz") .setParam("projectKey", "projectKey") .setParam("repositorySlug", "repo-slug") .execute(); }) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_missing_project_creator_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(SCAN); assertThatThrownBy(() -> { ws.newRequest() .setParam("almSetting", "sdgfdshfjztutz") .setParam("projectKey", "projectKey") .setParam("repositorySlug", "repo-slug") .execute(); }) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void check_pat_is_missing() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); assertThatThrownBy(() -> { ws.newRequest() .setParam("almSetting", almSetting.getKey()) .execute(); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("personal access token for '" + almSetting.getKey() + "' is missing"); } @Test public void fail_check_alm_setting_not_found() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmPatDto almPatDto = newAlmPatDto(); db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null); assertThatThrownBy(() -> { ws.newRequest() .setParam("almSetting", "testKey") .execute(); }) .isInstanceOf(NotFoundException.class) .hasMessage("DevOps Platform Setting 'testKey' not found"); } @Test public void fail_when_no_creation_project_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); assertThatThrownBy(() -> { ws.newRequest() .setParam("almSetting", "anyvalue") .execute(); }) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void handle_givenNoDefaultBranchFound_doNotUpdateDefaultBranchName() { BranchesList branchesList = new BranchesList(); Branch branch = new Branch("not_a_master", false); branchesList.addBranch(branch); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Project project = getGsonBBSProject(); Repository repo = getGsonBBSRepo(project); when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo); when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(branchesList); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectKey", "projectKey") .setParam("repositorySlug", "repo-slug") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); Collection<BranchDto> branchDtos = db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get()); List<BranchDto> collect = branchDtos.stream().filter(BranchDto::isMain).toList(); String mainBranchName = collect.iterator().next().getKey(); assertThat(mainBranchName).isEqualTo(DEFAULT_MAIN_BRANCH_NAME); } @Test public void handle_givenDefaultBranchNamedDefault_updateDefaultBranchNameToDefault() { BranchesList branchesList = new BranchesList(); Branch branch = new Branch("default", true); branchesList.addBranch(branch); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); Project project = getGsonBBSProject(); Repository repo = getGsonBBSRepo(project); when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo); when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(branchesList); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("projectKey", "projectKey") .setParam("repositorySlug", "repo-slug") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); Collection<BranchDto> branchDtos = db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get()); List<BranchDto> collect = branchDtos.stream().filter(BranchDto::isMain).toList(); String mainBranchName = collect.iterator().next().getKey(); assertThat(mainBranchName).isEqualTo("default"); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.2"); assertThat(def.isPost()).isTrue(); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("almSetting", true), tuple("repositorySlug", true), tuple("projectKey", true), tuple(PARAM_NEW_CODE_DEFINITION_TYPE, false), tuple(PARAM_NEW_CODE_DEFINITION_VALUE, false)); } private Repository getGsonBBSRepo(Project project) { Repository bbsResult = new Repository(); bbsResult.setProject(project); bbsResult.setSlug(randomAlphanumeric(5)); bbsResult.setName(randomAlphanumeric(5)); bbsResult.setId(nextLong(100)); return bbsResult; } private Project getGsonBBSProject() { return new Project() .setKey(randomAlphanumeric(5)) .setId(nextLong(100)) .setName(randomAlphanumeric(5)); } }
22,536
43.277014
165
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/bitbucketserver/ListBitbucketServerProjectsActionIT.java
/* * 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.almintegration.ws.bitbucketserver; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient; import org.sonar.alm.client.bitbucketserver.Project; import org.sonar.alm.client.bitbucketserver.ProjectList; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; 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.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.AlmIntegrations; import org.sonarqube.ws.AlmIntegrations.ListBitbucketserverProjectsWsResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; public class ListBitbucketServerProjectsActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final BitbucketServerRestClient bitbucketServerRestClient = mock(BitbucketServerRestClient.class); private final WsActionTester ws = new WsActionTester(new ListBitbucketServerProjectsAction(db.getDbClient(), userSession, bitbucketServerRestClient)); @Before public void before() { ProjectList projectList = new ProjectList(); List<Project> values = new ArrayList<>(); Project project = new Project(); project.setId(1); project.setKey("key"); project.setName("name"); values.add(project); projectList.setValues(values); when(bitbucketServerRestClient.getProjects(anyString(), anyString())).thenReturn(projectList); } @Test public void list_projects() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); ListBitbucketserverProjectsWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(ListBitbucketserverProjectsWsResponse.class); assertThat(response.getProjectsCount()).isOne(); assertThat(response.getProjectsList()) .extracting(AlmIntegrations.AlmProject::getKey, AlmIntegrations.AlmProject::getName) .containsExactly(tuple("key", "name")); } @Test public void check_pat_is_missing() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketAlmSetting(); TestRequest request = ws.newRequest() .setParam("almSetting", almSetting.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("No personal access token found"); } @Test public void fail_check_alm_setting_not_found() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmPatDto almPatDto = newAlmPatDto(); db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null); TestRequest request = ws.newRequest() .setParam("almSetting", "testKey"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("DevOps Platform Setting 'testKey' not found"); } @Test public void fail_when_not_logged_in() { TestRequest request = ws.newRequest() .setParam("almSetting", "anyvalue"); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_no_creation_project_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); TestRequest request = ws.newRequest() .setParam("almSetting", "anyvalue"); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.2"); assertThat(def.isPost()).isFalse(); assertThat(def.responseExampleFormat()).isEqualTo("json"); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder(tuple("almSetting", true)); } }
5,930
35.838509
152
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/bitbucketserver/SearchBitbucketServerReposActionIT.java
/* * 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.almintegration.ws.bitbucketserver; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient; import org.sonar.alm.client.bitbucketserver.Project; import org.sonar.alm.client.bitbucketserver.Repository; import org.sonar.alm.client.bitbucketserver.RepositoryList; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDao; import org.sonar.db.project.ProjectDao; import org.sonar.db.project.ProjectDto; 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.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.AlmIntegrations; import org.sonarqube.ws.AlmIntegrations.SearchBitbucketserverReposWsResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; public class SearchBitbucketServerReposActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final BitbucketServerRestClient bitbucketServerRestClient = mock(BitbucketServerRestClient.class); private final ProjectAlmSettingDao projectAlmSettingDao = db.getDbClient().projectAlmSettingDao(); private final ProjectDao projectDao = db.getDbClient().projectDao(); private final WsActionTester ws = new WsActionTester( new SearchBitbucketServerReposAction(db.getDbClient(), userSession, bitbucketServerRestClient, projectAlmSettingDao, projectDao)); @Before public void before() { RepositoryList gsonBBSRepoList = new RepositoryList(); gsonBBSRepoList.setLastPage(true); List<Repository> values = new ArrayList<>(); values.add(getGsonBBSRepo1()); values.add(getGsonBBSRepo2()); gsonBBSRepoList.setValues(values); when(bitbucketServerRestClient.getRepos(any(), any(), any(), any())).thenReturn(gsonBBSRepoList); } @Test public void list_repos() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); ProjectDto projectDto = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertBitbucketProjectAlmSetting(almSetting, projectDto, s -> s.setAlmRepo("projectKey2"), s -> s.setAlmSlug("repo-slug-2")); AlmIntegrations.SearchBitbucketserverReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchBitbucketserverReposWsResponse.class); assertThat(response.getIsLastPage()).isTrue(); assertThat(response.getRepositoriesList()) .extracting(AlmIntegrations.BBSRepo::getId, AlmIntegrations.BBSRepo::getName, AlmIntegrations.BBSRepo::getSlug, AlmIntegrations.BBSRepo::hasSqProjectKey, AlmIntegrations.BBSRepo::getSqProjectKey, AlmIntegrations.BBSRepo::getProjectKey) .containsExactlyInAnyOrder( tuple(1L, "repoName1", "repo-slug-1", false, "", "projectKey1"), tuple(3L, "repoName2", "repo-slug-2", true, projectDto.getKey(), "projectKey2")); } @Test public void return_empty_list_when_no_bbs_repo() { RepositoryList gsonBBSRepoList = new RepositoryList(); gsonBBSRepoList.setLastPage(true); gsonBBSRepoList.setValues(new ArrayList<>()); when(bitbucketServerRestClient.getRepos(any(), any(), any(), any())).thenReturn(gsonBBSRepoList); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); ProjectDto projectDto = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertBitbucketProjectAlmSetting(almSetting, projectDto, s -> s.setAlmRepo("projectKey2"), s -> s.setAlmSlug("repo-slug-2")); AlmIntegrations.SearchBitbucketserverReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchBitbucketserverReposWsResponse.class); assertThat(response.getIsLastPage()).isTrue(); assertThat(response.getRepositoriesList()).isEmpty(); } @Test public void already_imported_detection_does_not_get_confused_by_same_slug_in_different_projects() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); ProjectDto projectDto = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertBitbucketProjectAlmSetting(almSetting, projectDto, s -> s.setAlmRepo("projectKey2"), s -> s.setAlmSlug("repo-slug-2")); db.almSettings().insertBitbucketProjectAlmSetting(almSetting, db.components().insertPrivateProject().getProjectDto(), s -> s.setAlmRepo("projectKey2"), s -> s.setAlmSlug("repo-slug-2")); AlmIntegrations.SearchBitbucketserverReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchBitbucketserverReposWsResponse.class); assertThat(response.getIsLastPage()).isTrue(); assertThat(response.getRepositoriesList()) .extracting(AlmIntegrations.BBSRepo::getId, AlmIntegrations.BBSRepo::getName, AlmIntegrations.BBSRepo::getSlug, AlmIntegrations.BBSRepo::getSqProjectKey, AlmIntegrations.BBSRepo::getProjectKey) .containsExactlyInAnyOrder( tuple(1L, "repoName1", "repo-slug-1", "", "projectKey1"), tuple(3L, "repoName2", "repo-slug-2", projectDto.getKey(), "projectKey2")); } @Test public void use_projectKey_to_disambiguate_when_multiple_projects_are_binded_on_one_bitbucketserver_repo() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); ProjectDto project1 = db.components().insertPrivateProject(p -> p.setKey("B")).getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject(p -> p.setKey("A")).getProjectDto(); db.almSettings().insertBitbucketProjectAlmSetting(almSetting, project1, s -> s.setAlmRepo("projectKey2"), s -> s.setAlmSlug("repo-slug-2")); db.almSettings().insertBitbucketProjectAlmSetting(almSetting, project2, s -> s.setAlmRepo("projectKey2"), s -> s.setAlmSlug("repo-slug-2")); AlmIntegrations.SearchBitbucketserverReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchBitbucketserverReposWsResponse.class); assertThat(response.getIsLastPage()).isTrue(); assertThat(response.getRepositoriesList()) .extracting(AlmIntegrations.BBSRepo::getId, AlmIntegrations.BBSRepo::getName, AlmIntegrations.BBSRepo::getSlug, AlmIntegrations.BBSRepo::getSqProjectKey, AlmIntegrations.BBSRepo::getProjectKey) .containsExactlyInAnyOrder( tuple(1L, "repoName1", "repo-slug-1", "", "projectKey1"), tuple(3L, "repoName2", "repo-slug-2", "A", "projectKey2")); } @Test public void check_pat_is_missing() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); assertThatThrownBy(() -> { ws.newRequest() .setParam("almSetting", almSetting.getKey()) .execute(); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("No personal access token found"); } @Test public void fail_check_pat_alm_setting_not_found() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmPatDto almPatDto = newAlmPatDto(); db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null); assertThatThrownBy(() -> { ws.newRequest() .setParam("almSetting", "testKey") .execute(); }) .isInstanceOf(NotFoundException.class) .hasMessage("DevOps Platform Setting 'testKey' not found"); } @Test public void fail_when_not_logged_in() { assertThatThrownBy(() -> { ws.newRequest() .setParam("almSetting", "anyvalue") .execute(); }) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_no_creation_project_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); assertThatThrownBy(() -> { ws.newRequest() .setParam("almSetting", "anyvalue") .execute(); }) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.2"); assertThat(def.isPost()).isFalse(); assertThat(def.responseExampleFormat()).isEqualTo("json"); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("almSetting", true), tuple("projectName", false), tuple("repositoryName", false)); } private Repository getGsonBBSRepo1() { Repository gsonBBSRepo1 = new Repository(); gsonBBSRepo1.setId(1L); gsonBBSRepo1.setName("repoName1"); Project project1 = new Project(); project1.setName("projectName1"); project1.setKey("projectKey1"); project1.setId(2L); gsonBBSRepo1.setProject(project1); gsonBBSRepo1.setSlug("repo-slug-1"); return gsonBBSRepo1; } private Repository getGsonBBSRepo2() { Repository gsonBBSRepo = new Repository(); gsonBBSRepo.setId(3L); gsonBBSRepo.setName("repoName2"); Project project = new Project(); project.setName("projectName2"); project.setKey("projectKey2"); project.setId(4L); gsonBBSRepo.setProject(project); gsonBBSRepo.setSlug("repo-slug-2"); return gsonBBSRepo; } }
12,033
42.132616
190
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/github/GetGithubClientIdActionIT.java
/* * 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.almintegration.ws.github; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.AlmIntegrations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.sonar.server.tester.UserSessionRule.standalone; public class GetGithubClientIdActionIT { @Rule public UserSessionRule userSession = standalone(); private final System2 system2 = mock(System2.class); @Rule public DbTester db = DbTester.create(system2); private final WsActionTester ws = new WsActionTester(new GetGithubClientIdAction(db.getDbClient(), userSession)); @Test public void get_client_id() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS); AlmSettingDto githubAlmSetting = db.almSettings().insertGitHubAlmSetting(alm -> alm.setClientId("client_123").setClientSecret("client_secret_123")); AlmIntegrations.GithubClientIdWsResponse response = ws.newRequest().setParam(GetGithubClientIdAction.PARAM_ALM_SETTING, githubAlmSetting.getKey()) .executeProtobuf(AlmIntegrations.GithubClientIdWsResponse.class); assertThat(response.getClientId()).isEqualTo(githubAlmSetting.getClientId()); } @Test public void fail_when_missing_create_project_permission() { TestRequest request = ws.newRequest(); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_almSetting_does_not_exist() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS); TestRequest request = ws.newRequest().setParam(GetGithubClientIdAction.PARAM_ALM_SETTING, "unknown"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("Github Setting 'unknown' not found"); } @Test public void fail_when_client_id_does_not_exist() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS); AlmSettingDto githubAlmSetting = db.almSettings().insertGitHubAlmSetting(s -> s.setClientId(null)); TestRequest request = ws.newRequest() .setParam(GetGithubClientIdAction.PARAM_ALM_SETTING, githubAlmSetting.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("No client ID for setting with key '%s'", githubAlmSetting.getKey()); } }
3,868
39.302083
152
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/github/ImportGithubProjectActionIT.java
/* * 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.almintegration.ws.github; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.github.GithubApplicationClient; import org.sonar.alm.client.github.GithubApplicationClientImpl; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.core.i18n.I18n; import org.sonar.core.platform.EditionProvider; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbTester; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.component.BranchDto; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.almintegration.ws.ImportHelper; import org.sonar.server.almintegration.ws.ProjectKeyGenerator; import org.sonar.server.component.ComponentUpdater; import org.sonar.server.es.TestIndexers; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.favorite.FavoriteUpdater; import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver; import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.project.DefaultBranchNameResolver; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.project.Visibility; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Projects; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; import static org.sonar.db.newcodeperiod.NewCodePeriodType.NUMBER_OF_DAYS; import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH; import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING; import static org.sonar.server.almintegration.ws.github.ImportGithubProjectAction.PARAM_ORGANIZATION; import static org.sonar.server.almintegration.ws.github.ImportGithubProjectAction.PARAM_REPOSITORY_KEY; import static org.sonar.server.tester.UserSessionRule.standalone; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE; public class ImportGithubProjectActionIT { private static final String PROJECT_KEY_NAME = "PROJECT_NAME"; @Rule public UserSessionRule userSession = standalone(); private final System2 system2 = mock(System2.class); private final GithubApplicationClientImpl appClient = mock(GithubApplicationClientImpl.class); private final DefaultBranchNameResolver defaultBranchNameResolver = mock(DefaultBranchNameResolver.class); @Rule public DbTester db = DbTester.create(system2); private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), mock(I18n.class), System2.INSTANCE, mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestIndexers(), new SequenceUuidFactory(), defaultBranchNameResolver, true); private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession); private final ProjectKeyGenerator projectKeyGenerator = mock(ProjectKeyGenerator.class); private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class); private PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class); private NewCodeDefinitionResolver newCodeDefinitionResolver = new NewCodeDefinitionResolver(db.getDbClient(), editionProvider); private final WsActionTester ws = new WsActionTester(new ImportGithubProjectAction(db.getDbClient(), userSession, projectDefaultVisibility, appClient, componentUpdater, importHelper, projectKeyGenerator, newCodeDefinitionResolver, defaultBranchNameResolver)); @Before public void before() { when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE); when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn(DEFAULT_MAIN_BRANCH_NAME); } @Test public void importProject_ifProjectWithSameNameDoesNotExist_importSucceed() { AlmSettingDto githubAlmSetting = setupAlm(); db.almPats().insert(p -> p.setAlmSettingUuid(githubAlmSetting.getUuid()).setUserUuid(userSession.getUuid())); GithubApplicationClient.Repository repository = new GithubApplicationClient.Repository(1L, PROJECT_KEY_NAME, false, "octocat/" + PROJECT_KEY_NAME, "https://github.sonarsource.com/api/v3/repos/octocat/" + PROJECT_KEY_NAME, "default-branch"); when(appClient.getRepository(any(), any(), any(), any())).thenReturn(Optional.of(repository)); when(projectKeyGenerator.generateUniqueProjectKey(repository.getFullName())).thenReturn(PROJECT_KEY_NAME); Projects.CreateWsResponse response = ws.newRequest() .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey()) .setParam(PARAM_ORGANIZATION, "octocat") .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME) .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME); assertThat(result.getName()).isEqualTo(repository.getName()); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent(); Optional<BranchDto> mainBranch = db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get()).stream().filter(BranchDto::isMain).findAny(); assertThat(mainBranch).isPresent(); assertThat(mainBranch.get().getKey()).isEqualTo("default-branch"); } @Test public void importProject_withNCD_developer_edition() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); AlmSettingDto githubAlmSetting = setupAlm(); db.almPats().insert(p -> p.setAlmSettingUuid(githubAlmSetting.getUuid()).setUserUuid(userSession.getUuid())); GithubApplicationClient.Repository repository = new GithubApplicationClient.Repository(1L, PROJECT_KEY_NAME, false, "octocat/" + PROJECT_KEY_NAME, "https://github.sonarsource.com/api/v3/repos/octocat/" + PROJECT_KEY_NAME, "default-branch"); when(appClient.getRepository(any(), any(), any(), any())).thenReturn(Optional.of(repository)); when(projectKeyGenerator.generateUniqueProjectKey(repository.getFullName())).thenReturn(PROJECT_KEY_NAME); Projects.CreateWsResponse response = ws.newRequest() .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey()) .setParam(PARAM_ORGANIZATION, "octocat") .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME) .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS") .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid) .containsExactly(NUMBER_OF_DAYS, "30", null); } @Test public void importProject_withNCD_community_edition() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); AlmSettingDto githubAlmSetting = setupAlm(); db.almPats().insert(p -> p.setAlmSettingUuid(githubAlmSetting.getUuid()).setUserUuid(userSession.getUuid())); GithubApplicationClient.Repository repository = new GithubApplicationClient.Repository(1L, PROJECT_KEY_NAME, false, "octocat/" + PROJECT_KEY_NAME, "https://github.sonarsource.com/api/v3/repos/octocat/" + PROJECT_KEY_NAME, "default-branch"); when(appClient.getRepository(any(), any(), any(), any())).thenReturn(Optional.of(repository)); when(projectKeyGenerator.generateUniqueProjectKey(repository.getFullName())).thenReturn(PROJECT_KEY_NAME); Projects.CreateWsResponse response = ws.newRequest() .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey()) .setParam(PARAM_ORGANIZATION, "octocat") .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME) .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS") .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); String projectUuid = projectDto.get().getUuid(); assertThat(db.getDbClient().newCodePeriodDao().selectByBranch(db.getSession(), projectUuid, projectUuid)) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid) .containsExactly(NUMBER_OF_DAYS, "30", projectUuid); } @Test public void importProject_reference_branch_ncd_no_default_branch() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn("default-branch"); AlmSettingDto githubAlmSetting = setupAlm(); db.almPats().insert(p -> p.setAlmSettingUuid(githubAlmSetting.getUuid()).setUserUuid(userSession.getUuid())); GithubApplicationClient.Repository repository = new GithubApplicationClient.Repository(1L, PROJECT_KEY_NAME, false, "octocat/" + PROJECT_KEY_NAME, "https://github.sonarsource.com/api/v3/repos/octocat/" + PROJECT_KEY_NAME, null); when(appClient.getRepository(any(), any(), any(), any())).thenReturn(Optional.of(repository)); when(projectKeyGenerator.generateUniqueProjectKey(repository.getFullName())).thenReturn(PROJECT_KEY_NAME); Projects.CreateWsResponse response = ws.newRequest() .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey()) .setParam(PARAM_ORGANIZATION, "octocat") .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME) .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "reference_branch") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue) .containsExactly(REFERENCE_BRANCH, "default-branch"); } @Test public void importProject_reference_branch_ncd() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); AlmSettingDto githubAlmSetting = setupAlm(); db.almPats().insert(p -> p.setAlmSettingUuid(githubAlmSetting.getUuid()).setUserUuid(userSession.getUuid())); GithubApplicationClient.Repository repository = new GithubApplicationClient.Repository(1L, PROJECT_KEY_NAME, false, "octocat/" + PROJECT_KEY_NAME, "https://github.sonarsource.com/api/v3/repos/octocat/" + PROJECT_KEY_NAME, "mainBranch"); when(appClient.getRepository(any(), any(), any(), any())).thenReturn(Optional.of(repository)); when(projectKeyGenerator.generateUniqueProjectKey(repository.getFullName())).thenReturn(PROJECT_KEY_NAME); Projects.CreateWsResponse response = ws.newRequest() .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey()) .setParam(PARAM_ORGANIZATION, "octocat") .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME) .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "reference_branch") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue) .containsExactly(REFERENCE_BRANCH, "mainBranch"); } @Test public void importProject_ifProjectWithSameNameAlreadyExists_importSucceed() { AlmSettingDto githubAlmSetting = setupAlm(); db.almPats().insert(p -> p.setAlmSettingUuid(githubAlmSetting.getUuid()).setUserUuid(userSession.getUuid())); db.components().insertPublicProject(p -> p.setKey("Hello-World")).getMainBranchComponent(); GithubApplicationClient.Repository repository = new GithubApplicationClient.Repository(1L, "Hello-World", false, "Hello-World", "https://github.sonarsource.com/api/v3/repos/octocat/Hello-World", "main"); when(appClient.getRepository(any(), any(), any(), any())).thenReturn(Optional.of(repository)); when(projectKeyGenerator.generateUniqueProjectKey(repository.getFullName())).thenReturn(PROJECT_KEY_NAME); Projects.CreateWsResponse response = ws.newRequest() .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey()) .setParam(PARAM_ORGANIZATION, "octocat") .setParam(PARAM_REPOSITORY_KEY, "Hello-World") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME); assertThat(result.getName()).isEqualTo(repository.getName()); } @Test public void fail_when_not_logged_in() { TestRequest request = ws.newRequest() .setParam(PARAM_ALM_SETTING, "asdfghjkl") .setParam(PARAM_ORGANIZATION, "test") .setParam(PARAM_REPOSITORY_KEY, "test/repo"); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_missing_create_project_permission() { TestRequest request = ws.newRequest(); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_almSetting_does_not_exist() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS); TestRequest request = ws.newRequest() .setParam(PARAM_ALM_SETTING, "unknown") .setParam(PARAM_ORGANIZATION, "test") .setParam(PARAM_REPOSITORY_KEY, "test/repo"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("DevOps Platform Setting 'unknown' not found"); } @Test public void fail_when_personal_access_token_doesnt_exist() { AlmSettingDto githubAlmSetting = setupAlm(); TestRequest request = ws.newRequest() .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey()) .setParam(PARAM_ORGANIZATION, "test") .setParam(PARAM_REPOSITORY_KEY, "test/repo"); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("No personal access token found"); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.4"); assertThat(def.isPost()).isTrue(); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple(PARAM_ALM_SETTING, true), tuple(PARAM_ORGANIZATION, true), tuple(PARAM_REPOSITORY_KEY, true), tuple(PARAM_NEW_CODE_DEFINITION_TYPE, false), tuple(PARAM_NEW_CODE_DEFINITION_VALUE, false)); } private AlmSettingDto setupAlm() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS); return db.almSettings().insertGitHubAlmSetting(alm -> alm.setClientId("client_123").setClientSecret("client_secret_123")); } }
17,752
48.313889
131
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/github/ListGithubOrganizationsActionIT.java
/* * 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.almintegration.ws.github; import java.util.stream.Stream; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; import org.sonar.alm.client.github.GithubApplicationClient; import org.sonar.alm.client.github.GithubApplicationClientImpl; import org.sonar.alm.client.github.security.UserAccessToken; import org.sonar.api.config.internal.Encryption; import org.sonar.api.config.internal.Settings; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.AlmIntegrations.GithubOrganization; import org.sonarqube.ws.AlmIntegrations.ListGithubOrganizationsWsResponse; import org.sonarqube.ws.Common; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.server.almintegration.ws.github.ListGithubOrganizationsAction.PARAM_ALM_SETTING; import static org.sonar.server.almintegration.ws.github.ListGithubOrganizationsAction.PARAM_TOKEN; import static org.sonar.server.tester.UserSessionRule.standalone; public class ListGithubOrganizationsActionIT { private static final Encryption encryption = mock(Encryption.class); private static final Settings settings = mock(Settings.class); @Rule public UserSessionRule userSession = standalone(); private final System2 system2 = mock(System2.class); private final GithubApplicationClientImpl appClient = mock(GithubApplicationClientImpl.class); @Rule public DbTester db = DbTester.create(system2); private final WsActionTester ws = new WsActionTester(new ListGithubOrganizationsAction(db.getDbClient(), settings, userSession, appClient)); @BeforeClass public static void setUp() { when(settings.getEncryption()).thenReturn(encryption); } @Test public void fail_when_missing_create_project_permission() { TestRequest request = ws.newRequest(); assertThatThrownBy(request::execute).isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_almSetting_does_not_exist() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS); TestRequest request = ws.newRequest().setParam(PARAM_ALM_SETTING, "unknown"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("GitHub Setting 'unknown' not found"); } @Test public void fail_when_unable_to_create_personal_access_token() { AlmSettingDto githubAlmSetting = setupAlm(); when(appClient.createUserAccessToken(githubAlmSetting.getUrl(), githubAlmSetting.getClientId(), githubAlmSetting.getDecryptedClientSecret(encryption), "abc")) .thenThrow(IllegalStateException.class); TestRequest request = ws.newRequest() .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey()) .setParam(PARAM_TOKEN, "abc"); assertThatThrownBy(request::execute) .isInstanceOf(IllegalStateException.class) .hasMessage(null); } @Test public void fail_create_personal_access_token_because_of_invalid_settings() { AlmSettingDto githubAlmSetting = setupAlm(); when(appClient.createUserAccessToken(githubAlmSetting.getUrl(), githubAlmSetting.getClientId(), githubAlmSetting.getDecryptedClientSecret(encryption), "abc")) .thenThrow(IllegalArgumentException.class); TestRequest request = ws.newRequest() .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey()) .setParam(PARAM_TOKEN, "abc"); assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Unable to authenticate with GitHub. Check the GitHub App client ID and client secret configured in the Global Settings and try again."); } @Test public void fail_when_personal_access_token_doesnt_exist() { AlmSettingDto githubAlmSetting = setupAlm(); TestRequest request = ws.newRequest().setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("No personal access token found"); } @Test public void return_organizations_and_store_personal_access_token() { UserAccessToken accessToken = new UserAccessToken("token_for_abc"); AlmSettingDto githubAlmSettings = setupAlm(); when(encryption.isEncrypted(any())).thenReturn(false); when(appClient.createUserAccessToken(githubAlmSettings.getUrl(), githubAlmSettings.getClientId(), githubAlmSettings.getDecryptedClientSecret(encryption), "abc")) .thenReturn(accessToken); setupGhOrganizations(githubAlmSettings, accessToken.getValue()); ListGithubOrganizationsWsResponse response = ws.newRequest() .setParam(PARAM_ALM_SETTING, githubAlmSettings.getKey()) .setParam(PARAM_TOKEN, "abc") .executeProtobuf(ListGithubOrganizationsWsResponse.class); assertThat(response.getPaging()) .extracting(Common.Paging::getPageIndex, Common.Paging::getPageSize, Common.Paging::getTotal) .containsOnly(1, 100, 2); assertThat(response.getOrganizationsList()) .extracting(GithubOrganization::getKey, GithubOrganization::getName) .containsOnly(tuple("github", "github"), tuple("octacat", "octacat")); verify(appClient).createUserAccessToken(githubAlmSettings.getUrl(), githubAlmSettings.getClientId(), githubAlmSettings.getDecryptedClientSecret(encryption), "abc"); verify(appClient).listOrganizations(githubAlmSettings.getUrl(), accessToken, 1, 100); Mockito.verifyNoMoreInteractions(appClient); assertThat(db.getDbClient().almPatDao().selectByUserAndAlmSetting(db.getSession(), userSession.getUuid(), githubAlmSettings).get().getPersonalAccessToken()) .isEqualTo(accessToken.getValue()); } @Test public void return_organizations_and_store_personal_access_token_with_encrypted_client_secret() { String decryptedSecret = "decrypted-secret"; UserAccessToken accessToken = new UserAccessToken("token_for_abc"); AlmSettingDto githubAlmSettings = setupAlm(); when(encryption.isEncrypted(any())).thenReturn(true); when(encryption.decrypt(any())).thenReturn(decryptedSecret); when(appClient.createUserAccessToken(githubAlmSettings.getUrl(), githubAlmSettings.getClientId(), decryptedSecret, "abc")) .thenReturn(accessToken); setupGhOrganizations(githubAlmSettings, accessToken.getValue()); ListGithubOrganizationsWsResponse response = ws.newRequest() .setParam(PARAM_ALM_SETTING, githubAlmSettings.getKey()) .setParam(PARAM_TOKEN, "abc") .executeProtobuf(ListGithubOrganizationsWsResponse.class); assertThat(response.getPaging()) .extracting(Common.Paging::getPageIndex, Common.Paging::getPageSize, Common.Paging::getTotal) .containsOnly(1, 100, 2); assertThat(response.getOrganizationsList()) .extracting(GithubOrganization::getKey, GithubOrganization::getName) .containsOnly(tuple("github", "github"), tuple("octacat", "octacat")); verify(appClient).createUserAccessToken(githubAlmSettings.getUrl(), githubAlmSettings.getClientId(), decryptedSecret, "abc"); verify(appClient).listOrganizations(githubAlmSettings.getUrl(), accessToken, 1, 100); Mockito.verifyNoMoreInteractions(appClient); assertThat(db.getDbClient().almPatDao().selectByUserAndAlmSetting(db.getSession(), userSession.getUuid(), githubAlmSettings).get().getPersonalAccessToken()) .isEqualTo(accessToken.getValue()); } @Test public void return_organizations_overriding_existing_personal_access_token() { AlmSettingDto githubAlmSettings = setupAlm(); // old pat AlmPatDto pat = db.almPats().insert(p -> p.setAlmSettingUuid(githubAlmSettings.getUuid()).setUserUuid(userSession.getUuid())); // new pat UserAccessToken accessToken = new UserAccessToken("token_for_abc"); when(appClient.createUserAccessToken(githubAlmSettings.getUrl(), githubAlmSettings.getClientId(), githubAlmSettings.getDecryptedClientSecret(encryption), "abc")) .thenReturn(accessToken); setupGhOrganizations(githubAlmSettings, accessToken.getValue()); ListGithubOrganizationsWsResponse response = ws.newRequest() .setParam(PARAM_ALM_SETTING, githubAlmSettings.getKey()) .setParam(PARAM_TOKEN, "abc") .executeProtobuf(ListGithubOrganizationsWsResponse.class); assertThat(response.getPaging()) .extracting(Common.Paging::getPageIndex, Common.Paging::getPageSize, Common.Paging::getTotal) .containsOnly(1, 100, 2); assertThat(response.getOrganizationsList()) .extracting(GithubOrganization::getKey, GithubOrganization::getName) .containsOnly(tuple("github", "github"), tuple("octacat", "octacat")); verify(appClient).createUserAccessToken(githubAlmSettings.getUrl(), githubAlmSettings.getClientId(), githubAlmSettings.getDecryptedClientSecret(encryption), "abc"); verify(appClient).listOrganizations(eq(githubAlmSettings.getUrl()), argThat(token -> token.getValue().equals(accessToken.getValue())), eq(1), eq(100)); Mockito.verifyNoMoreInteractions(appClient); assertThat(db.getDbClient().almPatDao().selectByUserAndAlmSetting(db.getSession(), userSession.getUuid(), githubAlmSettings).get().getPersonalAccessToken()) .isEqualTo(accessToken.getValue()); } @Test public void return_organizations_using_existing_personal_access_token() { AlmSettingDto githubAlmSettings = setupAlm(); AlmPatDto pat = db.almPats().insert(p -> p.setAlmSettingUuid(githubAlmSettings.getUuid()).setUserUuid(userSession.getUuid())); setupGhOrganizations(githubAlmSettings, pat.getPersonalAccessToken()); ListGithubOrganizationsWsResponse response = ws.newRequest() .setParam(PARAM_ALM_SETTING, githubAlmSettings.getKey()) .executeProtobuf(ListGithubOrganizationsWsResponse.class); assertThat(response.getPaging()) .extracting(Common.Paging::getPageIndex, Common.Paging::getPageSize, Common.Paging::getTotal) .containsOnly(1, 100, 2); assertThat(response.getOrganizationsList()) .extracting(GithubOrganization::getKey, GithubOrganization::getName) .containsOnly(tuple("github", "github"), tuple("octacat", "octacat")); verify(appClient, never()).createUserAccessToken(any(), any(), any(), any()); verify(appClient).listOrganizations(eq(githubAlmSettings.getUrl()), argThat(token -> token.getValue().equals(pat.getPersonalAccessToken())), eq(1), eq(100)); Mockito.verifyNoMoreInteractions(appClient); assertThat(db.getDbClient().almPatDao().selectByUserAndAlmSetting(db.getSession(), userSession.getUuid(), githubAlmSettings).get().getPersonalAccessToken()) .isEqualTo(pat.getPersonalAccessToken()); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.4"); assertThat(def.isPost()).isFalse(); assertThat(def.isInternal()).isTrue(); assertThat(def.responseExampleFormat()).isEqualTo("json"); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder(tuple("p", false), tuple("ps", false), tuple("almSetting", true), tuple("token", false)); } private void setupGhOrganizations(AlmSettingDto almSetting, String pat) { when(appClient.listOrganizations(eq(almSetting.getUrl()), argThat(token -> token.getValue().equals(pat)), eq(1), eq(100))) .thenReturn(new GithubApplicationClient.Organizations() .setTotal(2) .setOrganizations(Stream.of("github", "octacat") .map(login -> new GithubApplicationClient.Organization(login.length(), login, login, null, null, null, null, "Organization")) .toList())); } private AlmSettingDto setupAlm() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS); return db.almSettings().insertGitHubAlmSetting(alm -> alm.setClientId("client_123").setClientSecret("client_secret_123")); } }
13,779
46.681661
161
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/github/ListGithubRepositoriesActionIT.java
/* * 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.almintegration.ws.github; import java.util.stream.Stream; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.github.GithubApplicationClient; import org.sonar.alm.client.github.GithubApplicationClientImpl; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDao; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Common; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.server.tester.UserSessionRule.standalone; import static org.sonarqube.ws.AlmIntegrations.GithubRepository; import static org.sonarqube.ws.AlmIntegrations.ListGithubRepositoriesWsResponse; public class ListGithubRepositoriesActionIT { @Rule public UserSessionRule userSession = standalone(); private final System2 system2 = mock(System2.class); private final GithubApplicationClientImpl appClient = mock(GithubApplicationClientImpl.class); @Rule public DbTester db = DbTester.create(system2); private final ProjectAlmSettingDao projectAlmSettingDao = db.getDbClient().projectAlmSettingDao(); private final WsActionTester ws = new WsActionTester(new ListGithubRepositoriesAction(db.getDbClient(), userSession, appClient, projectAlmSettingDao)); @Test public void fail_when_missing_create_project_permission() { TestRequest request = ws.newRequest(); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_almSetting_does_not_exist() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS); TestRequest request = ws.newRequest() .setParam(ListGithubRepositoriesAction.PARAM_ALM_SETTING, "unknown") .setParam(ListGithubRepositoriesAction.PARAM_ORGANIZATION, "test"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("GitHub Setting 'unknown' not found"); } @Test public void fail_when_personal_access_token_doesnt_exist() { AlmSettingDto githubAlmSetting = setupAlm(); TestRequest request = ws.newRequest() .setParam(ListGithubRepositoriesAction.PARAM_ALM_SETTING, githubAlmSetting.getKey()) .setParam(ListGithubRepositoriesAction.PARAM_ORGANIZATION, "test"); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("No personal access token found"); } @Test public void return_repositories_using_existing_personal_access_token() { AlmSettingDto githubAlmSettings = setupAlm(); AlmPatDto pat = db.almPats().insert(p -> p.setAlmSettingUuid(githubAlmSettings.getUuid()).setUserUuid(userSession.getUuid())); when(appClient.listRepositories(eq(githubAlmSettings.getUrl()), argThat(token -> token.getValue().equals(pat.getPersonalAccessToken())), eq("github"), isNull(), eq(1), eq(100))) .thenReturn(new GithubApplicationClient.Repositories() .setTotal(2) .setRepositories(Stream.of("HelloWorld", "HelloUniverse") .map(name -> new GithubApplicationClient.Repository(name.length(), name, false, "github/" + name, "https://github-enterprise.sonarqube.com/api/v3/github/HelloWorld", "main")) .toList())); ProjectDto project = db.components().insertPrivateProject(componentDto -> componentDto.setKey("github_HelloWorld")).getProjectDto(); db.almSettings().insertGitHubProjectAlmSetting(githubAlmSettings, project, projectAlmSettingDto -> projectAlmSettingDto.setAlmRepo("github/HelloWorld")); ProjectDto project2 = db.components().insertPrivateProject(componentDto -> componentDto.setKey("github_HelloWorld2")).getProjectDto(); db.almSettings().insertGitHubProjectAlmSetting(githubAlmSettings, project2, projectAlmSettingDto -> projectAlmSettingDto.setAlmRepo("github/HelloWorld")); ListGithubRepositoriesWsResponse response = ws.newRequest() .setParam(ListGithubRepositoriesAction.PARAM_ALM_SETTING, githubAlmSettings.getKey()) .setParam(ListGithubRepositoriesAction.PARAM_ORGANIZATION, "github") .executeProtobuf(ListGithubRepositoriesWsResponse.class); assertThat(response.getPaging()) .extracting(Common.Paging::getPageIndex, Common.Paging::getPageSize, Common.Paging::getTotal) .containsOnly(1, 100, 2); assertThat(response.getRepositoriesCount()).isEqualTo(2); assertThat(response.getRepositoriesList()) .extracting(GithubRepository::getKey, GithubRepository::getName, GithubRepository::getSqProjectKey) .containsOnly(tuple("github/HelloWorld", "HelloWorld", project.getKey()), tuple("github/HelloUniverse", "HelloUniverse", "")); verify(appClient).listRepositories(eq(githubAlmSettings.getUrl()), argThat(token -> token.getValue().equals(pat.getPersonalAccessToken())), eq("github"), isNull(), eq(1), eq(100)); } private AlmSettingDto setupAlm() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS); return db.almSettings().insertGitHubAlmSetting(alm -> alm.setClientId("client_123").setClientSecret("client_secret_123")); } }
6,905
46.30137
174
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/github/config/CheckActionIT.java
/* * 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.almintegration.ws.github.config; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import org.apache.commons.io.IOUtils; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.github.config.ConfigCheckResult; import org.sonar.alm.client.github.config.ConfigCheckResult.ApplicationStatus; import org.sonar.alm.client.github.config.GithubProvisioningConfigValidator; import org.sonar.api.server.ws.WebService; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.alm.client.github.config.ConfigCheckResult.ConfigStatus; import static org.sonar.alm.client.github.config.ConfigCheckResult.InstallationStatus; import static org.sonar.test.JsonAssert.assertJson; public class CheckActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private GithubProvisioningConfigValidator configValidator = mock(GithubProvisioningConfigValidator.class); private final WsActionTester ws = new WsActionTester(new CheckAction(userSession, configValidator)); @Test public void test_definition() { WebService.Action def = ws.getDef(); assertThat(def.key()).isEqualTo("check"); assertThat(def.since()).isEqualTo("10.1"); assertThat(def.isInternal()).isTrue(); assertThat(def.isPost()).isTrue(); assertThat(def.params()).isEmpty(); assertThat(def.responseExample()).isNotNull(); assertThat(def.responseExample()).isEqualTo(getClass().getResource("check-example.json")); } @Test public void check_whenUserIsAdmin_shouldReturnCheckResult() throws IOException { userSession.logIn().setSystemAdministrator(); ConfigCheckResult result = new ConfigCheckResult( new ApplicationStatus( ConfigStatus.SUCCESS, ConfigStatus.failed("App validation failed")), List.of( new InstallationStatus( "org1", ConfigStatus.SUCCESS, ConfigStatus.SUCCESS ), new InstallationStatus( "org2", ConfigStatus.SUCCESS, ConfigStatus.failed("Organization validation failed.") ) )); when(configValidator.checkConfig()).thenReturn(result); TestResponse response = ws.newRequest().execute(); assertThat(response.getStatus()).isEqualTo(200); assertJson(response.getInput()).isSimilarTo(readResponse("check-example.json")); } @Test public void check_whenNotAnAdmin_shouldThrow() { userSession.logIn("not-an-admin"); TestRequest testRequest = ws.newRequest(); assertThatThrownBy(testRequest::execute) .hasMessage("Insufficient privileges") .isInstanceOf(ForbiddenException.class); } private String readResponse(String file) throws IOException { return IOUtils.toString(getClass().getResource(file), StandardCharsets.UTF_8); } }
4,079
36.777778
108
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/gitlab/ImportGitLabProjectActionIT.java
/* * 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.almintegration.ws.gitlab; import java.util.Optional; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.gitlab.GitLabBranch; import org.sonar.alm.client.gitlab.GitlabHttpClient; import org.sonar.alm.client.gitlab.Project; import org.sonar.api.utils.System2; import org.sonar.core.i18n.I18n; import org.sonar.core.platform.EditionProvider; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbTester; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.component.BranchDto; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.almintegration.ws.ImportHelper; import org.sonar.server.almintegration.ws.ProjectKeyGenerator; import org.sonar.server.component.ComponentUpdater; import org.sonar.server.es.TestIndexers; import org.sonar.server.favorite.FavoriteUpdater; import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver; import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.project.DefaultBranchNameResolver; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.project.Visibility; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Projects; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; import static org.sonar.db.newcodeperiod.NewCodePeriodType.NUMBER_OF_DAYS; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.server.tester.UserSessionRule.standalone; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE; public class ImportGitLabProjectActionIT { private static final String PROJECT_KEY_NAME = "PROJECT_NAME"; private final System2 system2 = mock(System2.class); @Rule public UserSessionRule userSession = standalone(); @Rule public DbTester db = DbTester.create(system2); DefaultBranchNameResolver defaultBranchNameResolver = mock(DefaultBranchNameResolver.class); private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), mock(I18n.class), System2.INSTANCE, mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestIndexers(), new SequenceUuidFactory(), defaultBranchNameResolver, true); private final GitlabHttpClient gitlabHttpClient = mock(GitlabHttpClient.class); private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession); private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class); private final ProjectKeyGenerator projectKeyGenerator = mock(ProjectKeyGenerator.class); private PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class); private NewCodeDefinitionResolver newCodeDefinitionResolver = new NewCodeDefinitionResolver(db.getDbClient(), editionProvider); private final ImportGitLabProjectAction importGitLabProjectAction = new ImportGitLabProjectAction( db.getDbClient(), userSession, projectDefaultVisibility, gitlabHttpClient, componentUpdater, importHelper, projectKeyGenerator, newCodeDefinitionResolver, defaultBranchNameResolver); private final WsActionTester ws = new WsActionTester(importGitLabProjectAction); @Before public void before() { when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE); when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn(DEFAULT_MAIN_BRANCH_NAME); } @Test public void import_project_developer_edition() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); dto.setPersonalAccessToken("PAT"); }); Project project = getGitlabProject(); when(gitlabHttpClient.getProject(any(), any(), any())).thenReturn(project); when(gitlabHttpClient.getBranches(any(), any(), any())).thenReturn(singletonList(new GitLabBranch("master", true))); when(projectKeyGenerator.generateUniqueProjectKey(project.getPathWithNamespace())).thenReturn(PROJECT_KEY_NAME); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("gitlabProjectId", "12345") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS") .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30") .executeProtobuf(Projects.CreateWsResponse.class); verify(gitlabHttpClient).getProject(almSetting.getUrl(), "PAT", 12345L); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME); assertThat(result.getName()).isEqualTo(project.getName()); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid) .containsExactly(NUMBER_OF_DAYS, "30", null); } @Test public void import_project_community_edition() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); dto.setPersonalAccessToken("PAT"); }); Project project = getGitlabProject(); when(gitlabHttpClient.getProject(any(), any(), any())).thenReturn(project); when(gitlabHttpClient.getBranches(any(), any(), any())).thenReturn(singletonList(new GitLabBranch("master", true))); when(projectKeyGenerator.generateUniqueProjectKey(project.getPathWithNamespace())).thenReturn(PROJECT_KEY_NAME); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("gitlabProjectId", "12345") .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS") .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30") .executeProtobuf(Projects.CreateWsResponse.class); Projects.CreateWsResponse.Project result = response.getProject(); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); String projectUuid = projectDto.get().getUuid(); assertThat(db.getDbClient().newCodePeriodDao().selectByBranch(db.getSession(), projectUuid, projectUuid)) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid) .containsExactly(NUMBER_OF_DAYS, "30", projectUuid); } @Test public void import_project_with_specific_different_default_branch() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); dto.setPersonalAccessToken("PAT"); }); Project project = getGitlabProject(); when(gitlabHttpClient.getProject(any(), any(), any())).thenReturn(project); when(gitlabHttpClient.getBranches(any(), any(), any())).thenReturn(singletonList(new GitLabBranch("main", true))); when(projectKeyGenerator.generateUniqueProjectKey(project.getPathWithNamespace())).thenReturn(PROJECT_KEY_NAME); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("gitlabProjectId", "12345") .executeProtobuf(Projects.CreateWsResponse.class); verify(gitlabHttpClient).getProject(almSetting.getUrl(), "PAT", 12345L); verify(gitlabHttpClient).getBranches(almSetting.getUrl(), "PAT", 12345L); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME); assertThat(result.getName()).isEqualTo(project.getName()); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent(); Assertions.assertThat(db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get())) .extracting(BranchDto::getKey, BranchDto::isMain) .containsExactlyInAnyOrder(tuple("main", true)); } @Test public void import_project_no_gitlab_default_branch() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); dto.setPersonalAccessToken("PAT"); }); Project project = getGitlabProject(); when(gitlabHttpClient.getProject(any(), any(), any())).thenReturn(project); when(gitlabHttpClient.getBranches(any(), any(), any())).thenReturn(emptyList()); when(projectKeyGenerator.generateUniqueProjectKey(project.getPathWithNamespace())).thenReturn(PROJECT_KEY_NAME); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("gitlabProjectId", "12345") .executeProtobuf(Projects.CreateWsResponse.class); verify(gitlabHttpClient).getProject(almSetting.getUrl(), "PAT", 12345L); verify(gitlabHttpClient).getBranches(almSetting.getUrl(), "PAT", 12345L); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME); assertThat(result.getName()).isEqualTo(project.getName()); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent(); Assertions.assertThat(db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get())) .extracting(BranchDto::getKey, BranchDto::isMain) .containsExactlyInAnyOrder(tuple(DEFAULT_MAIN_BRANCH_NAME, true)); } @Test public void import_project_without_NCD() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); dto.setPersonalAccessToken("PAT"); }); Project project = getGitlabProject(); when(gitlabHttpClient.getProject(any(), any(), any())).thenReturn(project); when(gitlabHttpClient.getBranches(any(), any(), any())).thenReturn(singletonList(new GitLabBranch("master", true))); when(projectKeyGenerator.generateUniqueProjectKey(project.getPathWithNamespace())).thenReturn(PROJECT_KEY_NAME); Projects.CreateWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .setParam("gitlabProjectId", "12345") .executeProtobuf(Projects.CreateWsResponse.class); verify(gitlabHttpClient).getProject(almSetting.getUrl(), "PAT", 12345L); Projects.CreateWsResponse.Project result = response.getProject(); assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME); assertThat(result.getName()).isEqualTo(project.getName()); Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey()); assertThat(projectDto).isPresent(); assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent(); } private Project getGitlabProject() { return new Project(randomAlphanumeric(5), randomAlphanumeric(5)); } }
14,286
48.265517
158
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/gitlab/SearchGitlabReposActionIT.java
/* * 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.almintegration.ws.gitlab; import java.util.Arrays; import java.util.LinkedList; import org.junit.Rule; import org.junit.Test; import org.sonar.alm.client.gitlab.GitlabHttpClient; import org.sonar.alm.client.gitlab.Project; import org.sonar.alm.client.gitlab.ProjectList; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.project.ProjectDto; 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.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.AlmIntegrations; import org.sonarqube.ws.AlmIntegrations.GitlabRepository; import org.sonarqube.ws.AlmIntegrations.SearchGitlabReposWsResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; 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.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; public class SearchGitlabReposActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final GitlabHttpClient gitlabHttpClient = mock(GitlabHttpClient.class); private final WsActionTester ws = new WsActionTester(new SearchGitlabReposAction(db.getDbClient(), userSession, gitlabHttpClient)); @Test public void list_gitlab_repos() { Project gitlabProject1 = new Project(1L, "repoName1", "repoNamePath1", "repo-slug-1", "repo-path-slug-1", "url-1"); Project gitlabProject2 = new Project(2L, "repoName2", "path1 / repoName2", "repo-slug-2", "path-1/repo-slug-2", "url-2"); Project gitlabProject3 = new Project(3L, "repoName3", "repoName3 / repoName3", "repo-slug-3", "repo-slug-3/repo-slug-3", "url-3"); Project gitlabProject4 = new Project(4L, "repoName4", "repoName4 / repoName4 / repoName4", "repo-slug-4", "repo-slug-4/repo-slug-4/repo-slug-4", "url-4"); when(gitlabHttpClient.searchProjects(any(), any(), any(), anyInt(), anyInt())) .thenReturn( new ProjectList(Arrays.asList(gitlabProject1, gitlabProject2, gitlabProject3, gitlabProject4), 1, 10, 4)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); dto.setPersonalAccessToken("some-pat"); }); ProjectDto projectDto = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertGitlabProjectAlmSetting(almSetting, projectDto); AlmIntegrations.SearchGitlabReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchGitlabReposWsResponse.class); assertThat(response.getRepositoriesCount()).isEqualTo(4); assertThat(response.getRepositoriesList()) .extracting(GitlabRepository::getId, GitlabRepository::getName, GitlabRepository::getPathName, GitlabRepository::getSlug, GitlabRepository::getPathSlug, GitlabRepository::getUrl, GitlabRepository::hasSqProjectKey, GitlabRepository::hasSqProjectName) .containsExactlyInAnyOrder( tuple(1L, "repoName1", "repoNamePath1", "repo-slug-1", "repo-path-slug-1", "url-1", false, false), tuple(2L, "repoName2", "path1", "repo-slug-2", "path-1", "url-2", false, false), tuple(3L, "repoName3", "repoName3", "repo-slug-3", "repo-slug-3", "url-3", false, false), tuple(4L, "repoName4", "repoName4 / repoName4", "repo-slug-4", "repo-slug-4/repo-slug-4", "url-4", false, false)); } @Test public void list_gitlab_repos_some_projects_already_set_up() { Project gitlabProject1 = new Project(1L, "repoName1", "repoNamePath1", "repo-slug-1", "repo-path-slug-1", "url-1"); Project gitlabProject2 = new Project(2L, "repoName2", "path1 / repoName2", "repo-slug-2", "path-1/repo-slug-2", "url-2"); Project gitlabProject3 = new Project(3L, "repoName3", "repoName3 / repoName3", "repo-slug-3", "repo-slug-3/repo-slug-3", "url-3"); Project gitlabProject4 = new Project(4L, "repoName4", "repoName4 / repoName4 / repoName4", "repo-slug-4", "repo-slug-4/repo-slug-4/repo-slug-4", "url-4"); when(gitlabHttpClient.searchProjects(any(), any(), any(), anyInt(), anyInt())) .thenReturn( new ProjectList(Arrays.asList(gitlabProject1, gitlabProject2, gitlabProject3, gitlabProject4), 1, 10, 4)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); dto.setPersonalAccessToken("some-pat"); }); ProjectDto projectDto1 = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertGitlabProjectAlmSetting(almSetting, projectDto1); ProjectDto projectDto2 = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertGitlabProjectAlmSetting(almSetting, projectDto2, projectAlmSettingDto -> projectAlmSettingDto.setAlmRepo("2")); ProjectDto projectDto3 = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertGitlabProjectAlmSetting(almSetting, projectDto3, projectAlmSettingDto -> projectAlmSettingDto.setAlmRepo("3")); ProjectDto projectDto4 = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertGitlabProjectAlmSetting(almSetting, projectDto4, projectAlmSettingDto -> projectAlmSettingDto.setAlmRepo("3")); AlmIntegrations.SearchGitlabReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchGitlabReposWsResponse.class); assertThat(response.getRepositoriesCount()).isEqualTo(4); assertThat(response.getRepositoriesList()) .extracting(GitlabRepository::getId, GitlabRepository::getName, GitlabRepository::getPathName, GitlabRepository::getSlug, GitlabRepository::getPathSlug, GitlabRepository::getUrl, GitlabRepository::getSqProjectKey, GitlabRepository::getSqProjectName) .containsExactlyInAnyOrder( tuple(1L, "repoName1", "repoNamePath1", "repo-slug-1", "repo-path-slug-1", "url-1", "", ""), tuple(2L, "repoName2", "path1", "repo-slug-2", "path-1", "url-2", projectDto2.getKey(), projectDto2.getName()), tuple(3L, "repoName3", "repoName3", "repo-slug-3", "repo-slug-3", "url-3", projectDto3.getKey(), projectDto3.getName()), tuple(4L, "repoName4", "repoName4 / repoName4", "repo-slug-4", "repo-slug-4/repo-slug-4", "url-4", "", "")); } @Test public void return_empty_list_when_no_gitlab_projects() { when(gitlabHttpClient.searchProjects(any(), any(), any(), anyInt(), anyInt())).thenReturn(new ProjectList(new LinkedList<>(), 1, 10, 0)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertBitbucketAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); }); ProjectDto projectDto = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertGitlabProjectAlmSetting(almSetting, projectDto); AlmIntegrations.SearchGitlabReposWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(SearchGitlabReposWsResponse.class); assertThat(response.getRepositoriesList()).isEmpty(); } @Test public void check_pat_is_missing() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting(); TestRequest request = ws.newRequest() .setParam("almSetting", almSetting.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("No personal access token found"); } @Test public void fail_when_alm_setting_not_found() { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmPatDto almPatDto = newAlmPatDto(); db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null); TestRequest request = ws.newRequest() .setParam("almSetting", "testKey"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("DevOps Platform Setting 'testKey' not found"); } @Test public void fail_when_not_logged_in() { TestRequest request = ws.newRequest() .setParam("almSetting", "anyvalue"); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class) .hasMessage("Authentication is required"); } @Test public void fail_when_no_creation_project_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); TestRequest request = ws.newRequest() .setParam("almSetting", "anyvalue"); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void verify_response_example() { Project gitlabProject1 = new Project(1L, "Gitlab repo name 1", "Group / Gitlab repo name 1", "gitlab-repo-name-1", "group/gitlab-repo-name-1", "https://example.gitlab.com/group/gitlab-repo-name-1"); Project gitlabProject2 = new Project(2L, "Gitlab repo name 2", "Group / Gitlab repo name 2", "gitlab-repo-name-2", "group/gitlab-repo-name-2", "https://example.gitlab.com/group/gitlab-repo-name-2"); Project gitlabProject3 = new Project(3L, "Gitlab repo name 3", "Group / Gitlab repo name 3", "gitlab-repo-name-3", "group/gitlab-repo-name-3", "https://example.gitlab.com/group/gitlab-repo-name-3"); when(gitlabHttpClient.searchProjects(any(), any(), any(), anyInt(), anyInt())) .thenReturn( new ProjectList(Arrays.asList(gitlabProject1, gitlabProject2, gitlabProject3), 1, 3, 10)); UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting(); db.almPats().insert(dto -> { dto.setAlmSettingUuid(almSetting.getUuid()); dto.setUserUuid(user.getUuid()); dto.setPersonalAccessToken("some-pat"); }); ProjectDto projectDto = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertGitlabProjectAlmSetting(almSetting, projectDto); WebService.Action def = ws.getDef(); String responseExample = def.responseExampleAsString(); assertThat(responseExample).isNotBlank(); ws.newRequest() .setParam("almSetting", almSetting.getKey()) .execute().assertJson( responseExample); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.5"); assertThat(def.isPost()).isFalse(); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("almSetting", true), tuple("p", false), tuple("ps", false), tuple("projectName", false)); } }
12,974
44.848057
158
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/CountBindingActionIT.java
/* * 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.almsettings.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.almsettings.MultipleAlmFeature; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.AlmSettings.CountBindingWsResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.sonar.test.JsonAssert.assertJson; public class CountBindingActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private WsActionTester ws = new WsActionTester(new CountBindingAction(db.getDbClient(), userSession, new AlmSettingsSupport(db.getDbClient(), userSession, new ComponentFinder(db.getDbClient(), null), mock(MultipleAlmFeature.class)))); @Test public void count_github_binding() { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); ProjectDto project1 = db.components().insertPrivateProject().getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertGitHubProjectAlmSetting(almSetting, project1); db.almSettings().insertGitHubProjectAlmSetting(almSetting, project2); CountBindingWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(CountBindingWsResponse.class); assertThat(response.getKey()).isEqualTo(almSetting.getKey()); assertThat(response.getProjects()).isEqualTo(2); } @Test public void count_azure_binding() { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting(); ProjectDto project1 = db.components().insertPrivateProject().getProjectDto(); db.almSettings().insertAzureProjectAlmSetting(almSetting, project1); CountBindingWsResponse response = ws.newRequest() .setParam("almSetting", almSetting.getKey()) .executeProtobuf(CountBindingWsResponse.class); assertThat(response.getKey()).isEqualTo(almSetting.getKey()); assertThat(response.getProjects()).isOne(); } @Test public void fail_when_alm_setting_does_not_exist() { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); assertThatThrownBy(() -> ws.newRequest() .setParam("almSetting", "unknown") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("DevOps Platform setting with key 'unknown' cannot be found"); } @Test public void fail_when_missing_system_administer_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); AlmSettingDto githubAlmSetting = db.almSettings().insertGitHubAlmSetting(); assertThatThrownBy(() -> ws.newRequest() .setParam("almSetting", githubAlmSetting.getKey()) .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void json_example() { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); AlmSettingDto githubAlmSetting = db.almSettings().insertGitHubAlmSetting( almSettingDto -> almSettingDto .setKey("GitHub Server - Dev Team") .setAppId("12345") .setPrivateKey("54684654")); db.almSettings().insertGitHubProjectAlmSetting(githubAlmSetting, db.components().insertPrivateProject().getProjectDto()); db.almSettings().insertGitHubProjectAlmSetting(githubAlmSetting, db.components().insertPrivateProject().getProjectDto()); db.almSettings().insertGitHubProjectAlmSetting(githubAlmSetting, db.components().insertPrivateProject().getProjectDto()); String response = ws.newRequest() .setParam("almSetting", githubAlmSetting.getKey()) .execute().getInput(); assertJson(response).isSimilarTo(getClass().getResource("count_binding-example.json")); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.1"); assertThat(def.isPost()).isFalse(); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder(tuple("almSetting", true)); } }
5,742
38.881944
125
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/CreateAzureActionIT.java
/* * 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.almsettings.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.internal.Encryption; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.user.UserDto; import org.sonar.server.almsettings.MultipleAlmFeature; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CreateAzureActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final Encryption encryption = mock(Encryption.class); private final MultipleAlmFeature multipleAlmFeature = mock(MultipleAlmFeature.class); private WsActionTester ws = new WsActionTester(new CreateAzureAction(db.getDbClient(), userSession, new AlmSettingsSupport(db.getDbClient(), userSession, new ComponentFinder(db.getDbClient(), null), multipleAlmFeature))); @Before public void before() { when(multipleAlmFeature.isAvailable()).thenReturn(false); } @Test public void create() { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); ws.newRequest() .setParam("key", "Azure Server - Dev Team") .setParam("personalAccessToken", "98765432100") .setParam("url", "https://ado.sonarqube.com/") .execute(); assertThat(db.getDbClient().almSettingDao().selectAll(db.getSession())) .extracting(AlmSettingDto::getKey, s -> s.getDecryptedPersonalAccessToken(encryption), AlmSettingDto::getUrl) .containsOnly(tuple("Azure Server - Dev Team", "98765432100", "https://ado.sonarqube.com/")); } @Test public void fail_when_key_is_already_used() { when(multipleAlmFeature.isAvailable()).thenReturn(true); UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); AlmSettingDto azureAlmSetting = db.almSettings().insertAzureAlmSetting(); assertThatThrownBy(() -> ws.newRequest() .setParam("key", azureAlmSetting.getKey()) .setParam("personalAccessToken", "98765432100") .setParam("url", "https://ado.sonarqube.com/") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(String.format("An DevOps Platform setting with key '%s' already exist", azureAlmSetting.getKey())); } @Test public void fail_when_no_multiple_instance_allowed() { when(multipleAlmFeature.isAvailable()).thenReturn(false); UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); db.almSettings().insertAzureAlmSetting(); assertThatThrownBy(() -> ws.newRequest() .setParam("key", "key") .setParam("personalAccessToken", "98765432100") .setParam("url", "https://ado.sonarqube.com/") .execute()) .isInstanceOf(BadRequestException.class) .hasMessageContaining("A AZURE_DEVOPS setting is already defined"); } @Test public void fail_when_missing_administer_system_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); assertThatThrownBy(() -> ws.newRequest() .setParam("key", "Azure Server - Dev Team") .setParam("personalAccessToken", "98765432100") .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.1"); assertThat(def.isPost()).isTrue(); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder(tuple("key", true), tuple("personalAccessToken", true), tuple("url", true)); } }
5,062
36.503704
127
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/CreateBitbucketActionIT.java
/* * 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.almsettings.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.internal.Encryption; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.user.UserDto; import org.sonar.server.almsettings.MultipleAlmFeature; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CreateBitbucketActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final Encryption encryption = mock(Encryption.class); private final MultipleAlmFeature multipleAlmFeature = mock(MultipleAlmFeature.class); private WsActionTester ws = new WsActionTester(new CreateBitBucketAction(db.getDbClient(), userSession, new AlmSettingsSupport(db.getDbClient(), userSession, new ComponentFinder(db.getDbClient(), null), multipleAlmFeature))); @Before public void before() { when(multipleAlmFeature.isAvailable()).thenReturn(false); } @Test public void create() { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); ws.newRequest() .setParam("key", "Bitbucket Server - Dev Team") .setParam("url", "https://bitbucket.enterprise.com") .setParam("personalAccessToken", "98765432100") .execute(); assertThat(db.getDbClient().almSettingDao().selectAll(db.getSession())) .extracting(AlmSettingDto::getKey, AlmSettingDto::getUrl, s -> s.getDecryptedPersonalAccessToken(encryption)) .containsOnly(tuple("Bitbucket Server - Dev Team", "https://bitbucket.enterprise.com", "98765432100")); } @Test public void fail_when_key_is_already_used() { when(multipleAlmFeature.isAvailable()).thenReturn(true); UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); AlmSettingDto bitbucketAlmSetting = db.almSettings().insertBitbucketAlmSetting(); assertThatThrownBy(() -> ws.newRequest() .setParam("key", bitbucketAlmSetting.getKey()) .setParam("url", "https://bitbucket.enterprise.com") .setParam("personalAccessToken", "98765432100") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(String.format("An DevOps Platform setting with key '%s' already exist", bitbucketAlmSetting.getKey())); } @Test public void fail_when_no_multiple_instance_allowed() { when(multipleAlmFeature.isAvailable()).thenReturn(false); UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); db.almSettings().insertBitbucketAlmSetting(); assertThatThrownBy(() -> ws.newRequest() .setParam("key", "otherKey") .setParam("url", "https://bitbucket.enterprise.com") .setParam("personalAccessToken", "98765432100") .execute()) .isInstanceOf(BadRequestException.class) .hasMessageContaining("A BITBUCKET setting is already defined"); } @Test public void fail_when_no_multiple_instance_allowed_and_bitbucket_cloud_exists() { when(multipleAlmFeature.isAvailable()).thenReturn(false); UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); db.almSettings().insertBitbucketCloudAlmSetting(); assertThatThrownBy(() -> ws.newRequest() .setParam("key", "otherKey") .setParam("url", "https://bitbucket.enterprise.com") .setParam("personalAccessToken", "98765432100") .execute()) .isInstanceOf(BadRequestException.class) .hasMessageContaining("A BITBUCKET_CLOUD setting is already defined"); } @Test public void fail_when_missing_administer_system_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); assertThatThrownBy(() -> ws.newRequest() .setParam("key", "Bitbucket Server - Dev Team") .setParam("url", "https://bitbucket.enterprise.com") .setParam("personalAccessToken", "98765432100") .setParam("personalAccessToken", "98765432100") .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.since()).isEqualTo("8.1"); assertThat(def.isPost()).isTrue(); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder(tuple("key", true), tuple("url", true), tuple("personalAccessToken", true)); } }
5,873
37.900662
131
java