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-core/src/test/java/org/sonar/server/startup/RegisterPermissionTemplatesTest.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.startup;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.security.DefaultGroups;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbTester;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.permission.template.PermissionTemplateGroupDto;
import org.sonar.db.user.GroupDto;
import org.sonar.server.usergroups.DefaultGroupFinder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto;
import static org.sonar.server.property.InternalProperties.DEFAULT_PROJECT_TEMPLATE;
public class RegisterPermissionTemplatesTest {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public LogTester logTester = new LogTester();
private RegisterPermissionTemplates underTest = new RegisterPermissionTemplates(db.getDbClient(), UuidFactoryFast.getInstance(), System2.INSTANCE, new DefaultGroupFinder(db.getDbClient()));
@Test
public void insert_default_permission_template_if_fresh_install() {
GroupDto defaultGroup = db.users().insertDefaultGroup();
db.users().insertGroup(DefaultGroups.ADMINISTRATORS);
underTest.start();
PermissionTemplateDto defaultTemplate = selectTemplate();
assertThat(defaultTemplate.getName()).isEqualTo("Default template");
List<PermissionTemplateGroupDto> groupPermissions = selectGroupPermissions(defaultTemplate);
assertThat(groupPermissions).hasSize(5);
expectGroupPermission(groupPermissions, UserRole.ADMIN, DefaultGroups.ADMINISTRATORS);
expectGroupPermission(groupPermissions, UserRole.CODEVIEWER, defaultGroup.getName());
expectGroupPermission(groupPermissions, UserRole.USER, defaultGroup.getName());
expectGroupPermission(groupPermissions, UserRole.ISSUE_ADMIN, defaultGroup.getName());
expectGroupPermission(groupPermissions, UserRole.SECURITYHOTSPOT_ADMIN, defaultGroup.getName());
verifyDefaultTemplateForProject(defaultTemplate.getUuid());
assertThat(logTester.logs(Level.ERROR)).isEmpty();
}
@Test
public void ignore_administrators_permissions_if_group_does_not_exist() {
GroupDto defaultGroup = db.users().insertDefaultGroup();
underTest.start();
PermissionTemplateDto defaultTemplate = selectTemplate();
assertThat(defaultTemplate.getName()).isEqualTo("Default template");
List<PermissionTemplateGroupDto> groupPermissions = selectGroupPermissions(defaultTemplate);
assertThat(groupPermissions).hasSize(4);
expectGroupPermission(groupPermissions, UserRole.CODEVIEWER, defaultGroup.getName());
expectGroupPermission(groupPermissions, UserRole.USER, defaultGroup.getName());
expectGroupPermission(groupPermissions, UserRole.ISSUE_ADMIN, defaultGroup.getName());
expectGroupPermission(groupPermissions, UserRole.SECURITYHOTSPOT_ADMIN, defaultGroup.getName());
verifyDefaultTemplateForProject(defaultTemplate.getUuid());
assertThat(logTester.logs(Level.ERROR)).contains("Cannot setup default permission for group: sonar-administrators");
}
@Test
public void do_not_fail_if_default_template_exists() {
db.users().insertDefaultGroup();
PermissionTemplateDto projectTemplate = db.permissionTemplates().insertTemplate(newPermissionTemplateDto());
db.getDbClient().internalPropertiesDao().save(db.getSession(), DEFAULT_PROJECT_TEMPLATE, projectTemplate.getUuid());
db.commit();
underTest.start();
verifyDefaultTemplateForProject(projectTemplate.getUuid());
}
private PermissionTemplateDto selectTemplate() {
return db.getDbClient().permissionTemplateDao().selectByName(db.getSession(), "Default template");
}
private List<PermissionTemplateGroupDto> selectGroupPermissions(PermissionTemplateDto template) {
return db.getDbClient().permissionTemplateDao().selectGroupPermissionsByTemplateUuid(db.getSession(), template.getUuid());
}
private void expectGroupPermission(List<PermissionTemplateGroupDto> groupPermissions, String expectedPermission,
String expectedGroupName) {
assertThat(
groupPermissions.stream().anyMatch(gp -> gp.getPermission().equals(expectedPermission) && Objects.equals(gp.getGroupName(), expectedGroupName)))
.isTrue();
}
private void verifyDefaultTemplateForProject(String expectedDefaultTemplateForProjectUuid) {
Optional<String> defaultPermissionTemplateForProject = db.getDbClient().internalPropertiesDao().selectByKey(db.getSession(), DEFAULT_PROJECT_TEMPLATE);
assertThat(defaultPermissionTemplateForProject).isPresent();
assertThat(defaultPermissionTemplateForProject).contains(expectedDefaultTemplateForProjectUuid);
}
}
| 5,787 | 43.523077 | 191 | java |
sonarqube | sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/RenameDeprecatedPropertyKeysTest.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.startup;
import org.junit.Test;
import org.sonar.api.Properties;
import org.sonar.api.Property;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.System2;
import org.sonar.db.property.PropertiesDao;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
public class RenameDeprecatedPropertyKeysTest {
@Test
public void should_rename_deprecated_keys() {
PropertiesDao dao = mock(PropertiesDao.class);
PropertyDefinitions definitions = new PropertyDefinitions(System2.INSTANCE, FakeExtension.class);
RenameDeprecatedPropertyKeys task = new RenameDeprecatedPropertyKeys(dao, definitions);
task.start();
verify(dao).renamePropertyKey("old_key", "new_key");
verifyNoMoreInteractions(dao);
}
@Properties({
@Property(key = "new_key", deprecatedKey = "old_key", name = "Name"),
@Property(key = "other", name = "Other")
})
public static class FakeExtension {
}
}
| 1,888 | 34.641509 | 101 | java |
sonarqube | sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/telemetry/CloudUsageDataProviderTest.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.telemetry;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import javax.annotation.Nullable;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.api.utils.System2;
import org.sonar.server.platform.ContainerSupport;
import org.sonar.server.util.Paths2;
import org.sonarqube.ws.MediaTypes;
import static java.util.Objects.requireNonNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.server.telemetry.CloudUsageDataProvider.DOCKER_RUNNING;
import static org.sonar.server.telemetry.CloudUsageDataProvider.KUBERNETES_SERVICE_HOST;
import static org.sonar.server.telemetry.CloudUsageDataProvider.KUBERNETES_SERVICE_PORT;
import static org.sonar.server.telemetry.CloudUsageDataProvider.SONAR_HELM_CHART_VERSION;
public class CloudUsageDataProviderTest {
private final System2 system2 = Mockito.mock(System2.class);
private final Paths2 paths2 = Mockito.mock(Paths2.class);
private final OkHttpClient httpClient = Mockito.mock(OkHttpClient.class);
private final ContainerSupport containerSupport = mock(ContainerSupport.class);
private final CloudUsageDataProvider underTest = new CloudUsageDataProvider(containerSupport, system2, paths2, httpClient);
@Before
public void setUp() throws Exception {
when(system2.envVariable(KUBERNETES_SERVICE_HOST)).thenReturn("localhost");
when(system2.envVariable(KUBERNETES_SERVICE_PORT)).thenReturn("443");
mockHttpClientCall(200, "OK", ResponseBody.create("""
{
"major": "1",
"minor": "25",
"gitVersion": "v1.25.3",
"gitCommit": "434bfd82814af038ad94d62ebe59b133fcb50506",
"gitTreeState": "clean",
"buildDate": "2022-11-02T03:24:50Z",
"goVersion": "go1.19.2",
"compiler": "gc",
"platform": "linux/arm64"
}
""", MediaType.parse(MediaTypes.JSON)));
}
private void mockHttpClientCall(int code, String message, @Nullable ResponseBody body) throws IOException {
Call callMock = mock(Call.class);
when(callMock.execute()).thenReturn(new Response.Builder()
.request(new Request.Builder().url("http://any.test/").build())
.protocol(Protocol.HTTP_1_1)
.code(code)
.message(message)
.body(body)
.build());
when(httpClient.newCall(any())).thenReturn(callMock);
}
@Test
public void containerRuntime_whenContainerSupportContextExists_shouldNotBeNull() {
when(containerSupport.getContainerContext()).thenReturn("docker");
assertThat(underTest.getCloudUsage().containerRuntime()).isEqualTo("docker");
}
@Test
public void containerRuntime_whenContainerSupportContextMissing_shouldBeNull() {
when(containerSupport.getContainerContext()).thenReturn(null);
assertThat(underTest.getCloudUsage().containerRuntime()).isNull();
}
@Test
public void kubernetes_whenEnvVarExists_shouldReturnTrue() {
assertThat(underTest.getCloudUsage().kubernetes()).isTrue();
}
@Test
public void kubernetes_whenEnvVarDoesNotExist_shouldReturnFalse() {
when(system2.envVariable(KUBERNETES_SERVICE_HOST)).thenReturn(null);
assertThat(underTest.getCloudUsage().kubernetes()).isFalse();
}
@Test
public void kubernetesVersion_whenOnKubernetes_shouldReturnValue() {
assertThat(underTest.getCloudUsage().kubernetesVersion()).isEqualTo("1.25");
}
@Test
public void kubernetesVersion_whenNotOnKubernetes_shouldReturnNull() {
when(system2.envVariable(KUBERNETES_SERVICE_HOST)).thenReturn(null);
assertThat(underTest.getCloudUsage().kubernetesVersion()).isNull();
}
@Test
public void kubernetesVersion_whenApiCallFails_shouldReturnNull() throws IOException {
mockHttpClientCall(404, "not found", null);
assertThat(underTest.getCloudUsage().kubernetesVersion()).isNull();
}
@Test
public void kubernetesPlatform_whenOnKubernetes_shouldReturnValue() {
assertThat(underTest.getCloudUsage().kubernetesPlatform()).isEqualTo("linux/arm64");
}
@Test
public void kubernetesPlatform_whenNotOnKubernetes_shouldReturnNull() {
when(system2.envVariable(KUBERNETES_SERVICE_HOST)).thenReturn(null);
assertThat(underTest.getCloudUsage().kubernetesPlatform()).isNull();
}
@Test
public void kubernetesPlatform_whenApiCallFails_shouldReturnNull() throws IOException {
mockHttpClientCall(404, "not found", null);
assertThat(underTest.getCloudUsage().kubernetesPlatform()).isNull();
}
@Test
public void kubernetesProvider_shouldReturnValue() {
assertThat(underTest.getCloudUsage().kubernetesProvider()).isNotBlank();
}
@Test
public void officialHelmChart_whenEnvVarExists_shouldReturnValue() {
when(system2.envVariable(SONAR_HELM_CHART_VERSION)).thenReturn("10.1.0");
assertThat(underTest.getCloudUsage().officialHelmChart()).isEqualTo("10.1.0");
}
@Test
public void officialHelmChart_whenEnvVarDoesNotExist_shouldReturnNull() {
when(system2.envVariable(SONAR_HELM_CHART_VERSION)).thenReturn(null);
assertThat(underTest.getCloudUsage().officialHelmChart()).isNull();
}
@Test
public void officialImage_whenEnvVarTrue_shouldReturnTrue() {
when(system2.envVariable(DOCKER_RUNNING)).thenReturn("True");
assertThat(underTest.getCloudUsage().officialImage()).isTrue();
}
@Test
public void officialImage_whenEnvVarFalse_shouldReturnFalse() {
when(system2.envVariable(DOCKER_RUNNING)).thenReturn("False");
assertThat(underTest.getCloudUsage().officialImage()).isFalse();
}
@Test
public void officialImage_whenEnvVarDoesNotExist_shouldReturnFalse() {
when(system2.envVariable(DOCKER_RUNNING)).thenReturn(null);
assertThat(underTest.getCloudUsage().officialImage()).isFalse();
}
@Test
public void initHttpClient_whenValidCertificate_shouldCreateClient() throws URISyntaxException {
when(paths2.get(anyString())).thenReturn(Paths.get(requireNonNull(getClass().getResource("dummy.crt")).toURI()));
CloudUsageDataProvider provider = new CloudUsageDataProvider(containerSupport, system2, paths2);
assertThat(provider.getHttpClient()).isNotNull();
}
@Test
public void initHttpClient_whenNotOnKubernetes_shouldNotCreateClient() throws URISyntaxException {
when(paths2.get(anyString())).thenReturn(Paths.get(requireNonNull(getClass().getResource("dummy.crt")).toURI()));
when(system2.envVariable(KUBERNETES_SERVICE_HOST)).thenReturn(null);
CloudUsageDataProvider provider = new CloudUsageDataProvider(containerSupport, system2, paths2);
assertThat(provider.getHttpClient()).isNull();
}
@Test
public void initHttpClient_whenCertificateNotFound_shouldFail() {
when(paths2.get(any())).thenReturn(Paths.get("dummy.crt"));
CloudUsageDataProvider provider = new CloudUsageDataProvider(containerSupport, system2, paths2);
assertThat(provider.getHttpClient()).isNull();
}
}
| 8,140 | 37.952153 | 125 | java |
sonarqube | sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/telemetry/FakeServer.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.telemetry;
import java.util.Date;
import javax.annotation.CheckForNull;
import org.sonar.api.platform.Server;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
class FakeServer extends Server {
private String id;
private String version;
public FakeServer() {
this.id = randomAlphanumeric(20);
this.version = randomAlphanumeric(10);
}
@Override
public String getId() {
return id;
}
FakeServer setId(String id) {
this.id = id;
return this;
}
@CheckForNull
@Override
public String getPermanentServerId() {
return null;
}
@Override
public String getVersion() {
return this.version;
}
public FakeServer setVersion(String version) {
this.version = version;
return this;
}
@Override
public Date getStartedAt() {
return null;
}
@Override
public String getContextPath() {
return null;
}
@Override
public String getPublicRootUrl() {
return null;
}
@Override
public boolean isSecured() {
return false;
}
}
| 1,915 | 21.809524 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/telemetry/TelemetryClientCompressionTest.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.telemetry;
import java.io.IOException;
import java.util.Objects;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import okio.GzipSource;
import okio.Okio;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.process.ProcessProperties.Property.SONAR_TELEMETRY_URL;
public class TelemetryClientCompressionTest {
private final OkHttpClient okHttpClient = new OkHttpClient();
private final MockWebServer telemetryServer = new MockWebServer();
@Test
public void payload_is_gzip_encoded() throws IOException, InterruptedException {
telemetryServer.enqueue(new MockResponse().setResponseCode(200));
MapSettings settings = new MapSettings();
settings.setProperty(SONAR_TELEMETRY_URL.getKey(), telemetryServer.url("/").toString());
TelemetryClient underTest = new TelemetryClient(okHttpClient, settings.asConfig());
underTest.start();
underTest.upload("payload compressed with gzip");
RecordedRequest request = telemetryServer.takeRequest();
String contentType = Objects.requireNonNull(request.getHeader("content-type"));
assertThat(MediaType.parse(contentType)).isEqualTo(MediaType.parse("application/json; charset=utf-8"));
assertThat(request.getHeader("content-encoding")).isEqualTo("gzip");
GzipSource source = new GzipSource(request.getBody());
String body = Okio.buffer(source).readUtf8();
Assertions.assertThat(body).isEqualTo("payload compressed with gzip");
}
}
| 2,582 | 40 | 107 | java |
sonarqube | sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/telemetry/TelemetryClientTest.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.telemetry;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okio.Buffer;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.config.internal.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.sonar.process.ProcessProperties.Property.SONAR_TELEMETRY_COMPRESSION;
import static org.sonar.process.ProcessProperties.Property.SONAR_TELEMETRY_URL;
public class TelemetryClientTest {
private static final String JSON = "{\"key\":\"value\"}";
private static final String TELEMETRY_URL = "https://telemetry.com/url";
private OkHttpClient okHttpClient = mock(OkHttpClient.class, RETURNS_DEEP_STUBS);
private MapSettings settings = new MapSettings();
private TelemetryClient underTest = new TelemetryClient(okHttpClient, settings.asConfig());
@Test
public void upload() throws IOException {
ArgumentCaptor<Request> requestCaptor = ArgumentCaptor.forClass(Request.class);
settings.setProperty(SONAR_TELEMETRY_URL.getKey(), TELEMETRY_URL);
settings.setProperty(SONAR_TELEMETRY_COMPRESSION.getKey(), false);
underTest.start();
underTest.upload(JSON);
verify(okHttpClient).newCall(requestCaptor.capture());
Request request = requestCaptor.getValue();
assertThat(request.method()).isEqualTo("POST");
assertThat(request.body().contentType()).isEqualTo(MediaType.parse("application/json; charset=utf-8"));
Buffer body = new Buffer();
request.body().writeTo(body);
assertThat(body.readUtf8()).isEqualTo(JSON);
assertThat(request.url()).hasToString(TELEMETRY_URL);
}
@Test
public void opt_out() throws IOException {
ArgumentCaptor<Request> requestCaptor = ArgumentCaptor.forClass(Request.class);
settings.setProperty(SONAR_TELEMETRY_URL.getKey(), TELEMETRY_URL);
underTest.start();
underTest.optOut(JSON);
verify(okHttpClient).newCall(requestCaptor.capture());
Request request = requestCaptor.getValue();
assertThat(request.method()).isEqualTo("DELETE");
assertThat(request.body().contentType()).isEqualTo(MediaType.parse("application/json; charset=utf-8"));
Buffer body = new Buffer();
request.body().writeTo(body);
assertThat(body.readUtf8()).isEqualTo(JSON);
assertThat(request.url()).hasToString(TELEMETRY_URL);
}
}
| 3,368 | 38.635294 | 107 | java |
sonarqube | sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/telemetry/TelemetryDaemonTest.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.telemetry;
import java.io.IOException;
import java.util.Collections;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.server.property.InternalProperties;
import org.sonar.server.property.MapInternalProperties;
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.anyString;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.after;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.api.utils.DateUtils.parseDate;
import static org.sonar.process.ProcessProperties.Property.SONAR_TELEMETRY_ENABLE;
import static org.sonar.process.ProcessProperties.Property.SONAR_TELEMETRY_FREQUENCY_IN_SECONDS;
import static org.sonar.process.ProcessProperties.Property.SONAR_TELEMETRY_URL;
public class TelemetryDaemonTest {
@Rule
public LogTester logger = new LogTester().setLevel(LoggerLevel.DEBUG);
private static final long ONE_HOUR = 60 * 60 * 1_000L;
private static final long ONE_DAY = 24 * ONE_HOUR;
private static final TelemetryData SOME_TELEMETRY_DATA = TelemetryData.builder()
.setServerId("foo")
.setVersion("bar")
.setMessageSequenceNumber(1L)
.setPlugins(Collections.emptyMap())
.setDatabase(new TelemetryData.Database("H2", "11"))
.build();
private final TelemetryClient client = mock(TelemetryClient.class);
private final InternalProperties internalProperties = spy(new MapInternalProperties());
private final GlobalLockManager lockManager = mock(GlobalLockManagerImpl.class);
private final TestSystem2 system2 = new TestSystem2().setNow(System.currentTimeMillis());
private final MapSettings settings = new MapSettings();
private final TelemetryDataLoader dataLoader = mock(TelemetryDataLoader.class);
private final TelemetryDataJsonWriter dataJsonWriter = mock(TelemetryDataJsonWriter.class);
private final TelemetryDaemon underTest = new TelemetryDaemon(dataLoader, dataJsonWriter, client, settings.asConfig(), internalProperties, lockManager, system2);
@After
public void tearDown() {
underTest.stop();
}
@Test
public void send_data_via_client_at_startup_after_initial_delay() throws IOException {
initTelemetrySettingsToDefaultValues();
when(lockManager.tryLock(any(), anyInt())).thenReturn(true);
settings.setProperty("sonar.telemetry.frequencyInSeconds", "1");
when(dataLoader.load()).thenReturn(SOME_TELEMETRY_DATA);
mockDataJsonWriterDoingSomething();
underTest.start();
verify(client, timeout(2_000).atLeastOnce()).upload(anyString());
verify(dataJsonWriter).writeTelemetryData(any(JsonWriter.class), same(SOME_TELEMETRY_DATA));
}
private void mockDataJsonWriterDoingSomething() {
doAnswer(t -> {
JsonWriter json = t.getArgument(0);
json.beginObject().prop("foo", "bar").endObject();
return null;
})
.when(dataJsonWriter)
.writeTelemetryData(any(), any());
}
@Test
public void check_if_should_send_data_periodically() throws IOException {
initTelemetrySettingsToDefaultValues();
when(lockManager.tryLock(any(), anyInt())).thenReturn(true);
long now = system2.now();
long twentyHoursAgo = now - (ONE_HOUR * 20L);
long oneDayAgo = now - ONE_DAY;
internalProperties.write("telemetry.lastPing", String.valueOf(twentyHoursAgo));
settings.setProperty("sonar.telemetry.frequencyInSeconds", "1");
when(dataLoader.load()).thenReturn(SOME_TELEMETRY_DATA);
mockDataJsonWriterDoingSomething();
underTest.start();
verify(dataJsonWriter, after(2_000).never()).writeTelemetryData(any(JsonWriter.class), same(SOME_TELEMETRY_DATA));
verify(client, never()).upload(anyString());
internalProperties.write("telemetry.lastPing", String.valueOf(oneDayAgo));
verify(client, timeout(2_000)).upload(anyString());
verify(dataJsonWriter).writeTelemetryData(any(JsonWriter.class), same(SOME_TELEMETRY_DATA));
}
@Test
public void do_not_send_data_if_last_ping_earlier_than_one_day_ago() throws IOException {
initTelemetrySettingsToDefaultValues();
when(lockManager.tryLock(any(), anyInt())).thenReturn(true);
settings.setProperty("sonar.telemetry.frequencyInSeconds", "1");
long now = system2.now();
long twentyHoursAgo = now - (ONE_HOUR * 20L);
mockDataJsonWriterDoingSomething();
internalProperties.write("telemetry.lastPing", String.valueOf(twentyHoursAgo));
underTest.start();
verify(client, after(2_000).never()).upload(anyString());
}
@Test
public void send_data_if_last_ping_is_over_one_day_ago() throws IOException {
initTelemetrySettingsToDefaultValues();
when(lockManager.tryLock(any(), anyInt())).thenReturn(true);
settings.setProperty("sonar.telemetry.frequencyInSeconds", "1");
long today = parseDate("2017-08-01").getTime();
system2.setNow(today);
long oneDayAgo = today - ONE_DAY - ONE_HOUR;
internalProperties.write("telemetry.lastPing", String.valueOf(oneDayAgo));
reset(internalProperties);
when(dataLoader.load()).thenReturn(SOME_TELEMETRY_DATA);
mockDataJsonWriterDoingSomething();
underTest.start();
verify(internalProperties, timeout(4_000)).write("telemetry.lastPing", String.valueOf(today));
verify(client).upload(anyString());
}
@Test
public void opt_out_sent_once() throws IOException {
initTelemetrySettingsToDefaultValues();
when(lockManager.tryLock(any(), anyInt())).thenReturn(true);
settings.setProperty("sonar.telemetry.frequencyInSeconds", "1");
settings.setProperty("sonar.telemetry.enable", "false");
mockDataJsonWriterDoingSomething();
underTest.start();
underTest.start();
verify(client, after(2_000).never()).upload(anyString());
verify(client, timeout(2_000).times(1)).optOut(anyString());
assertThat(logger.logs(Level.INFO)).contains("Sharing of SonarQube statistics is disabled.");
}
@Test
public void write_sequence_as_one_if_not_previously_present() {
initTelemetrySettingsToDefaultValues();
when(lockManager.tryLock(any(), anyInt())).thenReturn(true);
settings.setProperty("sonar.telemetry.frequencyInSeconds", "1");
mockDataJsonWriterDoingSomething();
underTest.start();
verify(internalProperties, timeout(4_000)).write("telemetry.messageSeq", "1");
}
@Test
public void write_sequence_correctly_incremented() {
initTelemetrySettingsToDefaultValues();
when(lockManager.tryLock(any(), anyInt())).thenReturn(true);
settings.setProperty("sonar.telemetry.frequencyInSeconds", "1");
internalProperties.write("telemetry.messageSeq", "10");
mockDataJsonWriterDoingSomething();
underTest.start();
verify(internalProperties, timeout(4_000)).write("telemetry.messageSeq", "10");
// force another ping
internalProperties.write("telemetry.lastPing", String.valueOf(system2.now() - ONE_DAY));
verify(internalProperties, timeout(4_000)).write("telemetry.messageSeq", "11");
}
private void initTelemetrySettingsToDefaultValues() {
settings.setProperty(SONAR_TELEMETRY_ENABLE.getKey(), SONAR_TELEMETRY_ENABLE.getDefaultValue());
settings.setProperty(SONAR_TELEMETRY_URL.getKey(), SONAR_TELEMETRY_URL.getDefaultValue());
settings.setProperty(SONAR_TELEMETRY_FREQUENCY_IN_SECONDS.getKey(), SONAR_TELEMETRY_FREQUENCY_IN_SECONDS.getDefaultValue());
}
}
| 8,988 | 39.859091 | 163 | java |
sonarqube | sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/telemetry/TelemetryDataLoaderImplTest.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.telemetry;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.Configuration;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.core.platform.PlatformEditionProvider;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.alm.setting.AlmSettingDto;
import org.sonar.db.component.AnalysisPropertyDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ProjectData;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.db.user.UserDbTester;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTelemetryDto;
import org.sonar.server.management.ManagedInstanceService;
import org.sonar.server.platform.ContainerSupport;
import org.sonar.server.property.InternalProperties;
import org.sonar.server.property.MapInternalProperties;
import org.sonar.server.qualitygate.QualityGateCaycChecker;
import org.sonar.server.qualitygate.QualityGateFinder;
import org.sonar.server.telemetry.TelemetryData.Branch;
import org.sonar.server.telemetry.TelemetryData.CloudUsage;
import org.sonar.server.telemetry.TelemetryData.NewCodeDefinition;
import org.sonar.server.telemetry.TelemetryData.ProjectStatistics;
import org.sonar.updatecenter.common.Version;
import static java.util.Arrays.asList;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.BUGS_KEY;
import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY;
import static org.sonar.api.measures.CoreMetrics.DEVELOPMENT_COST_KEY;
import static org.sonar.api.measures.CoreMetrics.LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY;
import static org.sonar.api.measures.CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_KEY;
import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_KEY;
import static org.sonar.api.measures.CoreMetrics.VULNERABILITIES_KEY;
import static org.sonar.core.config.CorePropertyDefinitions.SONAR_ANALYSIS_DETECTEDCI;
import static org.sonar.core.config.CorePropertyDefinitions.SONAR_ANALYSIS_DETECTEDSCM;
import static org.sonar.core.platform.EditionProvider.Edition.COMMUNITY;
import static org.sonar.core.platform.EditionProvider.Edition.DEVELOPER;
import static org.sonar.core.platform.EditionProvider.Edition.ENTERPRISE;
import static org.sonar.db.component.BranchType.BRANCH;
import static org.sonar.server.metric.UnanalyzedLanguageMetrics.UNANALYZED_CPP_KEY;
import static org.sonar.server.metric.UnanalyzedLanguageMetrics.UNANALYZED_C_KEY;
import static org.sonar.server.qualitygate.QualityGateCaycStatus.NON_COMPLIANT;
@RunWith(DataProviderRunner.class)
public class TelemetryDataLoaderImplTest {
private final static Long NOW = 100_000_000L;
private final TestSystem2 system2 = new TestSystem2().setNow(NOW);
@Rule
public DbTester db = DbTester.create(system2);
private final FakeServer server = new FakeServer();
private final PluginRepository pluginRepository = mock(PluginRepository.class);
private final Configuration configuration = mock(Configuration.class);
private final PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class);
private final ContainerSupport containerSupport = mock(ContainerSupport.class);
private final QualityGateCaycChecker qualityGateCaycChecker = mock(QualityGateCaycChecker.class);
private final QualityGateFinder qualityGateFinder = new QualityGateFinder(db.getDbClient());
private final InternalProperties internalProperties = spy(new MapInternalProperties());
private final ManagedInstanceService managedInstanceService = mock(ManagedInstanceService.class);
private final CloudUsageDataProvider cloudUsageDataProvider = mock(CloudUsageDataProvider.class);
private final TelemetryDataLoader communityUnderTest = new TelemetryDataLoaderImpl(server, db.getDbClient(), pluginRepository, editionProvider,
internalProperties, configuration, containerSupport, qualityGateCaycChecker, qualityGateFinder, managedInstanceService, cloudUsageDataProvider);
private final TelemetryDataLoader commercialUnderTest = new TelemetryDataLoaderImpl(server, db.getDbClient(), pluginRepository, editionProvider,
internalProperties, configuration, containerSupport, qualityGateCaycChecker, qualityGateFinder, managedInstanceService, cloudUsageDataProvider);
private QualityGateDto builtInDefaultQualityGate;
private MetricDto bugsDto;
private MetricDto vulnerabilitiesDto;
private MetricDto securityHotspotsDto;
private MetricDto technicalDebtDto;
private MetricDto developmentCostDto;
@Before
public void setUpBuiltInQualityGate() {
String builtInQgName = "Sonar Way";
builtInDefaultQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName(builtInQgName).setBuiltIn(true));
when(qualityGateCaycChecker.checkCaycCompliant(any(), any())).thenReturn(NON_COMPLIANT);
db.qualityGates().setDefaultQualityGate(builtInDefaultQualityGate);
bugsDto = db.measures().insertMetric(m -> m.setKey(BUGS_KEY));
vulnerabilitiesDto = db.measures().insertMetric(m -> m.setKey(VULNERABILITIES_KEY));
securityHotspotsDto = db.measures().insertMetric(m -> m.setKey(SECURITY_HOTSPOTS_KEY));
technicalDebtDto = db.measures().insertMetric(m -> m.setKey(TECHNICAL_DEBT_KEY));
developmentCostDto = db.measures().insertMetric(m -> m.setKey(DEVELOPMENT_COST_KEY));
}
@Test
public void send_telemetry_data() {
String serverId = "AU-TpxcB-iU5OvuD2FL7";
String version = "7.5.4";
Long analysisDate = 1L;
Long lastConnectionDate = 5L;
server.setId(serverId);
server.setVersion(version);
List<PluginInfo> plugins = asList(newPlugin("java", "4.12.0.11033"), newPlugin("scmgit", "1.2"), new PluginInfo("other"));
when(pluginRepository.getPluginInfos()).thenReturn(plugins);
when(editionProvider.get()).thenReturn(Optional.of(DEVELOPER));
List<UserDto> activeUsers = composeActiveUsers(3);
// update last connection
activeUsers.forEach(u -> db.users().updateLastConnectionDate(u, 5L));
UserDto inactiveUser = db.users().insertUser(u -> u.setActive(false).setExternalIdentityProvider("provider0"));
MetricDto lines = db.measures().insertMetric(m -> m.setKey(LINES_KEY));
MetricDto ncloc = db.measures().insertMetric(m -> m.setKey(NCLOC_KEY));
MetricDto coverage = db.measures().insertMetric(m -> m.setKey(COVERAGE_KEY));
MetricDto nclocDistrib = db.measures().insertMetric(m -> m.setKey(NCLOC_LANGUAGE_DISTRIBUTION_KEY));
ProjectData projectData1 = db.components().insertPrivateProject();
ComponentDto mainBranch1 = projectData1.getMainBranchComponent();
db.measures().insertLiveMeasure(mainBranch1, lines, m -> m.setValue(110d));
db.measures().insertLiveMeasure(mainBranch1, ncloc, m -> m.setValue(110d));
db.measures().insertLiveMeasure(mainBranch1, coverage, m -> m.setValue(80d));
db.measures().insertLiveMeasure(mainBranch1, nclocDistrib, m -> m.setValue(null).setData("java=70;js=30;kotlin=10"));
db.measures().insertLiveMeasure(mainBranch1, bugsDto, m -> m.setValue(1d));
db.measures().insertLiveMeasure(mainBranch1, vulnerabilitiesDto, m -> m.setValue(1d).setData((String) null));
db.measures().insertLiveMeasure(mainBranch1, securityHotspotsDto, m -> m.setValue(1d).setData((String) null));
db.measures().insertLiveMeasure(mainBranch1, developmentCostDto, m -> m.setData("50").setValue(null));
db.measures().insertLiveMeasure(mainBranch1, technicalDebtDto, m -> m.setValue(5d).setData((String) null));
ProjectData projectData2 = db.components().insertPrivateProject();
ComponentDto mainBranch2 = projectData2.getMainBranchComponent();
db.measures().insertLiveMeasure(mainBranch2, lines, m -> m.setValue(200d));
db.measures().insertLiveMeasure(mainBranch2, ncloc, m -> m.setValue(200d));
db.measures().insertLiveMeasure(mainBranch2, coverage, m -> m.setValue(80d));
db.measures().insertLiveMeasure(mainBranch2, nclocDistrib, m -> m.setValue(null).setData("java=180;js=20"));
SnapshotDto project1Analysis = db.components().insertSnapshot(mainBranch1, t -> t.setLast(true).setBuildDate(analysisDate));
SnapshotDto project2Analysis = db.components().insertSnapshot(mainBranch2, t -> t.setLast(true).setBuildDate(analysisDate));
db.measures().insertMeasure(mainBranch1, project1Analysis, nclocDistrib, m -> m.setData("java=70;js=30;kotlin=10"));
db.measures().insertMeasure(mainBranch2, project2Analysis, nclocDistrib, m -> m.setData("java=180;js=20"));
insertAnalysisProperty(project1Analysis, "prop-uuid-1", SONAR_ANALYSIS_DETECTEDCI, "ci-1");
insertAnalysisProperty(project2Analysis, "prop-uuid-2", SONAR_ANALYSIS_DETECTEDCI, "ci-2");
insertAnalysisProperty(project1Analysis, "prop-uuid-3", SONAR_ANALYSIS_DETECTEDSCM, "scm-1");
insertAnalysisProperty(project2Analysis, "prop-uuid-4", SONAR_ANALYSIS_DETECTEDSCM, "scm-2");
// alm
db.almSettings().insertAzureAlmSetting();
db.almSettings().insertGitHubAlmSetting();
AlmSettingDto almSettingDto = db.almSettings().insertAzureAlmSetting(a -> a.setUrl("https://dev.azure.com"));
AlmSettingDto gitHubAlmSetting = db.almSettings().insertGitHubAlmSetting(a -> a.setUrl("https://api.github.com"));
db.almSettings().insertAzureProjectAlmSetting(almSettingDto, projectData1.getProjectDto());
db.almSettings().insertGitlabProjectAlmSetting(gitHubAlmSetting, projectData2.getProjectDto());
// quality gates
QualityGateDto qualityGate1 = db.qualityGates().insertQualityGate(qg -> qg.setName("QG1").setBuiltIn(true));
QualityGateDto qualityGate2 = db.qualityGates().insertQualityGate(qg -> qg.setName("QG2"));
// link one project to a non-default QG
db.qualityGates().associateProjectToQualityGate(db.components().getProjectDtoByMainBranch(mainBranch1), qualityGate1);
var branch1 = db.components().insertProjectBranch(mainBranch1, branchDto -> branchDto.setKey("reference"));
var branch2 = db.components().insertProjectBranch(mainBranch1, branchDto -> branchDto.setKey("custom"));
var ncd1 = db.newCodePeriods().insert(projectData1.projectUuid(), NewCodePeriodType.NUMBER_OF_DAYS, "30");
var ncd2 = db.newCodePeriods().insert(projectData1.projectUuid(), branch2.branchUuid(), NewCodePeriodType.REFERENCE_BRANCH, "reference");
var instanceNcdId = NewCodeDefinition.getInstanceDefault().hashCode();
var projectNcdId = new NewCodeDefinition(NewCodePeriodType.NUMBER_OF_DAYS.name(), "30", "project").hashCode();
var branchNcdId = new NewCodeDefinition(NewCodePeriodType.REFERENCE_BRANCH.name(), branch1.uuid(), "branch").hashCode();
TelemetryData data = communityUnderTest.load();
assertThat(data.getServerId()).isEqualTo(serverId);
assertThat(data.getVersion()).isEqualTo(version);
assertThat(data.getEdition()).contains(DEVELOPER);
assertThat(data.getDefaultQualityGate()).isEqualTo(builtInDefaultQualityGate.getUuid());
assertThat(data.getNcdId()).isEqualTo(NewCodeDefinition.getInstanceDefault().hashCode());
assertThat(data.getMessageSequenceNumber()).isOne();
assertDatabaseMetadata(data.getDatabase());
assertThat(data.getPlugins()).containsOnly(
entry("java", "4.12.0.11033"), entry("scmgit", "1.2"), entry("other", "undefined"));
assertThat(data.isInContainer()).isFalse();
assertThat(data.getUserTelemetries())
.extracting(UserTelemetryDto::getUuid, UserTelemetryDto::getLastConnectionDate, UserTelemetryDto::getLastSonarlintConnectionDate, UserTelemetryDto::isActive)
.containsExactlyInAnyOrder(
tuple(activeUsers.get(0).getUuid(), lastConnectionDate, activeUsers.get(0).getLastSonarlintConnectionDate(), true),
tuple(activeUsers.get(1).getUuid(), lastConnectionDate, activeUsers.get(1).getLastSonarlintConnectionDate(), true),
tuple(activeUsers.get(2).getUuid(), lastConnectionDate, activeUsers.get(2).getLastSonarlintConnectionDate(), true),
tuple(inactiveUser.getUuid(), null, inactiveUser.getLastSonarlintConnectionDate(), false));
assertThat(data.getProjects())
.extracting(TelemetryData.Project::projectUuid, TelemetryData.Project::language, TelemetryData.Project::loc, TelemetryData.Project::lastAnalysis)
.containsExactlyInAnyOrder(
tuple(projectData1.projectUuid(), "java", 70L, analysisDate),
tuple(projectData1.projectUuid(), "js", 30L, analysisDate),
tuple(projectData1.projectUuid(), "kotlin", 10L, analysisDate),
tuple(projectData2.projectUuid(), "java", 180L, analysisDate),
tuple(projectData2.projectUuid(), "js", 20L, analysisDate));
assertThat(data.getProjectStatistics())
.extracting(ProjectStatistics::getBranchCount, ProjectStatistics::getPullRequestCount, ProjectStatistics::getQualityGate,
ProjectStatistics::getScm, ProjectStatistics::getCi, ProjectStatistics::getDevopsPlatform,
ProjectStatistics::getBugs, ProjectStatistics::getVulnerabilities, ProjectStatistics::getSecurityHotspots,
ProjectStatistics::getDevelopmentCost, ProjectStatistics::getTechnicalDebt, ProjectStatistics::getNcdId)
.containsExactlyInAnyOrder(
tuple(3L, 0L, qualityGate1.getUuid(), "scm-1", "ci-1", "azure_devops_cloud", Optional.of(1L), Optional.of(1L), Optional.of(1L), Optional.of(50L), Optional.of(5L),
projectNcdId),
tuple(1L, 0L, builtInDefaultQualityGate.getUuid(), "scm-2", "ci-2", "github_cloud", Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(),
Optional.empty(), instanceNcdId));
assertThat(data.getBranches())
.extracting(Branch::branchUuid, Branch::ncdId)
.containsExactlyInAnyOrder(
tuple(branch1.uuid(), projectNcdId),
tuple(branch2.uuid(), branchNcdId),
tuple(mainBranch1.uuid(), projectNcdId),
tuple(mainBranch2.uuid(), instanceNcdId));
assertThat(data.getNewCodeDefinitions())
.extracting(NewCodeDefinition::scope, NewCodeDefinition::type, NewCodeDefinition::value)
.containsExactlyInAnyOrder(
tuple("instance", NewCodePeriodType.PREVIOUS_VERSION.name(), ""),
tuple("project", NewCodePeriodType.NUMBER_OF_DAYS.name(), "30"),
tuple("branch", NewCodePeriodType.REFERENCE_BRANCH.name(), branch1.uuid()));
assertThat(data.getQualityGates())
.extracting(TelemetryData.QualityGate::uuid, TelemetryData.QualityGate::caycStatus)
.containsExactlyInAnyOrder(
tuple(builtInDefaultQualityGate.getUuid(), "non-compliant"),
tuple(qualityGate1.getUuid(), "non-compliant"),
tuple(qualityGate2.getUuid(), "non-compliant")
);
}
@Test
public void send_branch_measures_data() {
Long analysisDate = ZonedDateTime.now(ZoneId.systemDefault()).toInstant().toEpochMilli();
MetricDto qg = db.measures().insertMetric(m -> m.setKey(ALERT_STATUS_KEY));
ProjectData projectData1 = db.components().insertPrivateProject();
ComponentDto mainBranch1 = projectData1.getMainBranchComponent();
ProjectData projectData2 = db.components().insertPrivateProject();
ComponentDto mainBranch2 = projectData2.getMainBranchComponent();
SnapshotDto project1Analysis1 = db.components().insertSnapshot(mainBranch1, t -> t.setLast(true).setBuildDate(analysisDate));
SnapshotDto project1Analysis2 = db.components().insertSnapshot(mainBranch1, t -> t.setLast(true).setBuildDate(analysisDate));
SnapshotDto project2Analysis = db.components().insertSnapshot(mainBranch2, t -> t.setLast(true).setBuildDate(analysisDate));
db.measures().insertMeasure(mainBranch1, project1Analysis1, qg, pm -> pm.setData("OK"));
db.measures().insertMeasure(mainBranch1, project1Analysis2, qg, pm -> pm.setData("ERROR"));
db.measures().insertMeasure(mainBranch2, project2Analysis, qg, pm -> pm.setData("ERROR"));
var branch1 = db.components().insertProjectBranch(mainBranch1, branchDto -> branchDto.setKey("reference"));
var branch2 = db.components().insertProjectBranch(mainBranch1, branchDto -> branchDto.setKey("custom"));
db.newCodePeriods().insert(projectData1.projectUuid(), NewCodePeriodType.NUMBER_OF_DAYS, "30");
db.newCodePeriods().insert(projectData1.projectUuid(), branch2.branchUuid(), NewCodePeriodType.REFERENCE_BRANCH, "reference");
var instanceNcdId = NewCodeDefinition.getInstanceDefault().hashCode();
var projectNcdId = new NewCodeDefinition(NewCodePeriodType.NUMBER_OF_DAYS.name(), "30", "project").hashCode();
var branchNcdId = new NewCodeDefinition(NewCodePeriodType.REFERENCE_BRANCH.name(), branch1.uuid(), "branch").hashCode();
TelemetryData data = communityUnderTest.load();
assertThat(data.getBranches())
.extracting(Branch::branchUuid, Branch::ncdId, Branch::greenQualityGateCount, Branch::analysisCount)
.containsExactlyInAnyOrder(
tuple(branch1.uuid(), projectNcdId, 0, 0),
tuple(branch2.uuid(), branchNcdId, 0, 0),
tuple(mainBranch1.uuid(), projectNcdId, 1, 2),
tuple(mainBranch2.uuid(), instanceNcdId, 0, 1));
}
private List<UserDto> composeActiveUsers(int count) {
UserDbTester userDbTester = db.users();
Function<Integer, Consumer<UserDto>> userConfigurator = index -> user -> user.setExternalIdentityProvider("provider" + index).setLastSonarlintConnectionDate(index * 2L);
return IntStream
.rangeClosed(1, count)
.mapToObj(userConfigurator::apply)
.map(userDbTester::insertUser)
.toList();
}
private void assertDatabaseMetadata(TelemetryData.Database database) {
try (DbSession dbSession = db.getDbClient().openSession(false)) {
DatabaseMetaData metadata = dbSession.getConnection().getMetaData();
assertThat(database.name()).isEqualTo("H2");
assertThat(database.version()).isEqualTo(metadata.getDatabaseProductVersion());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Test
public void take_largest_branch_snapshot_project_data() {
server.setId("AU-TpxcB-iU5OvuD2FL7").setVersion("7.5.4");
MetricDto lines = db.measures().insertMetric(m -> m.setKey(LINES_KEY));
MetricDto ncloc = db.measures().insertMetric(m -> m.setKey(NCLOC_KEY));
MetricDto coverage = db.measures().insertMetric(m -> m.setKey(COVERAGE_KEY));
MetricDto nclocDistrib = db.measures().insertMetric(m -> m.setKey(NCLOC_LANGUAGE_DISTRIBUTION_KEY));
ProjectData projectData = db.components().insertPublicProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
db.measures().insertLiveMeasure(mainBranch, lines, m -> m.setValue(110d));
db.measures().insertLiveMeasure(mainBranch, ncloc, m -> m.setValue(110d));
db.measures().insertLiveMeasure(mainBranch, coverage, m -> m.setValue(80d));
db.measures().insertLiveMeasure(mainBranch, nclocDistrib, m -> m.setValue(null).setData("java=70;js=30;kotlin=10"));
ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(BRANCH));
db.measures().insertLiveMeasure(branch, lines, m -> m.setValue(180d));
db.measures().insertLiveMeasure(branch, ncloc, m -> m.setValue(180d));
db.measures().insertLiveMeasure(branch, coverage, m -> m.setValue(80d));
db.measures().insertLiveMeasure(branch, nclocDistrib, m -> m.setValue(null).setData("java=100;js=50;kotlin=30"));
SnapshotDto project1Analysis = db.components().insertSnapshot(mainBranch, t -> t.setLast(true));
SnapshotDto project2Analysis = db.components().insertSnapshot(branch, t -> t.setLast(true));
db.measures().insertMeasure(mainBranch, project1Analysis, nclocDistrib, m -> m.setData("java=70;js=30;kotlin=10"));
db.measures().insertMeasure(branch, project2Analysis, nclocDistrib, m -> m.setData("java=100;js=50;kotlin=30"));
TelemetryData data = communityUnderTest.load();
assertThat(data.getProjects()).extracting(TelemetryData.Project::projectUuid, TelemetryData.Project::language, TelemetryData.Project::loc)
.containsExactlyInAnyOrder(
tuple(projectData.projectUuid(), "java", 100L),
tuple(projectData.projectUuid(), "js", 50L),
tuple(projectData.projectUuid(), "kotlin", 30L));
assertThat(data.getProjectStatistics())
.extracting(ProjectStatistics::getBranchCount, ProjectStatistics::getPullRequestCount,
ProjectStatistics::getScm, ProjectStatistics::getCi)
.containsExactlyInAnyOrder(
tuple(2L, 0L, "undetected", "undetected"));
}
@Test
public void test_ncd_on_community_edition() {
server.setId("AU-TpxcB-iU5OvuD2FL7").setVersion("7.5.4");
when(editionProvider.get()).thenReturn(Optional.of(COMMUNITY));
ProjectData project = db.components().insertPublicProject();
ComponentDto branch = db.components().insertProjectBranch(project.getMainBranchComponent(), b -> b.setBranchType(BRANCH));
db.newCodePeriods().insert(project.projectUuid(), branch.branchUuid(), NewCodePeriodType.NUMBER_OF_DAYS, "30");
var projectNcdId = new NewCodeDefinition(NewCodePeriodType.NUMBER_OF_DAYS.name(), "30", "project").hashCode();
TelemetryData data = communityUnderTest.load();
assertThat(data.getProjectStatistics())
.extracting(ProjectStatistics::getBranchCount, ProjectStatistics::getNcdId)
.containsExactlyInAnyOrder(tuple(2L, projectNcdId));
assertThat(data.getBranches())
.extracting(Branch::branchUuid, Branch::ncdId)
.contains(tuple(branch.uuid(), projectNcdId));
}
@Test
public void data_contains_weekly_count_sonarlint_users() {
db.users().insertUser(c -> c.setLastSonarlintConnectionDate(NOW - 100_000L));
db.users().insertUser(c -> c.setLastSonarlintConnectionDate(NOW));
// these don't count
db.users().insertUser(c -> c.setLastSonarlintConnectionDate(NOW - 1_000_000_000L));
db.users().insertUser();
TelemetryData data = communityUnderTest.load();
assertThat(data.getUserTelemetries())
.hasSize(4);
}
@Test
public void send_server_id_and_version() {
String id = randomAlphanumeric(40);
String version = randomAlphanumeric(10);
server.setId(id);
server.setVersion(version);
TelemetryData data = communityUnderTest.load();
assertThat(data.getServerId()).isEqualTo(id);
assertThat(data.getVersion()).isEqualTo(version);
data = commercialUnderTest.load();
assertThat(data.getServerId()).isEqualTo(id);
assertThat(data.getVersion()).isEqualTo(version);
}
@Test
public void send_server_installation_date_and_installation_version() {
String installationVersion = "7.9.BEST.LTS.EVER";
Long installationDate = 1546300800000L; // 2019/01/01
internalProperties.write(InternalProperties.INSTALLATION_DATE, String.valueOf(installationDate));
internalProperties.write(InternalProperties.INSTALLATION_VERSION, installationVersion);
TelemetryData data = communityUnderTest.load();
assertThat(data.getInstallationDate()).isEqualTo(installationDate);
assertThat(data.getInstallationVersion()).isEqualTo(installationVersion);
}
@Test
public void send_correct_sequence_number() {
internalProperties.write(TelemetryDaemon.I_PROP_MESSAGE_SEQUENCE, "10");
TelemetryData data = communityUnderTest.load();
assertThat(data.getMessageSequenceNumber()).isEqualTo(11L);
}
@Test
public void do_not_send_server_installation_details_if_missing_property() {
TelemetryData data = communityUnderTest.load();
assertThat(data.getInstallationDate()).isNull();
assertThat(data.getInstallationVersion()).isNull();
data = commercialUnderTest.load();
assertThat(data.getInstallationDate()).isNull();
assertThat(data.getInstallationVersion()).isNull();
}
@Test
public void send_unanalyzed_languages_flags_when_edition_is_community() {
when(editionProvider.get()).thenReturn(Optional.of(COMMUNITY));
MetricDto unanalyzedC = db.measures().insertMetric(m -> m.setKey(UNANALYZED_C_KEY));
MetricDto unanalyzedCpp = db.measures().insertMetric(m -> m.setKey(UNANALYZED_CPP_KEY));
ComponentDto project1 = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPublicProject().getMainBranchComponent();
db.measures().insertLiveMeasure(project1, unanalyzedC);
db.measures().insertLiveMeasure(project2, unanalyzedC);
db.measures().insertLiveMeasure(project2, unanalyzedCpp);
TelemetryData data = communityUnderTest.load();
assertThat(data.hasUnanalyzedC().get()).isTrue();
assertThat(data.hasUnanalyzedCpp().get()).isTrue();
}
@Test
public void do_not_send_unanalyzed_languages_flags_when_edition_is_not_community() {
when(editionProvider.get()).thenReturn(Optional.of(DEVELOPER));
MetricDto unanalyzedC = db.measures().insertMetric(m -> m.setKey(UNANALYZED_C_KEY));
MetricDto unanalyzedCpp = db.measures().insertMetric(m -> m.setKey(UNANALYZED_CPP_KEY));
ComponentDto project1 = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPublicProject().getMainBranchComponent();
db.measures().insertLiveMeasure(project1, unanalyzedC);
db.measures().insertLiveMeasure(project2, unanalyzedCpp);
TelemetryData data = communityUnderTest.load();
assertThat(data.hasUnanalyzedC()).isEmpty();
assertThat(data.hasUnanalyzedCpp()).isEmpty();
}
@Test
public void unanalyzed_languages_flags_are_set_to_false_when_no_unanalyzed_languages_and_edition_is_community() {
when(editionProvider.get()).thenReturn(Optional.of(COMMUNITY));
TelemetryData data = communityUnderTest.load();
assertThat(data.hasUnanalyzedC().get()).isFalse();
assertThat(data.hasUnanalyzedCpp().get()).isFalse();
}
@Test
public void populate_security_custom_config_for_languages_on_enterprise() {
when(editionProvider.get()).thenReturn(Optional.of(ENTERPRISE));
when(configuration.get("sonar.security.config.javasecurity")).thenReturn(Optional.of("{}"));
when(configuration.get("sonar.security.config.phpsecurity")).thenReturn(Optional.of("{}"));
when(configuration.get("sonar.security.config.pythonsecurity")).thenReturn(Optional.of("{}"));
when(configuration.get("sonar.security.config.roslyn.sonaranalyzer.security.cs")).thenReturn(Optional.of("{}"));
TelemetryData data = commercialUnderTest.load();
assertThat(data.getCustomSecurityConfigs())
.containsExactlyInAnyOrder("java", "php", "python", "csharp");
}
@Test
public void skip_security_custom_config_on_community() {
when(editionProvider.get()).thenReturn(Optional.of(COMMUNITY));
TelemetryData data = communityUnderTest.load();
assertThat(data.getCustomSecurityConfigs()).isEmpty();
}
@Test
public void undetected_alm_ci_slm_data() {
server.setId("AU-TpxcB-iU5OvuD2FL7").setVersion("7.5.4");
db.components().insertPublicProject().getMainBranchComponent();
TelemetryData data = communityUnderTest.load();
assertThat(data.getProjectStatistics())
.extracting(ProjectStatistics::getDevopsPlatform, ProjectStatistics::getScm, ProjectStatistics::getCi)
.containsExactlyInAnyOrder(tuple("undetected", "undetected", "undetected"));
}
@Test
@UseDataProvider("getManagedInstanceData")
public void managedInstanceData_containsCorrectInformation(boolean isManaged, String provider) {
when(managedInstanceService.isInstanceExternallyManaged()).thenReturn(isManaged);
when(managedInstanceService.getProviderName()).thenReturn(provider);
TelemetryData data = commercialUnderTest.load();
TelemetryData.ManagedInstanceInformation managedInstance = data.getManagedInstanceInformation();
assertThat(managedInstance.isManaged()).isEqualTo(isManaged);
assertThat(managedInstance.provider()).isEqualTo(provider);
}
@Test
public void load_shouldContainCloudUsage() {
CloudUsage cloudUsage = new CloudUsage(true, "1.27", "linux/amd64", "5.4.181-99.354.amzn2.x86_64", "10.1.0", "docker", false);
when(cloudUsageDataProvider.getCloudUsage()).thenReturn(cloudUsage);
TelemetryData data = commercialUnderTest.load();
assertThat(data.getCloudUsage()).isEqualTo(cloudUsage);
}
@Test
public void default_quality_gate_sent_with_project() {
db.components().insertPublicProject().getMainBranchComponent();
QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("anything").setBuiltIn(true));
db.qualityGates().setDefaultQualityGate(qualityGate);
TelemetryData data = communityUnderTest.load();
assertThat(data.getProjectStatistics())
.extracting(ProjectStatistics::getQualityGate)
.containsOnly(qualityGate.getUuid());
}
private PluginInfo newPlugin(String key, String version) {
return new PluginInfo(key)
.setVersion(Version.create(version));
}
private void insertAnalysisProperty(SnapshotDto snapshotDto, String uuid, String key, String value) {
db.getDbClient().analysisPropertiesDao().insert(db.getSession(), new AnalysisPropertyDto()
.setUuid(uuid)
.setAnalysisUuid(snapshotDto.getUuid())
.setKey(key)
.setValue(value)
.setCreatedAt(1L));
}
@DataProvider
public static Set<String> getScimFeatureStatues() {
HashSet<String> result = new HashSet<>();
result.add("true");
result.add("false");
result.add(null);
return result;
}
@DataProvider
public static Object[][] getManagedInstanceData() {
return new Object[][] {
{true, "scim"},
{true, "github"},
{true, "gitlab"},
{false, null},
};
}
}
| 31,664 | 50.487805 | 173 | java |
sonarqube | sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/updatecenter/UpdateCenterModuleTest.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.updatecenter;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class UpdateCenterModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new UpdateCenterModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(2);
}
}
| 1,273 | 35.4 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/util/DateCollectorTest.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.util;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import static org.assertj.core.api.Assertions.assertThat;
public class DateCollectorTest {
DateCollector collector = new DateCollector();
@Test
public void max_is_zero_if_no_dates() {
assertThat(collector.getMax()).isZero();
}
@Test
public void max() {
collector.add(DateUtils.parseDate("2013-06-01"));
collector.add(null);
collector.add(DateUtils.parseDate("2014-01-01"));
collector.add(DateUtils.parseDate("2013-08-01"));
assertThat(collector.getMax()).isEqualTo(DateUtils.parseDateQuietly("2014-01-01").getTime());
}
}
| 1,502 | 31.673913 | 97 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/it/java/org/sonar/server/permission/index/PermissionIndexerDaoIT.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.permission.index;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.ProjectData;
import org.sonar.db.permission.GroupPermissionDto;
import org.sonar.db.portfolio.PortfolioDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDbTester;
import org.sonar.db.user.UserDto;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.resources.Qualifiers.APP;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.api.resources.Qualifiers.VIEW;
import static org.sonar.api.web.UserRole.ADMIN;
import static org.sonar.api.web.UserRole.USER;
public class PermissionIndexerDaoIT {
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private final DbClient dbClient = dbTester.getDbClient();
private final DbSession dbSession = dbTester.getSession();
private final UserDbTester userDbTester = new UserDbTester(dbTester);
private ProjectDto publicProject;
private ProjectDto privateProject1;
private ProjectDto privateProject2;
private PortfolioDto view1;
private PortfolioDto view2;
private ProjectDto application;
private UserDto user1;
private UserDto user2;
private GroupDto group;
private final PermissionIndexerDao underTest = new PermissionIndexerDao();
@Before
public void setUp() {
publicProject = dbTester.components().insertPublicProject().getProjectDto();
privateProject1 = dbTester.components().insertPrivateProject().getProjectDto();
privateProject2 = dbTester.components().insertPrivateProject().getProjectDto();
view1 = dbTester.components().insertPublicPortfolioDto();
view2 = dbTester.components().insertPublicPortfolioDto();
application = dbTester.components().insertPublicApplication().getProjectDto();
user1 = userDbTester.insertUser();
user2 = userDbTester.insertUser();
group = userDbTester.insertGroup();
}
@Test
public void select_all() {
insertTestDataForProjectsAndViews();
Collection<IndexPermissions> dtos = underTest.selectAll(dbClient, dbSession);
Assertions.assertThat(dtos).hasSize(6);
IndexPermissions publicProjectAuthorization = getByProjectUuid(publicProject.getUuid(), dtos);
isPublic(publicProjectAuthorization, PROJECT);
IndexPermissions view1Authorization = getByProjectUuid(view1.getUuid(), dtos);
isPublic(view1Authorization, VIEW);
IndexPermissions applicationAuthorization = getByProjectUuid(application.getUuid(), dtos);
isPublic(applicationAuthorization, APP);
IndexPermissions privateProject1Authorization = getByProjectUuid(privateProject1.getUuid(), dtos);
assertThat(privateProject1Authorization.getGroupUuids()).containsOnly(group.getUuid());
assertThat(privateProject1Authorization.isAllowAnyone()).isFalse();
assertThat(privateProject1Authorization.getUserUuids()).containsOnly(user1.getUuid(), user2.getUuid());
assertThat(privateProject1Authorization.getQualifier()).isEqualTo(PROJECT);
IndexPermissions privateProject2Authorization = getByProjectUuid(privateProject2.getUuid(), dtos);
assertThat(privateProject2Authorization.getGroupUuids()).isEmpty();
assertThat(privateProject2Authorization.isAllowAnyone()).isFalse();
assertThat(privateProject2Authorization.getUserUuids()).containsOnly(user1.getUuid());
assertThat(privateProject2Authorization.getQualifier()).isEqualTo(PROJECT);
IndexPermissions view2Authorization = getByProjectUuid(view2.getUuid(), dtos);
isPublic(view2Authorization, VIEW);
}
@Test
public void selectByUuids() {
insertTestDataForProjectsAndViews();
Map<String, IndexPermissions> dtos = underTest
.selectByUuids(dbClient, dbSession,
asList(publicProject.getUuid(), privateProject1.getUuid(), privateProject2.getUuid(), view1.getUuid(), view2.getUuid(), application.getUuid()))
.stream()
.collect(Collectors.toMap(IndexPermissions::getEntityUuid, Function.identity()));
Assertions.assertThat(dtos).hasSize(6);
IndexPermissions publicProjectAuthorization = dtos.get(publicProject.getUuid());
isPublic(publicProjectAuthorization, PROJECT);
IndexPermissions view1Authorization = dtos.get(view1.getUuid());
isPublic(view1Authorization, VIEW);
IndexPermissions applicationAuthorization = dtos.get(application.getUuid());
isPublic(applicationAuthorization, APP);
IndexPermissions privateProject1Authorization = dtos.get(privateProject1.getUuid());
assertThat(privateProject1Authorization.getGroupUuids()).containsOnly(group.getUuid());
assertThat(privateProject1Authorization.isAllowAnyone()).isFalse();
assertThat(privateProject1Authorization.getUserUuids()).containsOnly(user1.getUuid(), user2.getUuid());
assertThat(privateProject1Authorization.getQualifier()).isEqualTo(PROJECT);
IndexPermissions privateProject2Authorization = dtos.get(privateProject2.getUuid());
assertThat(privateProject2Authorization.getGroupUuids()).isEmpty();
assertThat(privateProject2Authorization.isAllowAnyone()).isFalse();
assertThat(privateProject2Authorization.getUserUuids()).containsOnly(user1.getUuid());
assertThat(privateProject2Authorization.getQualifier()).isEqualTo(PROJECT);
IndexPermissions view2Authorization = dtos.get(view2.getUuid());
isPublic(view2Authorization, VIEW);
}
@Test
public void selectByUuids_returns_empty_list_when_project_does_not_exist() {
insertTestDataForProjectsAndViews();
List<IndexPermissions> dtos = underTest.selectByUuids(dbClient, dbSession, singletonList("missing"));
Assertions.assertThat(dtos).isEmpty();
}
@Test
public void select_by_projects_with_high_number_of_projects() {
List<String> projectUuids = new ArrayList<>();
for (int i = 0; i < 3500; i++) {
ProjectData project = dbTester.components().insertPrivateProject(Integer.toString(i));
projectUuids.add(project.projectUuid());
GroupPermissionDto dto = new GroupPermissionDto()
.setUuid(Uuids.createFast())
.setGroupUuid(group.getUuid())
.setGroupName(group.getName())
.setRole(USER)
.setEntityUuid(project.projectUuid())
.setEntityName(project.getProjectDto().getName());
dbClient.groupPermissionDao().insert(dbSession, dto, project.getProjectDto(), null);
}
dbSession.commit();
assertThat(underTest.selectByUuids(dbClient, dbSession, projectUuids))
.hasSize(3500)
.extracting(IndexPermissions::getEntityUuid)
.containsAll(projectUuids);
}
@Test
public void return_private_project_without_any_permission_when_no_permission_in_DB() {
List<IndexPermissions> dtos = underTest.selectByUuids(dbClient, dbSession, singletonList(privateProject1.getUuid()));
// no permissions
Assertions.assertThat(dtos).hasSize(1);
IndexPermissions dto = dtos.get(0);
assertThat(dto.getGroupUuids()).isEmpty();
assertThat(dto.getUserUuids()).isEmpty();
assertThat(dto.isAllowAnyone()).isFalse();
assertThat(dto.getEntityUuid()).isEqualTo(privateProject1.getUuid());
assertThat(dto.getQualifier()).isEqualTo(privateProject1.getQualifier());
}
@Test
public void return_public_project_with_only_AllowAnyone_true_when_no_permission_in_DB() {
List<IndexPermissions> dtos = underTest.selectByUuids(dbClient, dbSession, singletonList(publicProject.getUuid()));
Assertions.assertThat(dtos).hasSize(1);
IndexPermissions dto = dtos.get(0);
assertThat(dto.getGroupUuids()).isEmpty();
assertThat(dto.getUserUuids()).isEmpty();
assertThat(dto.isAllowAnyone()).isTrue();
assertThat(dto.getEntityUuid()).isEqualTo(publicProject.getUuid());
assertThat(dto.getQualifier()).isEqualTo(publicProject.getQualifier());
}
@Test
public void return_private_project_with_AllowAnyone_false_and_user_id_when_user_is_granted_USER_permission_directly() {
dbTester.users().insertProjectPermissionOnUser(user1, USER, privateProject1);
List<IndexPermissions> dtos = underTest.selectByUuids(dbClient, dbSession, singletonList(privateProject1.getUuid()));
Assertions.assertThat(dtos).hasSize(1);
IndexPermissions dto = dtos.get(0);
assertThat(dto.getGroupUuids()).isEmpty();
assertThat(dto.getUserUuids()).containsOnly(user1.getUuid());
assertThat(dto.isAllowAnyone()).isFalse();
assertThat(dto.getEntityUuid()).isEqualTo(privateProject1.getUuid());
assertThat(dto.getQualifier()).isEqualTo(privateProject1.getQualifier());
}
@Test
public void return_private_project_with_AllowAnyone_false_and_group_id_but_not_user_id_when_user_is_granted_USER_permission_through_group() {
dbTester.users().insertMember(group, user1);
dbTester.users().insertEntityPermissionOnGroup(group, USER, privateProject1);
List<IndexPermissions> dtos = underTest.selectByUuids(dbClient, dbSession, singletonList(privateProject1.getUuid()));
Assertions.assertThat(dtos).hasSize(1);
IndexPermissions dto = dtos.get(0);
assertThat(dto.getGroupUuids()).containsOnly(group.getUuid());
assertThat(dto.getUserUuids()).isEmpty();
assertThat(dto.isAllowAnyone()).isFalse();
assertThat(dto.getEntityUuid()).isEqualTo(privateProject1.getUuid());
assertThat(dto.getQualifier()).isEqualTo(privateProject1.getQualifier());
}
private void isPublic(IndexPermissions view1Authorization, String qualifier) {
assertThat(view1Authorization.getGroupUuids()).isEmpty();
assertThat(view1Authorization.isAllowAnyone()).isTrue();
assertThat(view1Authorization.getUserUuids()).isEmpty();
assertThat(view1Authorization.getQualifier()).isEqualTo(qualifier);
}
private static IndexPermissions getByProjectUuid(String projectUuid, Collection<IndexPermissions> dtos) {
return dtos.stream().filter(dto -> dto.getEntityUuid().equals(projectUuid)).findFirst().orElseThrow(IllegalArgumentException::new);
}
private void insertTestDataForProjectsAndViews() {
// user1 has USER access on both private projects
userDbTester.insertProjectPermissionOnUser(user1, ADMIN, publicProject);
userDbTester.insertProjectPermissionOnUser(user1, USER, privateProject1);
userDbTester.insertProjectPermissionOnUser(user1, USER, privateProject2);
userDbTester.insertProjectPermissionOnUser(user1, ADMIN, view1);
userDbTester.insertProjectPermissionOnUser(user1, ADMIN, application);
// user2 has USER access on privateProject1 only
userDbTester.insertProjectPermissionOnUser(user2, USER, privateProject1);
userDbTester.insertProjectPermissionOnUser(user2, ADMIN, privateProject2);
// group1 has USER access on privateProject1 only
userDbTester.insertEntityPermissionOnGroup(group, USER, privateProject1);
userDbTester.insertEntityPermissionOnGroup(group, ADMIN, privateProject1);
userDbTester.insertEntityPermissionOnGroup(group, ADMIN, view1);
userDbTester.insertEntityPermissionOnGroup(group, ADMIN, application);
}
}
| 12,350 | 44.241758 | 151 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/component/index/ComponentIndex.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.component.index;
import com.google.common.annotations.VisibleForTesting;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.filter.FiltersAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.FiltersAggregator.KeyedFilter;
import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilters;
import org.elasticsearch.search.aggregations.metrics.ParsedTopHits;
import org.elasticsearch.search.aggregations.metrics.TopHitsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.ScoreSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.sonar.api.utils.System2;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.SearchIdResult;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.es.textsearch.ComponentTextSearchFeature;
import org.sonar.server.es.textsearch.ComponentTextSearchFeatureRepertoire;
import org.sonar.server.es.textsearch.ComponentTextSearchQueryFactory;
import org.sonar.server.es.textsearch.ComponentTextSearchQueryFactory.ComponentTextSearchQuery;
import org.sonar.server.permission.index.WebAuthorizationTypeSupport;
import static java.util.Optional.ofNullable;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;
import static org.sonar.server.component.index.ComponentIndexDefinition.FIELD_KEY;
import static org.sonar.server.component.index.ComponentIndexDefinition.FIELD_NAME;
import static org.sonar.server.component.index.ComponentIndexDefinition.FIELD_QUALIFIER;
import static org.sonar.server.component.index.ComponentIndexDefinition.NAME_ANALYZERS;
import static org.sonar.server.component.index.ComponentIndexDefinition.TYPE_COMPONENT;
import static org.sonar.server.es.IndexType.FIELD_INDEX_TYPE;
import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SORTABLE_ANALYZER;
public class ComponentIndex {
private static final String FILTERS_AGGREGATION_NAME = "filters";
private static final String DOCS_AGGREGATION_NAME = "docs";
private final EsClient client;
private final WebAuthorizationTypeSupport authorizationTypeSupport;
private final System2 system2;
public ComponentIndex(EsClient client, WebAuthorizationTypeSupport authorizationTypeSupport, System2 system2) {
this.client = client;
this.authorizationTypeSupport = authorizationTypeSupport;
this.system2 = system2;
}
public SearchIdResult<String> search(ComponentQuery query, SearchOptions searchOptions) {
SearchSourceBuilder source = new SearchSourceBuilder()
.fetchSource(false)
.trackTotalHits(true)
.from(searchOptions.getOffset())
.size(searchOptions.getLimit());
BoolQueryBuilder esQuery = boolQuery();
esQuery.filter(authorizationTypeSupport.createQueryFilter());
setNullable(query.getQuery(), q -> {
ComponentTextSearchQuery componentTextSearchQuery = ComponentTextSearchQuery.builder()
.setQueryText(q)
.setFieldKey(FIELD_KEY)
.setFieldName(FIELD_NAME)
.build();
esQuery.must(ComponentTextSearchQueryFactory.createQuery(componentTextSearchQuery, ComponentTextSearchFeatureRepertoire.values()));
});
setEmptiable(query.getQualifiers(), q -> esQuery.must(termsQuery(FIELD_QUALIFIER, q)));
source.sort(SORTABLE_ANALYZER.subField(FIELD_NAME), SortOrder.ASC);
source.query(esQuery);
SearchRequest request = EsClient.prepareSearch(TYPE_COMPONENT.getMainType())
.source(source);
return new SearchIdResult<>(client.search(request), id -> id, system2.getDefaultTimeZone().toZoneId());
}
public ComponentIndexResults searchSuggestions(SuggestionQuery query) {
return searchSuggestions(query, ComponentTextSearchFeatureRepertoire.values());
}
@VisibleForTesting
ComponentIndexResults searchSuggestions(SuggestionQuery query, ComponentTextSearchFeature... features) {
Collection<String> qualifiers = query.getQualifiers();
if (qualifiers.isEmpty()) {
return ComponentIndexResults.newBuilder().build();
}
SearchSourceBuilder source = new SearchSourceBuilder()
.query(createQuery(query, features))
.aggregation(createAggregation(query))
// the search hits are part of the aggregations
.size(0);
SearchRequest request = EsClient.prepareSearch(TYPE_COMPONENT.getMainType())
.source(source);
SearchResponse response = client.search(request);
return aggregationsToQualifiers(response);
}
private static HighlightBuilder.Field createHighlighterField() {
HighlightBuilder.Field field = new HighlightBuilder.Field(FIELD_NAME);
field.highlighterType("fvh");
field.matchedFields(
Stream.concat(
Stream.of(FIELD_NAME),
Arrays
.stream(NAME_ANALYZERS)
.map(a -> a.subField(FIELD_NAME)))
.toArray(String[]::new));
return field;
}
private static FiltersAggregationBuilder createAggregation(SuggestionQuery query) {
return AggregationBuilders.filters(
FILTERS_AGGREGATION_NAME,
query.getQualifiers().stream().map(q -> new KeyedFilter(q, termQuery(FIELD_QUALIFIER, q))).toArray(KeyedFilter[]::new))
.subAggregation(createSubAggregation(query));
}
private static TopHitsAggregationBuilder createSubAggregation(SuggestionQuery query) {
return AggregationBuilders.topHits(DOCS_AGGREGATION_NAME)
.highlighter(new HighlightBuilder()
.encoder("html")
.preTags("<mark>")
.postTags("</mark>")
.field(createHighlighterField()))
.from(query.getSkip())
.size(query.getLimit())
.sort(new ScoreSortBuilder())
.sort(new FieldSortBuilder(ComponentIndexDefinition.FIELD_NAME))
.fetchSource(false);
}
private QueryBuilder createQuery(SuggestionQuery query, ComponentTextSearchFeature... features) {
BoolQueryBuilder esQuery = boolQuery();
esQuery.filter(termQuery(FIELD_INDEX_TYPE, TYPE_COMPONENT.getName()));
esQuery.filter(authorizationTypeSupport.createQueryFilter());
ComponentTextSearchQuery componentTextSearchQuery = ComponentTextSearchQuery.builder()
.setQueryText(query.getQuery())
.setFieldKey(FIELD_KEY)
.setFieldName(FIELD_NAME)
.setRecentlyBrowsedKeys(query.getRecentlyBrowsedKeys())
.setFavoriteKeys(query.getFavoriteKeys())
.build();
return esQuery.must(ComponentTextSearchQueryFactory.createQuery(componentTextSearchQuery, features));
}
private static ComponentIndexResults aggregationsToQualifiers(SearchResponse response) {
ParsedFilters filtersAgg = response.getAggregations().get(FILTERS_AGGREGATION_NAME);
List<ParsedFilters.ParsedBucket> buckets = (List<ParsedFilters.ParsedBucket>) filtersAgg.getBuckets();
return ComponentIndexResults.newBuilder()
.setQualifiers(
buckets.stream().map(ComponentIndex::bucketToQualifier))
.build();
}
private static ComponentHitsPerQualifier bucketToQualifier(ParsedFilters.ParsedBucket bucket) {
ParsedTopHits docs = bucket.getAggregations().get(DOCS_AGGREGATION_NAME);
SearchHits hitList = docs.getHits();
SearchHit[] hits = hitList.getHits();
return new ComponentHitsPerQualifier(bucket.getKey(), ComponentHit.fromSearchHits(hits), getTotalHits(hitList.getTotalHits()).value);
}
private static TotalHits getTotalHits(@Nullable TotalHits totalHits) {
return ofNullable(totalHits).orElseThrow(() -> new IllegalStateException("Could not get total hits of search results"));
}
private static <T> void setNullable(@Nullable T parameter, Consumer<T> consumer) {
if (parameter != null) {
consumer.accept(parameter);
}
}
private static <T> void setEmptiable(Collection<T> parameter, Consumer<Collection<T>> consumer) {
if (!parameter.isEmpty()) {
consumer.accept(parameter);
}
}
}
| 9,560 | 42.857798 | 137 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/component/index/ComponentIndexResults.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.component.index;
import java.util.List;
import java.util.stream.Stream;
import static java.util.Collections.emptyList;
import static java.util.Objects.requireNonNull;
public class ComponentIndexResults {
private final List<ComponentHitsPerQualifier> qualifiers;
private ComponentIndexResults(Builder builder) {
this.qualifiers = requireNonNull(builder.qualifiers);
}
public Stream<ComponentHitsPerQualifier> getQualifiers() {
return qualifiers.stream();
}
public boolean isEmpty() {
return qualifiers.isEmpty();
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
private List<ComponentHitsPerQualifier> qualifiers = emptyList();
private Builder() {
}
public Builder setQualifiers(Stream<ComponentHitsPerQualifier> qualifiers) {
this.qualifiers = qualifiers.toList();
return this;
}
public ComponentIndexResults build() {
return new ComponentIndexResults(this);
}
}
}
| 1,874 | 27.846154 | 80 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/component/index/ComponentQuery.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.component.index;
import java.util.Collection;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import static java.util.Collections.emptySet;
import static java.util.Collections.unmodifiableCollection;
public class ComponentQuery {
private final String query;
private final Collection<String> qualifiers;
private ComponentQuery(Builder builder) {
this.query = builder.query;
this.qualifiers = builder.qualifiers;
}
@CheckForNull
public String getQuery() {
return query;
}
public Collection<String> getQualifiers() {
return qualifiers;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String query;
private Collection<String> qualifiers = emptySet();
private Builder() {
// enforce static factory method
}
public Builder setQuery(@Nullable String query) {
this.query = query;
return this;
}
public Builder setQualifiers(Collection<String> qualifiers) {
this.qualifiers = unmodifiableCollection(qualifiers);
return this;
}
public ComponentQuery build() {
return new ComponentQuery(this);
}
}
}
| 2,065 | 26.918919 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/component/index/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.component.index;
import javax.annotation.ParametersAreNonnullByDefault;
| 972 | 39.541667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/es/EsIndexSyncInProgressException.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.es;
import org.sonar.server.es.IndexType.IndexMainType;
import org.sonar.server.exceptions.ServerException;
public class EsIndexSyncInProgressException extends ServerException {
private final IndexMainType indexType;
public EsIndexSyncInProgressException(IndexMainType indexType, String message) {
super(503, message);
this.indexType = indexType;
}
public IndexMainType getIndexType() {
return indexType;
}
}
| 1,304 | 33.342105 | 82 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/es/IndexCreator.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.es;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest;
import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.PutMappingRequest;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.common.settings.Settings;
import org.sonar.api.Startable;
import org.sonar.api.server.ServerSide;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.server.es.metadata.EsDbCompatibility;
import org.sonar.server.es.metadata.MetadataIndex;
import org.sonar.server.es.metadata.MetadataIndexDefinition;
import org.sonar.server.es.newindex.BuiltIndex;
import org.sonar.server.es.newindex.NewIndex;
import static org.sonar.server.es.metadata.MetadataIndexDefinition.DESCRIPTOR;
import static org.sonar.server.es.metadata.MetadataIndexDefinition.TYPE_METADATA;
/**
* Creates/deletes all indices in Elasticsearch during server startup.
*/
@ServerSide
public class IndexCreator implements Startable {
private static final Logger LOGGER = LoggerFactory.getLogger(IndexCreator.class);
private final MetadataIndexDefinition metadataIndexDefinition;
private final MetadataIndex metadataIndex;
private final EsClient client;
private final IndexDefinitions definitions;
private final EsDbCompatibility esDbCompatibility;
public IndexCreator(EsClient client, IndexDefinitions definitions, MetadataIndexDefinition metadataIndexDefinition,
MetadataIndex metadataIndex, EsDbCompatibility esDbCompatibility) {
this.client = client;
this.definitions = definitions;
this.metadataIndexDefinition = metadataIndexDefinition;
this.metadataIndex = metadataIndex;
this.esDbCompatibility = esDbCompatibility;
}
@Override
public void start() {
// create the "metadata" index first
IndexType.IndexMainType metadataMainType = TYPE_METADATA;
if (!client.indexExists(new GetIndexRequest(metadataMainType.getIndex().getName()))) {
IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext();
metadataIndexDefinition.define(context);
NewIndex index = context.getIndices().values().iterator().next();
createIndex(index.build(), false);
} else {
ensureWritable(metadataMainType);
}
checkDbCompatibility(definitions.getIndices().values());
// create indices that do not exist or that have a new definition (different mapping, cluster enabled, ...)
definitions.getIndices().values().stream()
.filter(i -> !i.getMainType().equals(metadataMainType))
.forEach(index -> {
boolean exists = client.indexExists(new GetIndexRequest(index.getMainType().getIndex().getName()));
if (!exists) {
createIndex(index, true);
} else if (hasDefinitionChange(index)) {
updateIndex(index);
} else {
ensureWritable(index.getMainType());
}
});
}
private void ensureWritable(IndexType.IndexMainType mainType) {
if (isReadOnly(mainType)) {
removeReadOnly(mainType);
}
}
private boolean isReadOnly(IndexType.IndexMainType mainType) {
String indexName = mainType.getIndex().getName();
String readOnly = client.getSettings(new GetSettingsRequest().indices(indexName))
.getSetting(indexName, "index.blocks.read_only_allow_delete");
return "true".equalsIgnoreCase(readOnly);
}
private void removeReadOnly(IndexType.IndexMainType mainType) {
LOGGER.info("Index [{}] is read-only. Making it writable...", mainType.getIndex().getName());
String indexName = mainType.getIndex().getName();
Settings.Builder builder = Settings.builder();
builder.putNull("index.blocks.read_only_allow_delete");
client.putSettings(new UpdateSettingsRequest().indices(indexName).settings(builder.build()));
}
@Override
public void stop() {
// nothing to do
}
private void createIndex(BuiltIndex<?> builtIndex, boolean useMetadata) {
Index index = builtIndex.getMainType().getIndex();
LOGGER.info(String.format("Create index [%s]", index.getName()));
Settings.Builder settings = Settings.builder();
settings.put(builtIndex.getSettings());
if (useMetadata) {
metadataIndex.setHash(index, IndexDefinitionHash.of(builtIndex));
metadataIndex.setInitialized(builtIndex.getMainType(), false);
builtIndex.getRelationTypes().forEach(relationType -> metadataIndex.setInitialized(relationType, false));
}
CreateIndexResponse indexResponse = client.create(new CreateIndexRequest(index.getName()).settings((settings)));
if (!indexResponse.isAcknowledged()) {
throw new IllegalStateException("Failed to create index [" + index.getName() + "]");
}
client.waitForStatus(ClusterHealthStatus.YELLOW);
LOGGER.info("Create mapping {}", builtIndex.getMainType().getIndex().getName());
AcknowledgedResponse mappingResponse = client.putMapping(new PutMappingRequest(builtIndex.getMainType().getIndex().getName())
.source(builtIndex.getAttributes()));
if (!mappingResponse.isAcknowledged()) {
throw new IllegalStateException("Failed to create mapping " + builtIndex.getMainType().getIndex().getName());
}
client.waitForStatus(ClusterHealthStatus.YELLOW);
}
private void deleteIndex(String indexName) {
client.deleteIndex(new DeleteIndexRequest(indexName));
}
private void updateIndex(BuiltIndex<?> index) {
String indexName = index.getMainType().getIndex().getName();
LOGGER.info("Delete Elasticsearch index {} (structure changed)", indexName);
deleteIndex(indexName);
createIndex(index, true);
}
private boolean hasDefinitionChange(BuiltIndex<?> index) {
return metadataIndex.getHash(index.getMainType().getIndex())
.map(hash -> {
String defHash = IndexDefinitionHash.of(index);
return !StringUtils.equals(hash, defHash);
}).orElse(true);
}
private void checkDbCompatibility(Collection<BuiltIndex> definitions) {
List<String> existingIndices = loadExistingIndicesExceptMetadata(definitions);
if (!existingIndices.isEmpty()) {
boolean delete = false;
if (!esDbCompatibility.hasSameDbVendor()) {
LOGGER.info("Delete Elasticsearch indices (DB vendor changed)");
delete = true;
}
if (delete) {
existingIndices.forEach(this::deleteIndex);
}
}
esDbCompatibility.markAsCompatible();
}
private List<String> loadExistingIndicesExceptMetadata(Collection<BuiltIndex> definitions) {
Set<String> definedNames = definitions.stream()
.map(t -> t.getMainType().getIndex().getName())
.collect(Collectors.toSet());
return Arrays.stream(client.getIndex(new GetIndexRequest("_all")).getIndices())
.filter(definedNames::contains)
.filter(index -> !DESCRIPTOR.getName().equals(index))
.toList();
}
}
| 8,272 | 39.553922 | 129 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/es/IndexDefinitions.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.es;
import java.util.HashMap;
import java.util.Map;
import org.sonar.api.Startable;
import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
import org.sonar.server.es.newindex.BuiltIndex;
import org.sonar.server.es.newindex.NewIndex;
/**
* This class collects definitions of all Elasticsearch indices during server startup
*/
@ServerSide
public class IndexDefinitions implements Startable {
private final Map<String, BuiltIndex> byKey = new HashMap<>();
private final IndexDefinition[] defs;
private final Configuration config;
public IndexDefinitions(IndexDefinition[] defs, Configuration config) {
this.defs = defs;
this.config = config;
}
public Map<String, BuiltIndex> getIndices() {
return byKey;
}
@Override
public void start() {
// collect definitions
IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext();
if (!config.getBoolean("sonar.internal.es.disableIndexes").orElse(false)) {
for (IndexDefinition definition : defs) {
definition.define(context);
}
for (Map.Entry<String, NewIndex> entry : context.getIndices().entrySet()) {
byKey.put(entry.getKey(), entry.getValue().build());
}
}
}
@Override
public void stop() {
// nothing to do
}
}
| 2,193 | 30.342857 | 98 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/es/RecoveryIndexer.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.es;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ListMultimap;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.math.RandomUtils;
import org.sonar.api.Startable;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.es.EsQueueDto;
import static java.lang.String.format;
public class RecoveryIndexer implements Startable {
private static final Logger LOGGER = Loggers.get(RecoveryIndexer.class);
private static final String LOG_PREFIX = "Elasticsearch recovery - ";
private static final String PROPERTY_INITIAL_DELAY = "sonar.search.recovery.initialDelayInMs";
private static final String PROPERTY_DELAY = "sonar.search.recovery.delayInMs";
private static final String PROPERTY_MIN_AGE = "sonar.search.recovery.minAgeInMs";
private static final String PROPERTY_LOOP_LIMIT = "sonar.search.recovery.loopLimit";
private static final long DEFAULT_DELAY_IN_MS = 5L * 60 * 1000;
private static final long DEFAULT_MIN_AGE_IN_MS = 5L * 60 * 1000;
private static final int DEFAULT_LOOP_LIMIT = 10_000;
private static final double CIRCUIT_BREAKER_IN_PERCENT = 0.7;
private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1,
new ThreadFactoryBuilder()
.setPriority(Thread.MIN_PRIORITY)
.setNameFormat("RecoveryIndexer-%d")
.build());
private final System2 system2;
private final Configuration config;
private final DbClient dbClient;
private final Map<String, Indexer> indexersByType;
private final long minAgeInMs;
private final long loopLimit;
public RecoveryIndexer(System2 system2, Configuration config, DbClient dbClient, ResilientIndexer... indexers) {
this.system2 = system2;
this.config = config;
this.dbClient = dbClient;
this.indexersByType = new HashMap<>();
Arrays.stream(indexers).forEach(i -> i.getIndexTypes().forEach(indexType -> indexersByType.put(indexType.format(), new Indexer(indexType, i))));
this.minAgeInMs = getSetting(PROPERTY_MIN_AGE, DEFAULT_MIN_AGE_IN_MS);
this.loopLimit = getSetting(PROPERTY_LOOP_LIMIT, DEFAULT_LOOP_LIMIT);
}
private record Indexer(IndexType indexType, ResilientIndexer delegate) {
}
@Override
public void start() {
long delayInMs = getSetting(PROPERTY_DELAY, DEFAULT_DELAY_IN_MS);
// in the cluster mode, avoid (but not prevent!) simultaneous executions of recovery
// indexers so that a document is not handled multiple times.
long initialDelayInMs = getSetting(PROPERTY_INITIAL_DELAY, RandomUtils.nextInt(1 + (int) (delayInMs / 2)));
executorService.scheduleAtFixedRate(
this::recover,
initialDelayInMs,
delayInMs,
TimeUnit.MILLISECONDS);
}
@Override
public void stop() {
try {
executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOGGER.error(LOG_PREFIX + "Unable to stop recovery indexer in timely fashion", e);
executorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
@VisibleForTesting
void recover() {
try (DbSession dbSession = dbClient.openSession(false)) {
Profiler profiler = Profiler.create(LOGGER).start();
long beforeDate = system2.now() - minAgeInMs;
IndexingResult result = new IndexingResult();
Collection<EsQueueDto> items = dbClient.esQueueDao().selectForRecovery(dbSession, beforeDate, loopLimit);
while (!items.isEmpty()) {
IndexingResult loopResult = new IndexingResult();
groupItemsByDocType(items).asMap().forEach((type, typeItems) -> loopResult.add(doIndex(dbSession, type, typeItems)));
result.add(loopResult);
if (loopResult.getSuccessRatio() <= CIRCUIT_BREAKER_IN_PERCENT) {
LOGGER.error(LOG_PREFIX + "too many failures [{}/{} documents], waiting for next run", loopResult.getFailures(), loopResult.getTotal());
break;
}
if (loopResult.getTotal() == 0L) {
break;
}
items = dbClient.esQueueDao().selectForRecovery(dbSession, beforeDate, loopLimit);
}
if (result.getTotal() > 0L) {
profiler.stopInfo(LOG_PREFIX + format("%d documents processed [%d failures]", result.getTotal(), result.getFailures()));
}
} catch (Throwable t) {
LOGGER.error(LOG_PREFIX + "fail to recover documents", t);
}
}
private IndexingResult doIndex(DbSession dbSession, String docType, Collection<EsQueueDto> typeItems) {
LOGGER.trace(LOG_PREFIX + "processing {} [{}]", typeItems.size(), docType);
Indexer indexer = indexersByType.get(docType);
if (indexer == null) {
LOGGER.error(LOG_PREFIX + "ignore {} items with unsupported type [{}]", typeItems.size(), docType);
return new IndexingResult();
}
return indexer.delegate.index(dbSession, typeItems);
}
private static ListMultimap<String, EsQueueDto> groupItemsByDocType(Collection<EsQueueDto> items) {
return items.stream().collect(MoreCollectors.index(EsQueueDto::getDocType));
}
private long getSetting(String key, long defaultValue) {
long val = config.getLong(key).orElse(defaultValue);
LOGGER.debug(LOG_PREFIX + "{}={}", key, val);
return val;
}
}
| 6,667 | 39.412121 | 148 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/es/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.es;
import javax.annotation.ParametersAreNonnullByDefault;
| 959 | 39 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/es/metadata/EsDbCompatibility.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.es.metadata;
/**
* Checks when Elasticsearch indices must be dropped because
* of changes in database
*/
public interface EsDbCompatibility {
/**
* Whether the effective DB vendor equals the vendor
* registered in Elasticsearch metadata.
* Return {@code false} if at least one of the values is absent
*/
boolean hasSameDbVendor();
/**
* Stores in Elasticsearch the metadata about database
*/
void markAsCompatible();
}
| 1,319 | 32 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/es/metadata/EsDbCompatibilityImpl.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.es.metadata;
import java.util.Optional;
import org.sonar.db.DbClient;
public class EsDbCompatibilityImpl implements EsDbCompatibility {
private final DbClient dbClient;
private final MetadataIndex metadataIndex;
public EsDbCompatibilityImpl(DbClient dbClient, MetadataIndex metadataIndex) {
this.dbClient = dbClient;
this.metadataIndex = metadataIndex;
}
@Override
public boolean hasSameDbVendor() {
Optional<String> registeredDbVendor = metadataIndex.getDbVendor();
return registeredDbVendor.isPresent() && registeredDbVendor.get().equals(getDbVendor());
}
@Override
public void markAsCompatible() {
if (!hasSameDbVendor()) {
metadataIndex.setDbMetadata(getDbVendor());
}
}
private String getDbVendor() {
return dbClient.getDatabase().getDialect().getId();
}
}
| 1,695 | 31.615385 | 92 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/es/metadata/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.es.metadata;
import javax.annotation.ParametersAreNonnullByDefault;
| 968 | 39.375 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/issue/index/IssueIndex.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.issue.index;
import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.indices.TermsLookup;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.HasAggregations;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilter;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.LongBounds;
import org.elasticsearch.search.aggregations.bucket.terms.IncludeExclude;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Min;
import org.elasticsearch.search.aggregations.metrics.ParsedMax;
import org.elasticsearch.search.aggregations.metrics.ParsedValueCount;
import org.elasticsearch.search.aggregations.metrics.SumAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.joda.time.Duration;
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.api.server.rule.RulesDefinition.OwaspTop10Version;
import org.sonar.api.server.rule.RulesDefinition.PciDssVersion;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.EsUtils;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.es.Sorting;
import org.sonar.server.es.searchrequest.RequestFiltersComputer;
import org.sonar.server.es.searchrequest.RequestFiltersComputer.AllFilters;
import org.sonar.server.es.searchrequest.SimpleFieldTopAggregationDefinition;
import org.sonar.server.es.searchrequest.SubAggregationHelper;
import org.sonar.server.es.searchrequest.TopAggregationDefinition;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.SimpleFieldFilterScope;
import org.sonar.server.es.searchrequest.TopAggregationHelper;
import org.sonar.server.issue.index.IssueQuery.PeriodStart;
import org.sonar.server.permission.index.AuthorizationDoc;
import org.sonar.server.permission.index.WebAuthorizationTypeSupport;
import org.sonar.server.security.SecurityStandards;
import org.sonar.server.security.SecurityStandards.PciDss;
import org.sonar.server.security.SecurityStandards.SQCategory;
import org.sonar.server.user.UserSession;
import org.sonar.server.view.index.ViewIndexDefinition;
import org.springframework.util.CollectionUtils;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toCollection;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.prefixQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.api.rules.RuleType.VULNERABILITY;
import static org.sonar.server.es.EsUtils.escapeSpecialRegexChars;
import static org.sonar.server.es.IndexType.FIELD_INDEX_TYPE;
import static org.sonar.server.es.searchrequest.TopAggregationDefinition.NON_STICKY;
import static org.sonar.server.es.searchrequest.TopAggregationDefinition.STICKY;
import static org.sonar.server.es.searchrequest.TopAggregationHelper.NO_EXTRA_FILTER;
import static org.sonar.server.es.searchrequest.TopAggregationHelper.NO_OTHER_SUBAGGREGATION;
import static org.sonar.server.issue.index.IssueIndex.Facet.ASSIGNED_TO_ME;
import static org.sonar.server.issue.index.IssueIndex.Facet.ASSIGNEES;
import static org.sonar.server.issue.index.IssueIndex.Facet.AUTHOR;
import static org.sonar.server.issue.index.IssueIndex.Facet.CODE_VARIANTS;
import static org.sonar.server.issue.index.IssueIndex.Facet.CREATED_AT;
import static org.sonar.server.issue.index.IssueIndex.Facet.CWE;
import static org.sonar.server.issue.index.IssueIndex.Facet.DIRECTORIES;
import static org.sonar.server.issue.index.IssueIndex.Facet.FILES;
import static org.sonar.server.issue.index.IssueIndex.Facet.LANGUAGES;
import static org.sonar.server.issue.index.IssueIndex.Facet.OWASP_ASVS_40;
import static org.sonar.server.issue.index.IssueIndex.Facet.OWASP_TOP_10;
import static org.sonar.server.issue.index.IssueIndex.Facet.OWASP_TOP_10_2021;
import static org.sonar.server.issue.index.IssueIndex.Facet.PCI_DSS_32;
import static org.sonar.server.issue.index.IssueIndex.Facet.PCI_DSS_40;
import static org.sonar.server.issue.index.IssueIndex.Facet.PROJECT_UUIDS;
import static org.sonar.server.issue.index.IssueIndex.Facet.RESOLUTIONS;
import static org.sonar.server.issue.index.IssueIndex.Facet.RULES;
import static org.sonar.server.issue.index.IssueIndex.Facet.SANS_TOP_25;
import static org.sonar.server.issue.index.IssueIndex.Facet.SCOPES;
import static org.sonar.server.issue.index.IssueIndex.Facet.SEVERITIES;
import static org.sonar.server.issue.index.IssueIndex.Facet.SONARSOURCE_SECURITY;
import static org.sonar.server.issue.index.IssueIndex.Facet.STATUSES;
import static org.sonar.server.issue.index.IssueIndex.Facet.TAGS;
import static org.sonar.server.issue.index.IssueIndex.Facet.TYPES;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_ASSIGNEE_UUID;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_AUTHOR_LOGIN;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_BRANCH_UUID;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_CODE_VARIANTS;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_COMPONENT_UUID;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_CWE;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_DIRECTORY_PATH;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_EFFORT;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_FILE_PATH;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_FUNC_CLOSED_AT;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_FUNC_CREATED_AT;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_FUNC_UPDATED_AT;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_IS_MAIN_BRANCH;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_KEY;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_LANGUAGE;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_LINE;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_NEW_CODE_REFERENCE;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_OWASP_ASVS_40;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_OWASP_TOP_10;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_OWASP_TOP_10_2021;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_PCI_DSS_32;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_PCI_DSS_40;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_PROJECT_UUID;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_RESOLUTION;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_RULE_UUID;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_SANS_TOP_25;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_SCOPE;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_SEVERITY;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_SEVERITY_VALUE;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_SQ_SECURITY_CATEGORY;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_STATUS;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_TAGS;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_TYPE;
import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_VULNERABILITY_PROBABILITY;
import static org.sonar.server.issue.index.IssueIndexDefinition.TYPE_ISSUE;
import static org.sonar.server.security.SecurityReviewRating.computePercent;
import static org.sonar.server.security.SecurityReviewRating.computeRating;
import static org.sonar.server.security.SecurityStandards.CWES_BY_CWE_TOP_25;
import static org.sonar.server.security.SecurityStandards.OWASP_ASVS_40_REQUIREMENTS_BY_LEVEL;
import static org.sonar.server.view.index.ViewIndexDefinition.TYPE_VIEW;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.FACET_MODE_EFFORT;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ASSIGNEES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_AUTHOR;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CODE_VARIANTS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_AT;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CWE;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_DIRECTORIES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_FILES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_LANGUAGES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_OWASP_ASVS_40;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_OWASP_TOP_10;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_OWASP_TOP_10_2021;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_PCI_DSS_32;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_PCI_DSS_40;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_RESOLUTIONS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_RULES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SANS_TOP_25;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SCOPES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SEVERITIES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SONARSOURCE_SECURITY;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_STATUSES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_TAGS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_TYPES;
/**
* The unique entry-point to interact with Elasticsearch index "issues".
* All the requests are listed here.
*/
public class IssueIndex {
public static final String FACET_PROJECTS = "projects";
public static final String FACET_ASSIGNED_TO_ME = "assigned_to_me";
private static final int DEFAULT_FACET_SIZE = 15;
private static final int MAX_FACET_SIZE = 100;
private static final String AGG_VULNERABILITIES = "vulnerabilities";
private static final String AGG_SEVERITIES = "severities";
private static final String AGG_TO_REVIEW_SECURITY_HOTSPOTS = "toReviewSecurityHotspots";
private static final String AGG_IN_REVIEW_SECURITY_HOTSPOTS = "inReviewSecurityHotspots";
private static final String AGG_REVIEWED_SECURITY_HOTSPOTS = "reviewedSecurityHotspots";
private static final String AGG_DISTRIBUTION = "distribution";
private static final BoolQueryBuilder NON_RESOLVED_VULNERABILITIES_FILTER = boolQuery()
.filter(termQuery(FIELD_ISSUE_TYPE, VULNERABILITY.name()))
.mustNot(existsQuery(FIELD_ISSUE_RESOLUTION));
private static final BoolQueryBuilder IN_REVIEW_HOTSPOTS_FILTER = boolQuery()
.filter(termQuery(FIELD_ISSUE_TYPE, SECURITY_HOTSPOT.name()))
.filter(termQuery(FIELD_ISSUE_STATUS, Issue.STATUS_IN_REVIEW))
.mustNot(existsQuery(FIELD_ISSUE_RESOLUTION));
private static final BoolQueryBuilder TO_REVIEW_HOTSPOTS_FILTER = boolQuery()
.filter(termQuery(FIELD_ISSUE_TYPE, SECURITY_HOTSPOT.name()))
.filter(termQuery(FIELD_ISSUE_STATUS, Issue.STATUS_TO_REVIEW))
.mustNot(existsQuery(FIELD_ISSUE_RESOLUTION));
private static final BoolQueryBuilder REVIEWED_HOTSPOTS_FILTER = boolQuery()
.filter(termQuery(FIELD_ISSUE_TYPE, SECURITY_HOTSPOT.name()))
.filter(termQuery(FIELD_ISSUE_STATUS, Issue.STATUS_REVIEWED))
.filter(termQuery(FIELD_ISSUE_RESOLUTION, Issue.RESOLUTION_FIXED));
private static final Object[] NO_SELECTED_VALUES = {0};
private static final SimpleFieldTopAggregationDefinition EFFORT_TOP_AGGREGATION = new SimpleFieldTopAggregationDefinition(FIELD_ISSUE_EFFORT, NON_STICKY);
public enum Facet {
SEVERITIES(PARAM_SEVERITIES, FIELD_ISSUE_SEVERITY, STICKY, Severity.ALL.size()),
STATUSES(PARAM_STATUSES, FIELD_ISSUE_STATUS, STICKY, Issue.STATUSES.size()),
// Resolutions facet returns one more element than the number of resolutions to take into account unresolved issues
RESOLUTIONS(PARAM_RESOLUTIONS, FIELD_ISSUE_RESOLUTION, STICKY, Issue.RESOLUTIONS.size() + 1),
TYPES(PARAM_TYPES, FIELD_ISSUE_TYPE, STICKY, RuleType.values().length),
SCOPES(PARAM_SCOPES, FIELD_ISSUE_SCOPE, STICKY, MAX_FACET_SIZE),
LANGUAGES(PARAM_LANGUAGES, FIELD_ISSUE_LANGUAGE, STICKY, MAX_FACET_SIZE),
RULES(PARAM_RULES, FIELD_ISSUE_RULE_UUID, STICKY, MAX_FACET_SIZE),
TAGS(PARAM_TAGS, FIELD_ISSUE_TAGS, STICKY, MAX_FACET_SIZE),
AUTHOR(PARAM_AUTHOR, FIELD_ISSUE_AUTHOR_LOGIN, STICKY, MAX_FACET_SIZE),
PROJECT_UUIDS(FACET_PROJECTS, FIELD_ISSUE_PROJECT_UUID, STICKY, MAX_FACET_SIZE),
FILES(PARAM_FILES, FIELD_ISSUE_FILE_PATH, STICKY, MAX_FACET_SIZE),
DIRECTORIES(PARAM_DIRECTORIES, FIELD_ISSUE_DIRECTORY_PATH, STICKY, MAX_FACET_SIZE),
ASSIGNEES(PARAM_ASSIGNEES, FIELD_ISSUE_ASSIGNEE_UUID, STICKY, MAX_FACET_SIZE),
ASSIGNED_TO_ME(FACET_ASSIGNED_TO_ME, FIELD_ISSUE_ASSIGNEE_UUID, STICKY, 1),
PCI_DSS_32(PARAM_PCI_DSS_32, FIELD_ISSUE_PCI_DSS_32, STICKY, DEFAULT_FACET_SIZE),
PCI_DSS_40(PARAM_PCI_DSS_40, FIELD_ISSUE_PCI_DSS_40, STICKY, DEFAULT_FACET_SIZE),
OWASP_ASVS_40(PARAM_OWASP_ASVS_40, FIELD_ISSUE_OWASP_ASVS_40, STICKY, DEFAULT_FACET_SIZE),
OWASP_TOP_10(PARAM_OWASP_TOP_10, FIELD_ISSUE_OWASP_TOP_10, STICKY, DEFAULT_FACET_SIZE),
OWASP_TOP_10_2021(PARAM_OWASP_TOP_10_2021, FIELD_ISSUE_OWASP_TOP_10_2021, STICKY, DEFAULT_FACET_SIZE),
SANS_TOP_25(PARAM_SANS_TOP_25, FIELD_ISSUE_SANS_TOP_25, STICKY, DEFAULT_FACET_SIZE),
CWE(PARAM_CWE, FIELD_ISSUE_CWE, STICKY, DEFAULT_FACET_SIZE),
CREATED_AT(PARAM_CREATED_AT, FIELD_ISSUE_FUNC_CREATED_AT, NON_STICKY),
SONARSOURCE_SECURITY(PARAM_SONARSOURCE_SECURITY, FIELD_ISSUE_SQ_SECURITY_CATEGORY, STICKY, DEFAULT_FACET_SIZE),
CODE_VARIANTS(PARAM_CODE_VARIANTS, FIELD_ISSUE_CODE_VARIANTS, STICKY, MAX_FACET_SIZE);
private final String name;
private final SimpleFieldTopAggregationDefinition topAggregation;
private final Integer numberOfTerms;
Facet(String name, String fieldName, boolean sticky, int numberOfTerms) {
this.name = name;
this.topAggregation = new SimpleFieldTopAggregationDefinition(fieldName, sticky);
this.numberOfTerms = numberOfTerms;
}
Facet(String name, String fieldName, boolean sticky) {
this.name = name;
this.topAggregation = new SimpleFieldTopAggregationDefinition(fieldName, sticky);
this.numberOfTerms = null;
}
public String getName() {
return name;
}
public String getFieldName() {
return topAggregation.getFilterScope().getFieldName();
}
public TopAggregationDefinition.FilterScope getFilterScope() {
return topAggregation.getFilterScope();
}
public SimpleFieldTopAggregationDefinition getTopAggregationDef() {
return topAggregation;
}
public int getNumberOfTerms() {
checkState(numberOfTerms != null, "numberOfTerms should have been provided in constructor");
return numberOfTerms;
}
}
private static final Map<String, Facet> FACETS_BY_NAME = Arrays.stream(Facet.values())
.collect(Collectors.toMap(Facet::getName, Function.identity()));
private static final String SUBSTRING_MATCH_REGEXP = ".*%s.*";
// TODO to be documented
// TODO move to Facets ?
private static final String FACET_SUFFIX_MISSING = "_missing";
private static final String IS_ASSIGNED_FILTER = "__isAssigned";
private static final SumAggregationBuilder EFFORT_AGGREGATION = AggregationBuilders.sum(FACET_MODE_EFFORT).field(FIELD_ISSUE_EFFORT);
private static final BucketOrder EFFORT_AGGREGATION_ORDER = BucketOrder.aggregation(FACET_MODE_EFFORT, false);
private static final Duration TWENTY_DAYS = Duration.standardDays(20L);
private static final Duration TWENTY_WEEKS = Duration.standardDays(20L * 7L);
private static final Duration TWENTY_MONTHS = Duration.standardDays(20L * 30L);
private static final String AGG_COUNT = "count";
private final Sorting sorting;
private final EsClient client;
private final System2 system;
private final UserSession userSession;
private final WebAuthorizationTypeSupport authorizationTypeSupport;
public IssueIndex(EsClient client, System2 system, UserSession userSession, WebAuthorizationTypeSupport authorizationTypeSupport) {
this.client = client;
this.system = system;
this.userSession = userSession;
this.authorizationTypeSupport = authorizationTypeSupport;
this.sorting = new Sorting();
this.sorting.add(IssueQuery.SORT_BY_STATUS, FIELD_ISSUE_STATUS);
this.sorting.add(IssueQuery.SORT_BY_STATUS, FIELD_ISSUE_KEY);
this.sorting.add(IssueQuery.SORT_BY_SEVERITY, FIELD_ISSUE_SEVERITY_VALUE);
this.sorting.add(IssueQuery.SORT_BY_SEVERITY, FIELD_ISSUE_KEY);
this.sorting.add(IssueQuery.SORT_BY_CREATION_DATE, FIELD_ISSUE_FUNC_CREATED_AT);
this.sorting.add(IssueQuery.SORT_BY_CREATION_DATE, FIELD_ISSUE_KEY);
this.sorting.add(IssueQuery.SORT_BY_UPDATE_DATE, FIELD_ISSUE_FUNC_UPDATED_AT);
this.sorting.add(IssueQuery.SORT_BY_UPDATE_DATE, FIELD_ISSUE_KEY);
this.sorting.add(IssueQuery.SORT_BY_CLOSE_DATE, FIELD_ISSUE_FUNC_CLOSED_AT);
this.sorting.add(IssueQuery.SORT_BY_CLOSE_DATE, FIELD_ISSUE_KEY);
this.sorting.add(IssueQuery.SORT_BY_FILE_LINE, FIELD_ISSUE_PROJECT_UUID);
this.sorting.add(IssueQuery.SORT_BY_FILE_LINE, FIELD_ISSUE_FILE_PATH);
this.sorting.add(IssueQuery.SORT_BY_FILE_LINE, FIELD_ISSUE_LINE);
this.sorting.add(IssueQuery.SORT_BY_FILE_LINE, FIELD_ISSUE_SEVERITY_VALUE).reverse();
this.sorting.add(IssueQuery.SORT_BY_FILE_LINE, FIELD_ISSUE_KEY);
this.sorting.add(IssueQuery.SORT_HOTSPOTS, FIELD_ISSUE_VULNERABILITY_PROBABILITY).reverse();
this.sorting.add(IssueQuery.SORT_HOTSPOTS, FIELD_ISSUE_SQ_SECURITY_CATEGORY);
this.sorting.add(IssueQuery.SORT_HOTSPOTS, FIELD_ISSUE_RULE_UUID);
this.sorting.add(IssueQuery.SORT_HOTSPOTS, FIELD_ISSUE_PROJECT_UUID);
this.sorting.add(IssueQuery.SORT_HOTSPOTS, FIELD_ISSUE_FILE_PATH);
this.sorting.add(IssueQuery.SORT_HOTSPOTS, FIELD_ISSUE_LINE);
this.sorting.add(IssueQuery.SORT_HOTSPOTS, FIELD_ISSUE_KEY);
// by default order by created date, project, file, line and issue key (in order to be deterministic when same ms)
this.sorting.addDefault(FIELD_ISSUE_FUNC_CREATED_AT).reverse();
this.sorting.addDefault(FIELD_ISSUE_PROJECT_UUID);
this.sorting.addDefault(FIELD_ISSUE_FILE_PATH);
this.sorting.addDefault(FIELD_ISSUE_LINE);
this.sorting.addDefault(FIELD_ISSUE_KEY);
}
public SearchResponse search(IssueQuery query, SearchOptions options) {
SearchRequest requestBuilder = EsClient.prepareSearch(TYPE_ISSUE.getMainType());
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
requestBuilder.source(sourceBuilder);
configureSorting(query, sourceBuilder);
configurePagination(options, sourceBuilder);
configureRouting(query, options, requestBuilder);
AllFilters allFilters = createAllFilters(query);
RequestFiltersComputer filterComputer = newFilterComputer(options, allFilters);
configureTopAggregations(query, options, sourceBuilder, allFilters, filterComputer);
configureQuery(sourceBuilder, filterComputer);
configureTopFilters(sourceBuilder, filterComputer);
sourceBuilder.fetchSource(false)
.trackTotalHits(true);
return client.search(requestBuilder);
}
private void configureTopAggregations(IssueQuery query, SearchOptions options, SearchSourceBuilder esRequest, AllFilters allFilters, RequestFiltersComputer filterComputer) {
TopAggregationHelper aggregationHelper = newAggregationHelper(filterComputer, query);
configureTopAggregations(aggregationHelper, query, options, allFilters, esRequest);
}
private static void configureQuery(SearchSourceBuilder esRequest, RequestFiltersComputer filterComputer) {
QueryBuilder esQuery = filterComputer.getQueryFilters()
.map(t -> (QueryBuilder) boolQuery().must(matchAllQuery()).filter(t))
.orElse(matchAllQuery());
esRequest.query(esQuery);
}
private static void configureTopFilters(SearchSourceBuilder esRequest, RequestFiltersComputer filterComputer) {
filterComputer.getPostFilters().ifPresent(esRequest::postFilter);
}
/**
* Optimization - do not send ES request to all shards when scope is restricted
* to a set of projects. Because project UUID is used for routing, the request
* can be sent to only the shards containing the specified projects.
* Note that sticky facets may involve all projects, so this optimization must be
* disabled when facets are enabled.
*/
private static void configureRouting(IssueQuery query, SearchOptions options, SearchRequest searchRequest) {
Collection<String> uuids = query.projectUuids();
if (!uuids.isEmpty() && options.getFacets().isEmpty()) {
searchRequest.routing(uuids.stream().map(AuthorizationDoc::idOf).toArray(String[]::new));
}
}
private static void configurePagination(SearchOptions options, SearchSourceBuilder esSearch) {
esSearch.from(options.getOffset()).size(options.getLimit());
}
private AllFilters createAllFilters(IssueQuery query) {
AllFilters filters = RequestFiltersComputer.newAllFilters();
filters.addFilter("__indexType", new SimpleFieldFilterScope(FIELD_INDEX_TYPE), termQuery(FIELD_INDEX_TYPE, TYPE_ISSUE.getName()));
filters.addFilter("__authorization", new SimpleFieldFilterScope("parent"), createAuthorizationFilter());
// Issue is assigned Filter
if (Boolean.TRUE.equals(query.assigned())) {
filters.addFilter(IS_ASSIGNED_FILTER, Facet.ASSIGNEES.getFilterScope(), existsQuery(FIELD_ISSUE_ASSIGNEE_UUID));
} else if (Boolean.FALSE.equals(query.assigned())) {
filters.addFilter(IS_ASSIGNED_FILTER, ASSIGNEES.getFilterScope(), boolQuery().mustNot(existsQuery(FIELD_ISSUE_ASSIGNEE_UUID)));
}
// Issue is Resolved Filter
if (Boolean.TRUE.equals(query.resolved())) {
filters.addFilter("__isResolved", Facet.RESOLUTIONS.getFilterScope(), existsQuery(FIELD_ISSUE_RESOLUTION));
} else if (Boolean.FALSE.equals(query.resolved())) {
filters.addFilter("__isResolved", Facet.RESOLUTIONS.getFilterScope(), boolQuery().mustNot(existsQuery(FIELD_ISSUE_RESOLUTION)));
}
// Field Filters
filters.addFilter(FIELD_ISSUE_KEY, new SimpleFieldFilterScope(FIELD_ISSUE_KEY), createTermsFilter(FIELD_ISSUE_KEY, query.issueKeys()));
filters.addFilter(FIELD_ISSUE_ASSIGNEE_UUID, ASSIGNEES.getFilterScope(), createTermsFilter(FIELD_ISSUE_ASSIGNEE_UUID, query.assignees()));
filters.addFilter(FIELD_ISSUE_SCOPE, SCOPES.getFilterScope(), createTermsFilter(FIELD_ISSUE_SCOPE, query.scopes()));
filters.addFilter(FIELD_ISSUE_LANGUAGE, LANGUAGES.getFilterScope(), createTermsFilter(FIELD_ISSUE_LANGUAGE, query.languages()));
filters.addFilter(FIELD_ISSUE_TAGS, TAGS.getFilterScope(), createTermsFilter(FIELD_ISSUE_TAGS, query.tags()));
filters.addFilter(FIELD_ISSUE_TYPE, TYPES.getFilterScope(), createTermsFilter(FIELD_ISSUE_TYPE, query.types()));
filters.addFilter(
FIELD_ISSUE_RESOLUTION, RESOLUTIONS.getFilterScope(),
createTermsFilter(FIELD_ISSUE_RESOLUTION, query.resolutions()));
filters.addFilter(
FIELD_ISSUE_AUTHOR_LOGIN, AUTHOR.getFilterScope(),
createTermsFilter(FIELD_ISSUE_AUTHOR_LOGIN, query.authors()));
filters.addFilter(
FIELD_ISSUE_RULE_UUID, RULES.getFilterScope(), createTermsFilter(
FIELD_ISSUE_RULE_UUID,
query.ruleUuids()));
filters.addFilter(FIELD_ISSUE_STATUS, STATUSES.getFilterScope(), createTermsFilter(FIELD_ISSUE_STATUS, query.statuses()));
filters.addFilter(FIELD_ISSUE_CODE_VARIANTS, CODE_VARIANTS.getFilterScope(), createTermsFilter(FIELD_ISSUE_CODE_VARIANTS, query.codeVariants()));
// security category
addSecurityCategoryPrefixFilter(FIELD_ISSUE_PCI_DSS_32, PCI_DSS_32, query.pciDss32(), filters);
addSecurityCategoryPrefixFilter(FIELD_ISSUE_PCI_DSS_40, PCI_DSS_40, query.pciDss40(), filters);
addOwaspAsvsFilter(FIELD_ISSUE_OWASP_ASVS_40, OWASP_ASVS_40, query, filters);
addSecurityCategoryFilter(FIELD_ISSUE_OWASP_TOP_10, OWASP_TOP_10, query.owaspTop10(), filters);
addSecurityCategoryFilter(FIELD_ISSUE_OWASP_TOP_10_2021, OWASP_TOP_10_2021, query.owaspTop10For2021(), filters);
addSecurityCategoryFilter(FIELD_ISSUE_SANS_TOP_25, SANS_TOP_25, query.sansTop25(), filters);
addSecurityCategoryFilter(FIELD_ISSUE_CWE, CWE, query.cwe(), filters);
addSecurityCategoryFilter(FIELD_ISSUE_SQ_SECURITY_CATEGORY, SONARSOURCE_SECURITY, query.sonarsourceSecurity(), filters);
addSeverityFilter(query, filters);
addComponentRelatedFilters(query, filters);
addDatesFilter(filters, query);
addCreatedAfterByProjectsFilter(filters, query);
addNewCodeReferenceFilter(filters, query);
addNewCodeReferenceFilterByProjectsFilter(filters, query);
return filters;
}
private static void addOwaspAsvsFilter(String fieldName, Facet facet, IssueQuery query, AllFilters allFilters) {
if (!CollectionUtils.isEmpty(query.owaspAsvs40())) {
Set<String> requirements = calculateRequirementsForOwaspAsvs40Params(query);
QueryBuilder securityCategoryFilter = termsQuery(fieldName, requirements);
allFilters.addFilter(
fieldName,
facet.getFilterScope(),
boolQuery()
.must(securityCategoryFilter)
.must(termsQuery(FIELD_ISSUE_TYPE, VULNERABILITY.name(), SECURITY_HOTSPOT.name())));
}
}
private static Set<String> calculateRequirementsForOwaspAsvs40Params(IssueQuery query) {
int level = query.getOwaspAsvsLevel().orElse(3);
List<String> levelRequirements = OWASP_ASVS_40_REQUIREMENTS_BY_LEVEL.get(level);
return query.owaspAsvs40().stream()
.flatMap(value -> {
// it's a specific category required
if (value.contains(".")) {
return Stream.of(value).filter(levelRequirements::contains);
} else {
return SecurityStandards.getRequirementsForCategoryAndLevel(value, level).stream();
}
}).collect(Collectors.toSet());
}
private static void addSecurityCategoryFilter(String fieldName, Facet facet, Collection<String> values, AllFilters allFilters) {
QueryBuilder securityCategoryFilter = createTermsFilter(fieldName, values);
if (securityCategoryFilter != null) {
allFilters.addFilter(
fieldName,
facet.getFilterScope(),
boolQuery()
.must(securityCategoryFilter)
.must(termsQuery(FIELD_ISSUE_TYPE, VULNERABILITY.name(), SECURITY_HOTSPOT.name())));
}
}
/**
* <p>Builds the Elasticsearch boolean query to filter the PCI DSS categories.</p>
*
* <p>The PCI DSS security report handles all the subcategories as one level. This means that subcategory 1.1 doesn't include the issues from 1.1.1.
* Taking this into account, the search filter follows the same logic and uses prefix matching for top-level categories and exact matching for subcategories</p>
*
* <p>Example</p>
* <p>List of PCI DSS categories in issues: {1.5.8, 1.5.9, 1.6.7}
* <ul>
* <li>Search: {1}, returns {1.5.8, 1.5.9, 1.6.7}</li>
* <li>Search: {1.5.8}, returns {1.5.8}</li>
* <li>Search: {1.5}, returns {}</li>
* </ul>
* </p>
*
* @param fieldName The PCI DSS version, e.g. pciDss-3.2
* @param facet The facet used for the filter
* @param values The PCI DSS categories to search for
* @param allFilters Object that holds all the filters for the Elastic search call
*/
private static void addSecurityCategoryPrefixFilter(String fieldName, Facet facet, Collection<String> values, AllFilters allFilters) {
if (values.isEmpty()) {
return;
}
BoolQueryBuilder boolQueryBuilder = boolQuery()
// ensures that at least one "should" query is matched. Without it, "should" queries are optional, when a "must" is also present.
.minimumShouldMatch(1)
// the field type must be vulnerability or security hotspot
.must(termsQuery(FIELD_ISSUE_TYPE, VULNERABILITY.name(), SECURITY_HOTSPOT.name()));
// for top level categories a prefix query is added, while for subcategories a term query is used for exact matching
values.stream().map(v -> choosePrefixQuery(fieldName, v)).forEach(boolQueryBuilder::should);
allFilters.addFilter(
fieldName,
facet.getFilterScope(),
boolQueryBuilder);
}
private static QueryBuilder choosePrefixQuery(String fieldName, String value) {
return value.contains(".") ? createTermFilter(fieldName, value) : createPrefixFilter(fieldName, value + ".");
}
private static void addSeverityFilter(IssueQuery query, AllFilters allFilters) {
QueryBuilder severityFieldFilter = createTermsFilter(FIELD_ISSUE_SEVERITY, query.severities());
if (severityFieldFilter != null) {
allFilters.addFilter(
FIELD_ISSUE_SEVERITY,
SEVERITIES.getFilterScope(),
boolQuery()
.must(severityFieldFilter)
// Ignore severity of Security HotSpots
.mustNot(termQuery(FIELD_ISSUE_TYPE, SECURITY_HOTSPOT.name())));
}
}
private static void addComponentRelatedFilters(IssueQuery query, AllFilters filters) {
addCommonComponentRelatedFilters(query, filters);
if (query.viewUuids().isEmpty()) {
addBranchComponentRelatedFilters(query, filters);
} else {
addViewRelatedFilters(query, filters);
}
}
private static void addCommonComponentRelatedFilters(IssueQuery query, AllFilters filters) {
filters.addFilter(FIELD_ISSUE_COMPONENT_UUID, new SimpleFieldFilterScope(FIELD_ISSUE_COMPONENT_UUID),
createTermsFilter(FIELD_ISSUE_COMPONENT_UUID, query.componentUuids()));
if (!Boolean.TRUE.equals(query.onComponentOnly())) {
filters.addFilter(
FIELD_ISSUE_PROJECT_UUID, new SimpleFieldFilterScope(FIELD_ISSUE_PROJECT_UUID),
createTermsFilter(FIELD_ISSUE_PROJECT_UUID, query.projectUuids()));
filters.addFilter(
FIELD_ISSUE_DIRECTORY_PATH, new SimpleFieldFilterScope(FIELD_ISSUE_DIRECTORY_PATH),
createTermsFilter(FIELD_ISSUE_DIRECTORY_PATH, query.directories()));
filters.addFilter(
FIELD_ISSUE_FILE_PATH, new SimpleFieldFilterScope(FIELD_ISSUE_FILE_PATH),
createTermsFilter(FIELD_ISSUE_FILE_PATH, query.files()));
}
}
private static void addBranchComponentRelatedFilters(IssueQuery query, AllFilters allFilters) {
if (Boolean.TRUE.equals(query.onComponentOnly())) {
return;
}
if (query.isMainBranch() != null) {
allFilters.addFilter(
"__is_main_branch", new SimpleFieldFilterScope(FIELD_ISSUE_IS_MAIN_BRANCH),
createTermFilter(FIELD_ISSUE_IS_MAIN_BRANCH, query.isMainBranch().toString()));
}
allFilters.addFilter(
FIELD_ISSUE_BRANCH_UUID, new SimpleFieldFilterScope(FIELD_ISSUE_BRANCH_UUID),
createTermFilter(FIELD_ISSUE_BRANCH_UUID, query.branchUuid()));
}
private static void addViewRelatedFilters(IssueQuery query, AllFilters allFilters) {
if (Boolean.TRUE.equals(query.onComponentOnly())) {
return;
}
Collection<String> viewUuids = query.viewUuids();
String branchUuid = query.branchUuid();
boolean onApplicationBranch = branchUuid != null && !viewUuids.isEmpty();
if (onApplicationBranch) {
allFilters.addFilter("__view", new SimpleFieldFilterScope("view"), createViewFilter(singletonList(query.branchUuid())));
} else {
allFilters.addFilter("__view", new SimpleFieldFilterScope("view"), createViewFilter(viewUuids));
}
}
@CheckForNull
private static QueryBuilder createViewFilter(Collection<String> viewUuids) {
if (viewUuids.isEmpty()) {
return null;
}
BoolQueryBuilder viewsFilter = boolQuery();
for (String viewUuid : viewUuids) {
viewsFilter.should(QueryBuilders.termsLookupQuery(FIELD_ISSUE_BRANCH_UUID,
new TermsLookup(
TYPE_VIEW.getIndex().getName(),
viewUuid,
ViewIndexDefinition.FIELD_PROJECTS)));
}
return viewsFilter;
}
private static RequestFiltersComputer newFilterComputer(SearchOptions options, AllFilters allFilters) {
Collection<String> facetNames = options.getFacets();
Set<TopAggregationDefinition<?>> facets = Stream.concat(
Stream.of(EFFORT_TOP_AGGREGATION),
facetNames.stream()
.map(FACETS_BY_NAME::get)
.filter(Objects::nonNull)
.map(Facet::getTopAggregationDef))
.collect(Collectors.toSet());
return new RequestFiltersComputer(allFilters, facets);
}
private static TopAggregationHelper newAggregationHelper(RequestFiltersComputer filterComputer, IssueQuery query) {
if (hasQueryEffortFacet(query)) {
return new TopAggregationHelper(filterComputer, new SubAggregationHelper(EFFORT_AGGREGATION, EFFORT_AGGREGATION_ORDER));
}
return new TopAggregationHelper(filterComputer, new SubAggregationHelper());
}
private static AggregationBuilder addEffortAggregationIfNeeded(IssueQuery query, AggregationBuilder aggregation) {
if (hasQueryEffortFacet(query)) {
aggregation.subAggregation(EFFORT_AGGREGATION);
}
return aggregation;
}
private static boolean hasQueryEffortFacet(IssueQuery query) {
return FACET_MODE_EFFORT.equals(query.facetMode());
}
@CheckForNull
private static QueryBuilder createTermsFilter(String field, Collection<?> values) {
return values.isEmpty() ? null : termsQuery(field, values);
}
@CheckForNull
private static QueryBuilder createTermFilter(String field, @Nullable String value) {
return value == null ? null : termQuery(field, value);
}
private static QueryBuilder createPrefixFilter(String field, String value) {
return prefixQuery(field, value);
}
private void configureSorting(IssueQuery query, SearchSourceBuilder esRequest) {
createSortBuilders(query).forEach(esRequest::sort);
}
private List<FieldSortBuilder> createSortBuilders(IssueQuery query) {
String sortField = query.sort();
if (sortField != null) {
boolean asc = Boolean.TRUE.equals(query.asc());
return sorting.fill(sortField, asc);
}
return sorting.fillDefault();
}
private QueryBuilder createAuthorizationFilter() {
return authorizationTypeSupport.createQueryFilter();
}
private void addDatesFilter(AllFilters filters, IssueQuery query) {
PeriodStart createdAfter = query.createdAfter();
Date createdBefore = query.createdBefore();
validateCreationDateBounds(createdBefore, createdAfter != null ? createdAfter.date() : null);
if (createdAfter != null) {
filters.addFilter(
"__createdAfter", CREATED_AT.getFilterScope(),
QueryBuilders
.rangeQuery(FIELD_ISSUE_FUNC_CREATED_AT)
.from(createdAfter.date().getTime(), createdAfter.inclusive()));
}
if (createdBefore != null) {
filters.addFilter(
"__createdBefore", CREATED_AT.getFilterScope(),
QueryBuilders
.rangeQuery(FIELD_ISSUE_FUNC_CREATED_AT)
.lt(createdBefore.getTime()));
}
Date createdAt = query.createdAt();
if (createdAt != null) {
filters.addFilter(
"__createdAt", CREATED_AT.getFilterScope(),
termQuery(FIELD_ISSUE_FUNC_CREATED_AT, createdAt.getTime()));
}
}
private static void addNewCodeReferenceFilter(AllFilters filters, IssueQuery query) {
Boolean newCodeOnReference = query.newCodeOnReference();
if (newCodeOnReference != null) {
filters.addFilter(
FIELD_ISSUE_NEW_CODE_REFERENCE, new SimpleFieldFilterScope(FIELD_ISSUE_NEW_CODE_REFERENCE),
termQuery(FIELD_ISSUE_NEW_CODE_REFERENCE, true));
}
}
private static void addNewCodeReferenceFilterByProjectsFilter(AllFilters allFilters, IssueQuery query) {
Collection<String> newCodeOnReferenceByProjectUuids = query.newCodeOnReferenceByProjectUuids();
BoolQueryBuilder boolQueryBuilder = boolQuery();
if (!newCodeOnReferenceByProjectUuids.isEmpty()) {
newCodeOnReferenceByProjectUuids.forEach(projectOrProjectBranchUuid -> boolQueryBuilder.should(boolQuery()
.filter(termQuery(FIELD_ISSUE_BRANCH_UUID, projectOrProjectBranchUuid))
.filter(termQuery(FIELD_ISSUE_NEW_CODE_REFERENCE, true))));
allFilters.addFilter("__is_new_code_reference_by_project_uuids",
new SimpleFieldFilterScope("newCodeReferenceByProjectUuids"), boolQueryBuilder);
}
}
private static void addCreatedAfterByProjectsFilter(AllFilters allFilters, IssueQuery query) {
Map<String, PeriodStart> createdAfterByProjectUuids = query.createdAfterByProjectUuids();
BoolQueryBuilder boolQueryBuilder = boolQuery();
createdAfterByProjectUuids.forEach((projectOrProjectBranchUuid, createdAfterDate) -> boolQueryBuilder.should(boolQuery()
.filter(termQuery(FIELD_ISSUE_BRANCH_UUID, projectOrProjectBranchUuid))
.filter(rangeQuery(FIELD_ISSUE_FUNC_CREATED_AT).from(createdAfterDate.date().getTime(), createdAfterDate.inclusive()))));
allFilters.addFilter("__created_after_by_project_uuids", new SimpleFieldFilterScope("createdAfterByProjectUuids"), boolQueryBuilder);
}
private void validateCreationDateBounds(@Nullable Date createdBefore, @Nullable Date createdAfter) {
Preconditions.checkArgument(createdAfter == null || createdAfter.compareTo(new Date(system.now())) <= 0,
"Start bound cannot be in the future");
Preconditions.checkArgument(createdAfter == null || createdBefore == null || createdAfter.before(createdBefore),
"Start bound cannot be larger or equal to end bound");
}
private void configureTopAggregations(TopAggregationHelper aggregationHelper, IssueQuery query, SearchOptions options,
AllFilters queryFilters, SearchSourceBuilder esRequest) {
addFacetIfNeeded(options, aggregationHelper, esRequest, STATUSES, NO_SELECTED_VALUES);
addFacetIfNeeded(options, aggregationHelper, esRequest, PROJECT_UUIDS, query.projectUuids().toArray());
addFacetIfNeeded(options, aggregationHelper, esRequest, DIRECTORIES, query.directories().toArray());
addFacetIfNeeded(options, aggregationHelper, esRequest, FILES, query.files().toArray());
addFacetIfNeeded(options, aggregationHelper, esRequest, SCOPES, query.scopes().toArray());
addFacetIfNeeded(options, aggregationHelper, esRequest, LANGUAGES, query.languages().toArray());
addFacetIfNeeded(options, aggregationHelper, esRequest, RULES, query.ruleUuids().toArray());
addFacetIfNeeded(options, aggregationHelper, esRequest, AUTHOR, query.authors().toArray());
addFacetIfNeeded(options, aggregationHelper, esRequest, TAGS, query.tags().toArray());
addFacetIfNeeded(options, aggregationHelper, esRequest, TYPES, query.types().toArray());
addFacetIfNeeded(options, aggregationHelper, esRequest, CODE_VARIANTS, query.codeVariants().toArray());
addSecurityCategoryFacetIfNeeded(PARAM_PCI_DSS_32, PCI_DSS_32, options, aggregationHelper, esRequest, query.pciDss32().toArray());
addSecurityCategoryFacetIfNeeded(PARAM_PCI_DSS_40, PCI_DSS_40, options, aggregationHelper, esRequest, query.pciDss40().toArray());
addSecurityCategoryFacetIfNeeded(PARAM_OWASP_ASVS_40, OWASP_ASVS_40, options, aggregationHelper, esRequest, query.owaspAsvs40().toArray());
addSecurityCategoryFacetIfNeeded(PARAM_OWASP_TOP_10, OWASP_TOP_10, options, aggregationHelper, esRequest, query.owaspTop10().toArray());
addSecurityCategoryFacetIfNeeded(PARAM_OWASP_TOP_10_2021, OWASP_TOP_10_2021, options, aggregationHelper, esRequest, query.owaspTop10For2021().toArray());
addSecurityCategoryFacetIfNeeded(PARAM_SANS_TOP_25, SANS_TOP_25, options, aggregationHelper, esRequest, query.sansTop25().toArray());
addSecurityCategoryFacetIfNeeded(PARAM_CWE, CWE, options, aggregationHelper, esRequest, query.cwe().toArray());
addSecurityCategoryFacetIfNeeded(PARAM_SONARSOURCE_SECURITY, SONARSOURCE_SECURITY, options, aggregationHelper, esRequest, query.sonarsourceSecurity().toArray());
addSeverityFacetIfNeeded(options, aggregationHelper, esRequest);
addResolutionFacetIfNeeded(options, query, aggregationHelper, esRequest);
addAssigneesFacetIfNeeded(options, query, aggregationHelper, esRequest);
addCreatedAtFacetIfNeeded(options, query, aggregationHelper, queryFilters, esRequest);
addAssignedToMeFacetIfNeeded(options, aggregationHelper, esRequest);
addEffortTopAggregation(aggregationHelper, esRequest);
}
private static void addFacetIfNeeded(SearchOptions options, TopAggregationHelper aggregationHelper,
SearchSourceBuilder esRequest, Facet facet, Object[] selectedValues) {
if (!options.getFacets().contains(facet.getName())) {
return;
}
FilterAggregationBuilder topAggregation = aggregationHelper.buildTermTopAggregation(
facet.getName(), facet.getTopAggregationDef(), facet.getNumberOfTerms(),
NO_EXTRA_FILTER,
t -> aggregationHelper.getSubAggregationHelper().buildSelectedItemsAggregation(facet.getName(), facet.getTopAggregationDef(), selectedValues)
.ifPresent(t::subAggregation));
esRequest.aggregation(topAggregation);
}
private static void addSecurityCategoryFacetIfNeeded(String param, Facet facet, SearchOptions options, TopAggregationHelper aggregationHelper, SearchSourceBuilder esRequest,
Object[] selectedValues) {
if (!options.getFacets().contains(param)) {
return;
}
AggregationBuilder aggregation = aggregationHelper.buildTermTopAggregation(
facet.getName(), facet.getTopAggregationDef(), facet.getNumberOfTerms(),
filter -> filter.must(termQuery(FIELD_ISSUE_TYPE, VULNERABILITY.name())),
t -> aggregationHelper.getSubAggregationHelper().buildSelectedItemsAggregation(facet.getName(), facet.getTopAggregationDef(), selectedValues)
.ifPresent(t::subAggregation));
esRequest.aggregation(aggregation);
}
private static void addSeverityFacetIfNeeded(SearchOptions options, TopAggregationHelper aggregationHelper, SearchSourceBuilder esRequest) {
if (!options.getFacets().contains(PARAM_SEVERITIES)) {
return;
}
AggregationBuilder aggregation = aggregationHelper.buildTermTopAggregation(
SEVERITIES.getName(), SEVERITIES.getTopAggregationDef(), SEVERITIES.getNumberOfTerms(),
// Ignore severity of Security HotSpots
filter -> filter.mustNot(termQuery(FIELD_ISSUE_TYPE, SECURITY_HOTSPOT.name())),
NO_OTHER_SUBAGGREGATION);
esRequest.aggregation(aggregation);
}
private static void addResolutionFacetIfNeeded(SearchOptions options, IssueQuery query, TopAggregationHelper aggregationHelper, SearchSourceBuilder esRequest) {
if (!options.getFacets().contains(PARAM_RESOLUTIONS)) {
return;
}
AggregationBuilder aggregation = aggregationHelper.buildTermTopAggregation(
RESOLUTIONS.getName(), RESOLUTIONS.getTopAggregationDef(), RESOLUTIONS.getNumberOfTerms(),
NO_EXTRA_FILTER,
t ->
// add aggregation of type "missing" to return count of unresolved issues in the facet
t.subAggregation(
addEffortAggregationIfNeeded(query, AggregationBuilders
.missing(RESOLUTIONS.getName() + FACET_SUFFIX_MISSING)
.field(RESOLUTIONS.getFieldName()))));
esRequest.aggregation(aggregation);
}
private static void addAssigneesFacetIfNeeded(SearchOptions options, IssueQuery query, TopAggregationHelper aggregationHelper, SearchSourceBuilder esRequest) {
if (!options.getFacets().contains(PARAM_ASSIGNEES)) {
return;
}
Consumer<FilterAggregationBuilder> assigneeAggregations = t -> {
// optional second aggregation to return the issue count for selected assignees (if any)
Object[] assignees = query.assignees().toArray();
aggregationHelper.getSubAggregationHelper().buildSelectedItemsAggregation(ASSIGNEES.getName(), ASSIGNEES.getTopAggregationDef(), assignees)
.ifPresent(t::subAggregation);
// third aggregation to always return the count of unassigned in the assignee facet
t.subAggregation(addEffortAggregationIfNeeded(query, AggregationBuilders
.missing(ASSIGNEES.getName() + FACET_SUFFIX_MISSING)
.field(ASSIGNEES.getFieldName())));
};
AggregationBuilder aggregation = aggregationHelper.buildTermTopAggregation(
ASSIGNEES.getName(), ASSIGNEES.getTopAggregationDef(), ASSIGNEES.getNumberOfTerms(),
NO_EXTRA_FILTER, assigneeAggregations);
esRequest.aggregation(aggregation);
}
private void addCreatedAtFacetIfNeeded(SearchOptions options, IssueQuery query, TopAggregationHelper aggregationHelper, AllFilters allFilters,
SearchSourceBuilder esRequest) {
if (options.getFacets().contains(PARAM_CREATED_AT)) {
getCreatedAtFacet(query, aggregationHelper, allFilters).ifPresent(esRequest::aggregation);
}
}
private Optional<AggregationBuilder> getCreatedAtFacet(IssueQuery query, TopAggregationHelper aggregationHelper, AllFilters allFilters) {
long startTime;
boolean startInclusive;
PeriodStart createdAfter = query.createdAfter();
if (createdAfter == null) {
OptionalLong minDate = getMinCreatedAt(allFilters);
if (!minDate.isPresent()) {
return Optional.empty();
}
startTime = minDate.getAsLong();
startInclusive = true;
} else {
startTime = createdAfter.date().getTime();
startInclusive = createdAfter.inclusive();
}
Date createdBefore = query.createdBefore();
long endTime = createdBefore == null ? system.now() : createdBefore.getTime();
Duration timeSpan = new Duration(startTime, endTime);
DateHistogramInterval bucketSize = computeDateHistogramBucketSize(timeSpan);
FilterAggregationBuilder topAggregation = aggregationHelper.buildTopAggregation(
CREATED_AT.getName(),
CREATED_AT.getTopAggregationDef(),
NO_EXTRA_FILTER,
t -> {
AggregationBuilder dateHistogram = AggregationBuilders.dateHistogram(CREATED_AT.getName())
.field(CREATED_AT.getFieldName())
.calendarInterval(bucketSize)
.minDocCount(0L)
.format(DateUtils.DATETIME_FORMAT)
.timeZone(Optional.ofNullable(query.timeZone()).orElse(system.getDefaultTimeZone().toZoneId()))
// ES dateHistogram bounds are inclusive while createdBefore parameter is exclusive
.extendedBounds(new LongBounds(startInclusive ? startTime : (startTime + 1), endTime - 1L));
addEffortAggregationIfNeeded(query, dateHistogram);
t.subAggregation(dateHistogram);
});
return Optional.of(topAggregation);
}
private static DateHistogramInterval computeDateHistogramBucketSize(Duration timeSpan) {
if (timeSpan.isShorterThan(TWENTY_DAYS)) {
return DateHistogramInterval.DAY;
}
if (timeSpan.isShorterThan(TWENTY_WEEKS)) {
return DateHistogramInterval.WEEK;
}
if (timeSpan.isShorterThan(TWENTY_MONTHS)) {
return DateHistogramInterval.MONTH;
}
return DateHistogramInterval.YEAR;
}
private OptionalLong getMinCreatedAt(AllFilters filters) {
String facetNameAndField = CREATED_AT.getFieldName();
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
.size(0);
BoolQueryBuilder esFilter = boolQuery();
filters.stream().filter(Objects::nonNull).forEach(esFilter::must);
if (esFilter.hasClauses()) {
sourceBuilder.query(QueryBuilders.boolQuery().filter(esFilter));
}
sourceBuilder.aggregation(AggregationBuilders.min(facetNameAndField).field(facetNameAndField));
SearchRequest request = EsClient.prepareSearch(TYPE_ISSUE.getMainType())
.source(sourceBuilder);
Min minValue = client.search(request).getAggregations().get(facetNameAndField);
double actualValue = minValue.getValue();
if (Double.isInfinite(actualValue)) {
return OptionalLong.empty();
}
return OptionalLong.of((long) actualValue);
}
private void addAssignedToMeFacetIfNeeded(SearchOptions options, TopAggregationHelper aggregationHelper, SearchSourceBuilder esRequest) {
String uuid = userSession.getUuid();
if (options.getFacets().contains(ASSIGNED_TO_ME.getName()) && !StringUtils.isEmpty(uuid)) {
AggregationBuilder aggregation = aggregationHelper.buildTopAggregation(
ASSIGNED_TO_ME.getName(),
ASSIGNED_TO_ME.getTopAggregationDef(),
NO_EXTRA_FILTER,
t ->
// add sub-aggregation to return issue count for current user
aggregationHelper.getSubAggregationHelper()
.buildSelectedItemsAggregation(ASSIGNED_TO_ME.getName(), ASSIGNED_TO_ME.getTopAggregationDef(), new String[]{uuid})
.ifPresent(t::subAggregation));
esRequest.aggregation(aggregation);
}
}
private static void addEffortTopAggregation(TopAggregationHelper aggregationHelper, SearchSourceBuilder esRequest) {
AggregationBuilder topAggregation = aggregationHelper.buildTopAggregation(
FACET_MODE_EFFORT,
EFFORT_TOP_AGGREGATION,
NO_EXTRA_FILTER,
t -> t.subAggregation(EFFORT_AGGREGATION));
esRequest.aggregation(topAggregation);
}
public List<String> searchTags(IssueQuery query, @Nullable String textQuery, int size) {
Terms terms = listTermsMatching(FIELD_ISSUE_TAGS, query, textQuery, BucketOrder.key(true), size);
return EsUtils.termsKeys(terms);
}
public Map<String, Long> countTags(IssueQuery query, int maxNumberOfTags) {
Terms terms = listTermsMatching(FIELD_ISSUE_TAGS, query, null, BucketOrder.count(false), maxNumberOfTags);
return EsUtils.termsToMap(terms);
}
public List<String> searchAuthors(IssueQuery query, @Nullable String textQuery, int maxNumberOfAuthors) {
Terms terms = listTermsMatching(FIELD_ISSUE_AUTHOR_LOGIN, query, textQuery, BucketOrder.key(true), maxNumberOfAuthors);
return EsUtils.termsKeys(terms);
}
private Terms listTermsMatching(String fieldName, IssueQuery query, @Nullable String textQuery, BucketOrder termsOrder, int size) {
SearchRequest requestBuilder = EsClient.prepareSearch(TYPE_ISSUE.getMainType());
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
// Avoids returning search hits
.size(0);
requestBuilder.source(sourceBuilder);
sourceBuilder.query(boolQuery().must(QueryBuilders.matchAllQuery()).filter(createBoolFilter(query)));
TermsAggregationBuilder aggreg = AggregationBuilders.terms("_ref")
.field(fieldName)
.size(size)
.order(termsOrder)
.minDocCount(1L);
if (textQuery != null) {
aggreg.includeExclude(new IncludeExclude(format(SUBSTRING_MATCH_REGEXP, escapeSpecialRegexChars(textQuery)), null));
}
sourceBuilder.aggregation(aggreg);
SearchResponse searchResponse = client.search(requestBuilder);
return searchResponse.getAggregations().get("_ref");
}
private BoolQueryBuilder createBoolFilter(IssueQuery query) {
BoolQueryBuilder boolQuery = boolQuery();
createAllFilters(query).stream()
.filter(Objects::nonNull)
.forEach(boolQuery::must);
return boolQuery;
}
public List<ProjectStatistics> searchProjectStatistics(List<String> projectUuids, List<Long> froms, @Nullable String assigneeUuid) {
checkState(projectUuids.size() == froms.size(),
"Expected same size for projectUuids (had size %s) and froms (had size %s)", projectUuids.size(), froms.size());
if (projectUuids.isEmpty()) {
return Collections.emptyList();
}
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
.query(
boolQuery()
.mustNot(existsQuery(FIELD_ISSUE_RESOLUTION))
.filter(termQuery(FIELD_ISSUE_ASSIGNEE_UUID, assigneeUuid))
.mustNot(termQuery(FIELD_ISSUE_TYPE, SECURITY_HOTSPOT.name())))
.size(0);
IntStream.range(0, projectUuids.size()).forEach(i -> {
String projectUuid = projectUuids.get(i);
long from = froms.get(i);
sourceBuilder
.aggregation(AggregationBuilders
.filter(projectUuid, boolQuery()
.filter(termQuery(FIELD_ISSUE_PROJECT_UUID, projectUuid))
.filter(rangeQuery(FIELD_ISSUE_FUNC_CREATED_AT).gte(from)))
.subAggregation(
AggregationBuilders.terms("branchUuid").field(FIELD_ISSUE_BRANCH_UUID)
.subAggregation(
AggregationBuilders.count(AGG_COUNT).field(FIELD_ISSUE_KEY))
.subAggregation(
AggregationBuilders.max("maxFuncCreatedAt").field(FIELD_ISSUE_FUNC_CREATED_AT))));
});
SearchRequest requestBuilder = EsClient.prepareSearch(TYPE_ISSUE.getMainType());
requestBuilder.source(sourceBuilder);
SearchResponse response = client.search(requestBuilder);
return response.getAggregations().asList().stream()
.map(ParsedFilter.class::cast)
.flatMap(projectBucket -> ((ParsedStringTerms) projectBucket.getAggregations().get("branchUuid")).getBuckets().stream()
.flatMap(branchBucket -> {
long count = ((ParsedValueCount) branchBucket.getAggregations().get(AGG_COUNT)).getValue();
if (count < 1L) {
return Stream.empty();
}
long lastIssueDate = (long) ((ParsedMax) branchBucket.getAggregations().get("maxFuncCreatedAt")).getValue();
return Stream.of(new ProjectStatistics(branchBucket.getKeyAsString(), count, lastIssueDate));
}))
.toList();
}
public List<SecurityStandardCategoryStatistics> getCweTop25Reports(String projectUuid, boolean isViewOrApp) {
SearchSourceBuilder request = prepareNonClosedVulnerabilitiesAndHotspotSearch(projectUuid, isViewOrApp);
CWES_BY_CWE_TOP_25.keySet()
.forEach(cweYear -> request.aggregation(
newSecurityReportSubAggregations(
AggregationBuilders.filter(cweYear, boolQuery().filter(existsQuery(FIELD_ISSUE_CWE))),
true,
CWES_BY_CWE_TOP_25.get(cweYear))));
List<SecurityStandardCategoryStatistics> result = search(request, true, null);
for (SecurityStandardCategoryStatistics cweReport : result) {
Set<String> foundRules = cweReport.getChildren().stream()
.map(SecurityStandardCategoryStatistics::getCategory)
.collect(Collectors.toSet());
CWES_BY_CWE_TOP_25.get(cweReport.getCategory()).stream()
.filter(rule -> !foundRules.contains(rule))
.forEach(rule -> cweReport.getChildren().add(emptyCweStatistics(rule)));
}
return result;
}
private static SecurityStandardCategoryStatistics emptyCweStatistics(String rule) {
return new SecurityStandardCategoryStatistics(rule, 0, OptionalInt.of(1), 0, 0, 1, null, null);
}
public List<SecurityStandardCategoryStatistics> getSonarSourceReport(String projectUuid, boolean isViewOrApp, boolean includeCwe) {
SearchSourceBuilder request = prepareNonClosedVulnerabilitiesAndHotspotSearch(projectUuid, isViewOrApp);
Arrays.stream(SQCategory.values())
.forEach(sonarsourceCategory -> request.aggregation(
newSecurityReportSubAggregations(
AggregationBuilders.filter(sonarsourceCategory.getKey(), boolQuery().filter(termQuery(FIELD_ISSUE_SQ_SECURITY_CATEGORY, sonarsourceCategory.getKey()))),
includeCwe,
SecurityStandards.CWES_BY_SQ_CATEGORY.get(sonarsourceCategory))));
return search(request, includeCwe, null);
}
public List<SecurityStandardCategoryStatistics> getPciDssReport(String projectUuid, boolean isViewOrApp, PciDssVersion version) {
SearchSourceBuilder request = prepareNonClosedVulnerabilitiesAndHotspotSearch(projectUuid, isViewOrApp);
Arrays.stream(PciDss.values())
.forEach(pciDss -> request.aggregation(
newSecurityReportSubAggregations(
AggregationBuilders.filter(pciDss.category(), boolQuery().filter(prefixQuery(version.prefix(), pciDss.category() + "."))), version.prefix())));
return searchWithDistribution(request, version.label(), null);
}
public List<SecurityStandardCategoryStatistics> getOwaspAsvsReport(String projectUuid, boolean isViewOrApp, RulesDefinition.OwaspAsvsVersion version, Integer level) {
SearchSourceBuilder request = prepareNonClosedVulnerabilitiesAndHotspotSearch(projectUuid, isViewOrApp);
Arrays.stream(SecurityStandards.OwaspAsvs.values())
.forEach(owaspAsvs -> request.aggregation(
newSecurityReportSubAggregations(
AggregationBuilders.filter(
owaspAsvs.category(),
boolQuery().filter(termsQuery(version.prefix(), SecurityStandards.getRequirementsForCategoryAndLevel(owaspAsvs, level)))),
version.prefix())));
return searchWithDistribution(request, version.label(), level);
}
public List<SecurityStandardCategoryStatistics> getOwaspAsvsReportGroupedByLevel(String projectUuid, boolean isViewOrApp, RulesDefinition.OwaspAsvsVersion version, int level) {
SearchSourceBuilder request = prepareNonClosedVulnerabilitiesAndHotspotSearch(projectUuid, isViewOrApp);
request.aggregation(
newSecurityReportSubAggregations(
AggregationBuilders.filter(
"l" + level,
boolQuery().filter(termsQuery(version.prefix(), SecurityStandards.OWASP_ASVS_REQUIREMENTS_BY_LEVEL.get(version).get(level)))),
version.prefix()));
return searchWithLevelDistribution(request, version.label(), Integer.toString(level));
}
public List<SecurityStandardCategoryStatistics> getOwaspTop10Report(String projectUuid, boolean isViewOrApp, boolean includeCwe, OwaspTop10Version version) {
SearchSourceBuilder request = prepareNonClosedVulnerabilitiesAndHotspotSearch(projectUuid, isViewOrApp);
IntStream.rangeClosed(1, 10).mapToObj(i -> "a" + i)
.forEach(owaspCategory -> request.aggregation(
newSecurityReportSubAggregations(
AggregationBuilders.filter(owaspCategory, boolQuery().filter(termQuery(version.prefix(), owaspCategory))),
includeCwe,
null)));
return search(request, includeCwe, version.label());
}
private List<SecurityStandardCategoryStatistics> searchWithLevelDistribution(SearchSourceBuilder sourceBuilder, String version, @Nullable String level) {
return getSearchResponse(sourceBuilder)
.getAggregations().asList().stream()
.map(c -> processSecurityReportIssueSearchResultsWithLevelDistribution((ParsedFilter) c, version, level))
.toList();
}
private List<SecurityStandardCategoryStatistics> searchWithDistribution(SearchSourceBuilder sourceBuilder, String version, @Nullable Integer level) {
return getSearchResponse(sourceBuilder)
.getAggregations().asList().stream()
.map(c -> processSecurityReportIssueSearchResultsWithDistribution((ParsedFilter) c, version, level))
.toList();
}
private List<SecurityStandardCategoryStatistics> search(SearchSourceBuilder sourceBuilder, boolean includeDistribution, @Nullable String version) {
return getSearchResponse(sourceBuilder)
.getAggregations().asList().stream()
.map(c -> processSecurityReportIssueSearchResults((ParsedFilter) c, includeDistribution, version))
.toList();
}
private SearchResponse getSearchResponse(SearchSourceBuilder sourceBuilder) {
SearchRequest request = EsClient.prepareSearch(TYPE_ISSUE.getMainType())
.source(sourceBuilder);
return client.search(request);
}
private static SecurityStandardCategoryStatistics processSecurityReportIssueSearchResultsWithDistribution(ParsedFilter categoryFilter, String version, @Nullable Integer level) {
var list = ((ParsedStringTerms) categoryFilter.getAggregations().get(AGG_DISTRIBUTION)).getBuckets();
List<SecurityStandardCategoryStatistics> children = list.stream()
.filter(categoryBucket -> StringUtils.startsWith(categoryBucket.getKeyAsString(), categoryFilter.getName() + "."))
.filter(categoryBucket -> level == null || OWASP_ASVS_40_REQUIREMENTS_BY_LEVEL.get(level).contains(categoryBucket.getKeyAsString()))
.map(categoryBucket -> processSecurityReportCategorySearchResults(categoryBucket, categoryBucket.getKeyAsString(), null, null))
.toList();
return processSecurityReportCategorySearchResults(categoryFilter, categoryFilter.getName(), children, version);
}
private static SecurityStandardCategoryStatistics processSecurityReportIssueSearchResultsWithLevelDistribution(ParsedFilter categoryFilter, String version, String level) {
var list = ((ParsedStringTerms) categoryFilter.getAggregations().get(AGG_DISTRIBUTION)).getBuckets();
List<SecurityStandardCategoryStatistics> children = list.stream()
.filter(categoryBucket -> OWASP_ASVS_40_REQUIREMENTS_BY_LEVEL.get(Integer.parseInt(level)).contains(categoryBucket.getKeyAsString()))
.map(categoryBucket -> processSecurityReportCategorySearchResults(categoryBucket, categoryBucket.getKeyAsString(), null, null))
.toList();
return processSecurityReportCategorySearchResults(categoryFilter, categoryFilter.getName(), children, version);
}
private static SecurityStandardCategoryStatistics processSecurityReportIssueSearchResults(ParsedFilter categoryBucket, boolean includeDistribution, String version) {
List<SecurityStandardCategoryStatistics> children = new ArrayList<>();
if (includeDistribution) {
Stream<? extends Terms.Bucket> stream = ((ParsedStringTerms) categoryBucket.getAggregations().get(AGG_DISTRIBUTION)).getBuckets().stream();
children = stream.map(cweBucket -> processSecurityReportCategorySearchResults(cweBucket, cweBucket.getKeyAsString(), null, null))
.collect(toCollection(ArrayList<SecurityStandardCategoryStatistics>::new));
}
return processSecurityReportCategorySearchResults(categoryBucket, categoryBucket.getName(), children, version);
}
private static SecurityStandardCategoryStatistics processSecurityReportCategorySearchResults(HasAggregations categoryBucket, String categoryName,
@Nullable List<SecurityStandardCategoryStatistics> children, @Nullable String version) {
List<? extends Terms.Bucket> severityBuckets = ((ParsedStringTerms) ((ParsedFilter) categoryBucket.getAggregations().get(AGG_VULNERABILITIES)).getAggregations()
.get(AGG_SEVERITIES)).getBuckets();
long vulnerabilities = severityBuckets.stream().mapToLong(b -> ((ParsedValueCount) b.getAggregations().get(AGG_COUNT)).getValue()).sum();
// Worst severity having at least one issue
OptionalInt severityRating = severityBuckets.stream()
.filter(b -> ((ParsedValueCount) b.getAggregations().get(AGG_COUNT)).getValue() != 0)
.mapToInt(b -> Severity.ALL.indexOf(b.getKeyAsString()) + 1)
.max();
long toReviewSecurityHotspots = ((ParsedValueCount) ((ParsedFilter) categoryBucket.getAggregations().get(AGG_TO_REVIEW_SECURITY_HOTSPOTS)).getAggregations().get(AGG_COUNT))
.getValue();
long reviewedSecurityHotspots = ((ParsedValueCount) ((ParsedFilter) categoryBucket.getAggregations().get(AGG_REVIEWED_SECURITY_HOTSPOTS)).getAggregations().get(AGG_COUNT))
.getValue();
Optional<Double> percent = computePercent(toReviewSecurityHotspots, reviewedSecurityHotspots);
Integer securityReviewRating = computeRating(percent.orElse(null)).getIndex();
return new SecurityStandardCategoryStatistics(categoryName, vulnerabilities, severityRating, toReviewSecurityHotspots,
reviewedSecurityHotspots, securityReviewRating, children, version);
}
private static AggregationBuilder newSecurityReportSubAggregations(AggregationBuilder categoriesAggs, String securityStandardVersionPrefix) {
AggregationBuilder aggregationBuilder = addSecurityReportIssueCountAggregations(categoriesAggs);
final TermsAggregationBuilder distributionAggregation = AggregationBuilders.terms(AGG_DISTRIBUTION)
.field(securityStandardVersionPrefix)
// 100 should be enough to display all the requirements per category. If not, the UI will be broken anyway
.size(MAX_FACET_SIZE);
categoriesAggs.subAggregation(addSecurityReportIssueCountAggregations(distributionAggregation));
return aggregationBuilder;
}
private static AggregationBuilder newSecurityReportSubAggregations(AggregationBuilder categoriesAggs, boolean includeCwe, @Nullable Collection<String> cwesInCategory) {
AggregationBuilder aggregationBuilder = addSecurityReportIssueCountAggregations(categoriesAggs);
if (includeCwe) {
final TermsAggregationBuilder cwesAgg = AggregationBuilders.terms(AGG_DISTRIBUTION)
.field(FIELD_ISSUE_CWE)
// 100 should be enough to display all CWEs. If not, the UI will be broken anyway
.size(MAX_FACET_SIZE);
if (cwesInCategory != null) {
cwesAgg.includeExclude(new IncludeExclude(cwesInCategory.toArray(new String[0]), new String[0]));
}
categoriesAggs.subAggregation(addSecurityReportIssueCountAggregations(cwesAgg));
}
return aggregationBuilder;
}
private static AggregationBuilder addSecurityReportIssueCountAggregations(AggregationBuilder categoryAggs) {
return categoryAggs
.subAggregation(
AggregationBuilders.filter(AGG_VULNERABILITIES, NON_RESOLVED_VULNERABILITIES_FILTER)
.subAggregation(
AggregationBuilders.terms(AGG_SEVERITIES).field(FIELD_ISSUE_SEVERITY)
.subAggregation(
AggregationBuilders.count(AGG_COUNT).field(FIELD_ISSUE_KEY))))
.subAggregation(AggregationBuilders.filter(AGG_TO_REVIEW_SECURITY_HOTSPOTS, TO_REVIEW_HOTSPOTS_FILTER)
.subAggregation(
AggregationBuilders.count(AGG_COUNT).field(FIELD_ISSUE_KEY)))
.subAggregation(AggregationBuilders.filter(AGG_IN_REVIEW_SECURITY_HOTSPOTS, IN_REVIEW_HOTSPOTS_FILTER)
.subAggregation(
AggregationBuilders.count(AGG_COUNT).field(FIELD_ISSUE_KEY)))
.subAggregation(AggregationBuilders.filter(AGG_REVIEWED_SECURITY_HOTSPOTS, REVIEWED_HOTSPOTS_FILTER)
.subAggregation(
AggregationBuilders.count(AGG_COUNT).field(FIELD_ISSUE_KEY)));
}
private static SearchSourceBuilder prepareNonClosedVulnerabilitiesAndHotspotSearch(String projectUuid, boolean isViewOrApp) {
BoolQueryBuilder componentFilter = boolQuery();
if (isViewOrApp) {
componentFilter.filter(QueryBuilders.termsLookupQuery(FIELD_ISSUE_BRANCH_UUID,
new TermsLookup(
TYPE_VIEW.getIndex().getName(),
projectUuid,
ViewIndexDefinition.FIELD_PROJECTS)));
} else {
componentFilter.filter(termQuery(FIELD_ISSUE_BRANCH_UUID, projectUuid));
}
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
return sourceBuilder
.query(
componentFilter
.should(NON_RESOLVED_VULNERABILITIES_FILTER)
.should(TO_REVIEW_HOTSPOTS_FILTER)
.should(IN_REVIEW_HOTSPOTS_FILTER)
.should(REVIEWED_HOTSPOTS_FILTER)
.minimumShouldMatch(1))
.size(0);
}
}
| 70,327 | 52.037707 | 179 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/issue/index/IssueIndexSyncProgressChecker.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.issue.index;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.es.EsIndexSyncInProgressException;
import static org.sonar.api.resources.Qualifiers.APP;
import static org.sonar.api.resources.Qualifiers.SUBVIEW;
import static org.sonar.api.resources.Qualifiers.VIEW;
public class IssueIndexSyncProgressChecker {
private static final ImmutableSet<String> APP_VIEW_OR_SUBVIEW = ImmutableSet.<String>builder().add(VIEW, SUBVIEW, APP).build();
private final DbClient dbClient;
public IssueIndexSyncProgressChecker(DbClient dbClient) {
this.dbClient = dbClient;
}
public IssueSyncProgress getIssueSyncProgress(DbSession dbSession) {
int completed = dbClient.branchDao().countByNeedIssueSync(dbSession, false);
boolean hasFailures = dbClient.ceActivityDao().hasAnyFailedOrCancelledIssueSyncTask(dbSession);
boolean isCompleted = !dbClient.ceQueueDao().hasAnyIssueSyncTaskPendingOrInProgress(dbSession);
int total = dbClient.branchDao().countAll(dbSession);
return new IssueSyncProgress(isCompleted, completed, total, hasFailures);
}
public void checkIfAnyComponentsNeedIssueSync(DbSession dbSession, List<String> componentKeys) {
boolean isAppOrViewOrSubview = dbClient.componentDao().existAnyOfComponentsWithQualifiers(dbSession, componentKeys, APP_VIEW_OR_SUBVIEW);
boolean needIssueSync;
if (isAppOrViewOrSubview) {
needIssueSync = dbClient.branchDao().hasAnyBranchWhereNeedIssueSync(dbSession, true);
} else {
needIssueSync = dbClient.branchDao().doAnyOfComponentsNeedIssueSync(dbSession, componentKeys);
}
if (needIssueSync) {
throw new EsIndexSyncInProgressException(IssueIndexDefinition.TYPE_ISSUE.getMainType(),
"Results are temporarily unavailable. Indexing of issues is in progress.");
}
}
public void checkIfComponentNeedIssueSync(DbSession dbSession, String componentKey) {
checkIfAnyComponentsNeedIssueSync(dbSession, Collections.singletonList(componentKey));
}
/**
* Checks if issue index sync is in progress, if it is, method throws exception org.sonar.server.es.EsIndexSyncInProgressException
*/
public void checkIfIssueSyncInProgress(DbSession dbSession) {
if (isIssueSyncInProgress(dbSession)) {
throw new EsIndexSyncInProgressException(IssueIndexDefinition.TYPE_ISSUE.getMainType(),
"Results are temporarily unavailable. Indexing of issues is in progress.");
}
}
public boolean isIssueSyncInProgress(DbSession dbSession) {
return dbClient.branchDao().hasAnyBranchWhereNeedIssueSync(dbSession, true);
}
public boolean doProjectNeedIssueSync(DbSession dbSession, String projectUuid) {
return !findProjectUuidsWithIssuesSyncNeed(dbSession, Sets.newHashSet(projectUuid)).isEmpty();
}
public List<String> findProjectUuidsWithIssuesSyncNeed(DbSession dbSession, Collection<String> projectUuids) {
return dbClient.branchDao().selectProjectUuidsWithIssuesNeedSync(dbSession, projectUuids);
}
}
| 4,043 | 43.43956 | 141 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/issue/index/IssueQuery.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.issue.index;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.sonar.db.rule.RuleDto;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE;
/**
* @since 3.6
*/
public class IssueQuery {
public static final String SORT_BY_CREATION_DATE = "CREATION_DATE";
public static final String SORT_BY_UPDATE_DATE = "UPDATE_DATE";
public static final String SORT_BY_CLOSE_DATE = "CLOSE_DATE";
public static final String SORT_BY_SEVERITY = "SEVERITY";
public static final String SORT_BY_STATUS = "STATUS";
/**
* Sort by project, file path then line id
*/
public static final String SORT_BY_FILE_LINE = "FILE_LINE";
/**
* Sort hotspots by vulnerabilityProbability, sqSecurityCategory, project, file path then line id
*/
public static final String SORT_HOTSPOTS = "HOTSPOTS";
public static final Set<String> SORTS = Set.of(SORT_BY_CREATION_DATE, SORT_BY_UPDATE_DATE, SORT_BY_CLOSE_DATE, SORT_BY_SEVERITY,
SORT_BY_STATUS, SORT_BY_FILE_LINE, SORT_HOTSPOTS);
private final Collection<String> issueKeys;
private final Collection<String> severities;
private final Collection<String> statuses;
private final Collection<String> resolutions;
private final Collection<String> components;
private final Collection<String> projects;
private final Collection<String> directories;
private final Collection<String> files;
private final Collection<String> views;
private final Collection<RuleDto> rules;
private final Collection<String> ruleUuids;
private final Collection<String> assignees;
private final Collection<String> authors;
private final Collection<String> scopes;
private final Collection<String> languages;
private final Collection<String> tags;
private final Collection<String> types;
private final Collection<String> owaspTop10;
private final Collection<String> pciDss32;
private final Collection<String> pciDss40;
private final Collection<String> owaspAsvs40;
private final Integer owaspAsvsLevel;
private final Collection<String> owaspTop10For2021;
private final Collection<String> sansTop25;
private final Collection<String> cwe;
private final Collection<String> sonarsourceSecurity;
private final Map<String, PeriodStart> createdAfterByProjectUuids;
private final Boolean onComponentOnly;
private final Boolean assigned;
private final Boolean resolved;
private final Date createdAt;
private final PeriodStart createdAfter;
private final Date createdBefore;
private final String sort;
private final Boolean asc;
private final String facetMode;
private final String branchUuid;
private final Boolean mainBranch;
private final ZoneId timeZone;
private final Boolean newCodeOnReference;
private final Collection<String> newCodeOnReferenceByProjectUuids;
private final Collection<String> codeVariants;
private IssueQuery(Builder builder) {
this.issueKeys = defaultCollection(builder.issueKeys);
this.severities = defaultCollection(builder.severities);
this.statuses = defaultCollection(builder.statuses);
this.resolutions = defaultCollection(builder.resolutions);
this.components = defaultCollection(builder.components);
this.projects = defaultCollection(builder.projects);
this.directories = defaultCollection(builder.directories);
this.files = defaultCollection(builder.files);
this.views = defaultCollection(builder.views);
this.rules = defaultCollection(builder.rules);
this.ruleUuids = defaultCollection(builder.ruleUuids);
this.assignees = defaultCollection(builder.assigneeUuids);
this.authors = defaultCollection(builder.authors);
this.scopes = defaultCollection(builder.scopes);
this.languages = defaultCollection(builder.languages);
this.tags = defaultCollection(builder.tags);
this.types = defaultCollection(builder.types);
this.pciDss32 = defaultCollection(builder.pciDss32);
this.pciDss40 = defaultCollection(builder.pciDss40);
this.owaspAsvs40 = defaultCollection(builder.owaspAsvs40);
this.owaspAsvsLevel = builder.owaspAsvsLevel;
this.owaspTop10 = defaultCollection(builder.owaspTop10);
this.owaspTop10For2021 = defaultCollection(builder.owaspTop10For2021);
this.sansTop25 = defaultCollection(builder.sansTop25);
this.cwe = defaultCollection(builder.cwe);
this.sonarsourceSecurity = defaultCollection(builder.sonarsourceSecurity);
this.createdAfterByProjectUuids = defaultMap(builder.createdAfterByProjectUuids);
this.onComponentOnly = builder.onComponentOnly;
this.assigned = builder.assigned;
this.resolved = builder.resolved;
this.createdAt = builder.createdAt;
this.createdAfter = builder.createdAfter;
this.createdBefore = builder.createdBefore;
this.sort = builder.sort;
this.asc = builder.asc;
this.facetMode = builder.facetMode;
this.branchUuid = builder.branchUuid;
this.mainBranch = builder.mainBranch;
this.timeZone = builder.timeZone;
this.newCodeOnReference = builder.newCodeOnReference;
this.newCodeOnReferenceByProjectUuids = defaultCollection(builder.newCodeOnReferenceByProjectUuids);
this.codeVariants = defaultCollection(builder.codeVariants);
}
public Collection<String> issueKeys() {
return issueKeys;
}
public Collection<String> severities() {
return severities;
}
public Collection<String> statuses() {
return statuses;
}
public Collection<String> resolutions() {
return resolutions;
}
public Collection<String> componentUuids() {
return components;
}
public Collection<String> projectUuids() {
return projects;
}
public Collection<String> directories() {
return directories;
}
public Collection<String> files() {
return files;
}
/**
* Restrict issues belonging to projects that were analyzed under a view.
* The view UUIDs should be portfolios, sub portfolios or application branches.
*/
public Collection<String> viewUuids() {
return views;
}
public Collection<RuleDto> rules() {
return rules;
}
public Collection<String> ruleUuids() {
return ruleUuids;
}
public Collection<String> assignees() {
return assignees;
}
public Collection<String> authors() {
return authors;
}
public Collection<String> scopes() {
return scopes;
}
public Collection<String> languages() {
return languages;
}
public Collection<String> tags() {
return tags;
}
public Collection<String> types() {
return types;
}
public Collection<String> pciDss32() {
return pciDss32;
}
public Collection<String> pciDss40() {
return pciDss40;
}
public Collection<String> owaspAsvs40() {
return owaspAsvs40;
}
public Optional<Integer> getOwaspAsvsLevel() {
return Optional.ofNullable(owaspAsvsLevel);
}
public Collection<String> owaspTop10() {
return owaspTop10;
}
public Collection<String> owaspTop10For2021() {
return owaspTop10For2021;
}
public Collection<String> sansTop25() {
return sansTop25;
}
public Collection<String> cwe() {
return cwe;
}
public Collection<String> sonarsourceSecurity() {
return sonarsourceSecurity;
}
public Map<String, PeriodStart> createdAfterByProjectUuids() {
return createdAfterByProjectUuids;
}
@CheckForNull
public Boolean onComponentOnly() {
return onComponentOnly;
}
@CheckForNull
public Boolean assigned() {
return assigned;
}
@CheckForNull
public Boolean resolved() {
return resolved;
}
@CheckForNull
public PeriodStart createdAfter() {
return createdAfter;
}
@CheckForNull
public Date createdAt() {
return createdAt == null ? null : new Date(createdAt.getTime());
}
@CheckForNull
public Date createdBefore() {
return createdBefore == null ? null : new Date(createdBefore.getTime());
}
@CheckForNull
public String sort() {
return sort;
}
@CheckForNull
public Boolean asc() {
return asc;
}
@CheckForNull
public String branchUuid() {
return branchUuid;
}
public Boolean isMainBranch() {
return mainBranch;
}
public String facetMode() {
return facetMode;
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
public static Builder builder() {
return new Builder();
}
@CheckForNull
public ZoneId timeZone() {
return timeZone;
}
@CheckForNull
public Boolean newCodeOnReference() {
return newCodeOnReference;
}
public Collection<String> newCodeOnReferenceByProjectUuids() {
return newCodeOnReferenceByProjectUuids;
}
public Collection<String> codeVariants() {
return codeVariants;
}
public static class Builder {
private Collection<String> issueKeys;
private Collection<String> severities;
private Collection<String> statuses;
private Collection<String> resolutions;
private Collection<String> components;
private Collection<String> projects;
private Collection<String> directories;
private Collection<String> files;
private Collection<String> views;
private Collection<RuleDto> rules;
private Collection<String> ruleUuids;
private Collection<String> assigneeUuids;
private Collection<String> authors;
private Collection<String> scopes;
private Collection<String> languages;
private Collection<String> tags;
private Collection<String> types;
private Collection<String> pciDss32;
private Collection<String> pciDss40;
private Collection<String> owaspAsvs40;
private Integer owaspAsvsLevel;
private Collection<String> owaspTop10;
private Collection<String> owaspTop10For2021;
private Collection<String> sansTop25;
private Collection<String> cwe;
private Collection<String> sonarsourceSecurity;
private Map<String, PeriodStart> createdAfterByProjectUuids;
private Boolean onComponentOnly = false;
private Boolean assigned = null;
private Boolean resolved = null;
private Date createdAt;
private PeriodStart createdAfter;
private Date createdBefore;
private String sort;
private Boolean asc = false;
private String facetMode;
private String branchUuid;
private Boolean mainBranch = true;
private ZoneId timeZone;
private Boolean newCodeOnReference = null;
private Collection<String> newCodeOnReferenceByProjectUuids;
private Collection<String> codeVariants;
private Builder() {
}
public Builder issueKeys(@Nullable Collection<String> l) {
this.issueKeys = l;
return this;
}
public Builder severities(@Nullable Collection<String> l) {
this.severities = l;
return this;
}
public Builder statuses(@Nullable Collection<String> l) {
this.statuses = l;
return this;
}
public Builder resolutions(@Nullable Collection<String> l) {
this.resolutions = l;
return this;
}
public Builder componentUuids(@Nullable Collection<String> l) {
this.components = l;
return this;
}
public Builder projectUuids(@Nullable Collection<String> l) {
this.projects = l;
return this;
}
public Builder directories(@Nullable Collection<String> l) {
this.directories = l;
return this;
}
public Builder files(@Nullable Collection<String> l) {
this.files = l;
return this;
}
/**
* Restrict issues belonging to projects that were analyzed under a view.
* The view UUIDs should be portfolios, sub portfolios or application branches.
*/
public Builder viewUuids(@Nullable Collection<String> l) {
this.views = l;
return this;
}
public Builder rules(@Nullable Collection<RuleDto> rules) {
this.rules = rules;
return this;
}
public Builder ruleUuids(@Nullable Collection<String> ruleUuids) {
this.ruleUuids = ruleUuids;
return this;
}
public Builder assigneeUuids(@Nullable Collection<String> l) {
this.assigneeUuids = l;
return this;
}
public Builder authors(@Nullable Collection<String> l) {
this.authors = l;
return this;
}
public Builder scopes(@Nullable Collection<String> s) {
this.scopes = s;
return this;
}
public Builder languages(@Nullable Collection<String> l) {
this.languages = l;
return this;
}
public Builder tags(@Nullable Collection<String> t) {
this.tags = t;
return this;
}
public Builder types(@Nullable Collection<String> t) {
this.types = t;
return this;
}
public Builder pciDss32(@Nullable Collection<String> o) {
this.pciDss32 = o;
return this;
}
public Builder pciDss40(@Nullable Collection<String> o) {
this.pciDss40 = o;
return this;
}
public Builder owaspAsvs40(@Nullable Collection<String> o) {
this.owaspAsvs40 = o;
return this;
}
public Builder owaspAsvsLevel(@Nullable Integer level) {
this.owaspAsvsLevel = level;
return this;
}
public Builder owaspTop10(@Nullable Collection<String> o) {
this.owaspTop10 = o;
return this;
}
public Builder owaspTop10For2021(@Nullable Collection<String> o) {
this.owaspTop10For2021 = o;
return this;
}
public Builder sansTop25(@Nullable Collection<String> s) {
this.sansTop25 = s;
return this;
}
public Builder cwe(@Nullable Collection<String> cwe) {
this.cwe = cwe;
return this;
}
public Builder sonarsourceSecurity(@Nullable Collection<String> sonarsourceSecurity) {
this.sonarsourceSecurity = sonarsourceSecurity;
return this;
}
public Builder createdAfterByProjectUuids(@Nullable Map<String, PeriodStart> createdAfterByProjectUuids) {
this.createdAfterByProjectUuids = createdAfterByProjectUuids;
return this;
}
/**
* If true, it will return only issues on the passed component(s)
* If false, it will return all issues on the passed component(s) and their descendants
*/
public Builder onComponentOnly(@Nullable Boolean b) {
this.onComponentOnly = b;
return this;
}
/**
* If true, it will return all issues assigned to someone
* If false, it will return all issues not assigned to someone
*/
public Builder assigned(@Nullable Boolean b) {
this.assigned = b;
return this;
}
/**
* If true, it will return all resolved issues
* If false, it will return all none resolved issues
*/
public Builder resolved(@Nullable Boolean resolved) {
this.resolved = resolved;
return this;
}
public Builder createdAt(@Nullable Date d) {
this.createdAt = d == null ? null : new Date(d.getTime());
return this;
}
public Builder createdAfter(@Nullable Date d) {
this.createdAfter(d, true);
return this;
}
public Builder createdAfter(@Nullable Date d, boolean inclusive) {
this.createdAfter = d == null ? null : new PeriodStart(new Date(d.getTime()), inclusive);
return this;
}
public Builder createdBefore(@Nullable Date d) {
this.createdBefore = d == null ? null : new Date(d.getTime());
return this;
}
public Builder sort(@Nullable String s) {
if (s != null && !SORTS.contains(s)) {
throw new IllegalArgumentException("Bad sort field: " + s);
}
this.sort = s;
return this;
}
public Builder asc(@Nullable Boolean asc) {
this.asc = asc;
return this;
}
public IssueQuery build() {
if (issueKeys != null) {
checkArgument(issueKeys.size() <= MAX_PAGE_SIZE, "Number of issue keys must be less than " + MAX_PAGE_SIZE + " (got " + issueKeys.size() + ")");
}
return new IssueQuery(this);
}
public Builder facetMode(String facetMode) {
this.facetMode = facetMode;
return this;
}
public Builder branchUuid(@Nullable String s) {
this.branchUuid = s;
return this;
}
public Builder mainBranch(@Nullable Boolean mainBranch) {
this.mainBranch = mainBranch;
return this;
}
public Builder timeZone(ZoneId timeZone) {
this.timeZone = timeZone;
return this;
}
public Builder newCodeOnReference(@Nullable Boolean newCodeOnReference) {
this.newCodeOnReference = newCodeOnReference;
return this;
}
public Builder newCodeOnReferenceByProjectUuids(@Nullable Collection<String> newCodeOnReferenceByProjectUuids) {
this.newCodeOnReferenceByProjectUuids = newCodeOnReferenceByProjectUuids;
return this;
}
public Builder codeVariants(@Nullable Collection<String> codeVariants) {
this.codeVariants = codeVariants;
return this;
}
}
private static <T> Collection<T> defaultCollection(@Nullable Collection<T> c) {
return c == null ? Collections.emptyList() : Collections.unmodifiableCollection(c);
}
private static <K, V> Map<K, V> defaultMap(@Nullable Map<K, V> map) {
return map == null ? Collections.emptyMap() : Collections.unmodifiableMap(map);
}
public static class PeriodStart {
private final Date date;
private final boolean inclusive;
public PeriodStart(Date date, boolean inclusive) {
this.date = date;
this.inclusive = inclusive;
}
public Date date() {
return date;
}
public boolean inclusive() {
return inclusive;
}
}
}
| 18,709 | 27.348485 | 152 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/issue/index/IssueQueryFactory.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.issue.index;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import java.time.Clock;
import java.time.DateTimeException;
import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang.BooleanUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.ServerSide;
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.component.SnapshotDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.issue.SearchRequest;
import org.sonar.server.issue.index.IssueQuery.PeriodStart;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Collections2.transform;
import static java.lang.String.format;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.sonar.api.issue.Issue.STATUSES;
import static org.sonar.api.issue.Issue.STATUS_REVIEWED;
import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW;
import static org.sonar.api.measures.CoreMetrics.ANALYSIS_FROM_SONARQUBE_9_4_KEY;
import static org.sonar.api.utils.DateUtils.longToDate;
import static org.sonar.api.utils.DateUtils.parseEndingDateOrDateTime;
import static org.sonar.api.utils.DateUtils.parseStartingDateOrDateTime;
import static org.sonar.api.web.UserRole.USER;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_COMPONENT_KEYS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_COMPONENT_UUIDS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_AFTER;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_IN_LAST;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_IN_NEW_CODE_PERIOD;
/**
* This component is used to create an IssueQuery, in order to transform the component and component roots keys into uuid.
*/
@ServerSide
public class IssueQueryFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(IssueQueryFactory.class);
public static final String UNKNOWN = "<UNKNOWN>";
public static final List<String> ISSUE_STATUSES = STATUSES.stream()
.filter(s -> !s.equals(STATUS_TO_REVIEW))
.filter(s -> !s.equals(STATUS_REVIEWED))
.collect(ImmutableList.toImmutableList());
public static final Set<String> ISSUE_TYPE_NAMES = Arrays.stream(RuleType.values())
.filter(t -> t != RuleType.SECURITY_HOTSPOT)
.map(Enum::name)
.collect(Collectors.toSet());
private static final ComponentDto UNKNOWN_COMPONENT = new ComponentDto().setUuid(UNKNOWN).setBranchUuid(UNKNOWN);
private static final Set<String> QUALIFIERS_WITHOUT_LEAK_PERIOD = new HashSet<>(Arrays.asList(Qualifiers.APP, Qualifiers.VIEW, Qualifiers.SUBVIEW));
private final DbClient dbClient;
private final Clock clock;
private final UserSession userSession;
public IssueQueryFactory(DbClient dbClient, Clock clock, UserSession userSession) {
this.dbClient = dbClient;
this.clock = clock;
this.userSession = userSession;
}
public IssueQuery create(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone());
Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules());
Collection<String> ruleUuids = ruleDtos.stream().map(RuleDto::getUuid).collect(Collectors.toSet());
if (request.getRules() != null && request.getRules().stream().collect(Collectors.toSet()).size() != ruleDtos.size()) {
ruleUuids.add("non-existing-uuid");
}
IssueQuery.Builder builder = IssueQuery.builder()
.issueKeys(request.getIssues())
.severities(request.getSeverities())
.statuses(request.getStatuses())
.resolutions(request.getResolutions())
.resolved(request.getResolved())
.rules(ruleDtos)
.ruleUuids(ruleUuids)
.assigneeUuids(request.getAssigneeUuids())
.authors(request.getAuthors())
.scopes(request.getScopes())
.languages(request.getLanguages())
.tags(request.getTags())
.types(request.getTypes())
.pciDss32(request.getPciDss32())
.pciDss40(request.getPciDss40())
.owaspAsvs40(request.getOwaspAsvs40())
.owaspAsvsLevel(request.getOwaspAsvsLevel())
.owaspTop10(request.getOwaspTop10())
.owaspTop10For2021(request.getOwaspTop10For2021())
.sansTop25(request.getSansTop25())
.cwe(request.getCwe())
.sonarsourceSecurity(request.getSonarsourceSecurity())
.assigned(request.getAssigned())
.createdAt(parseStartingDateOrDateTime(request.getCreatedAt(), timeZone))
.createdBefore(parseEndingDateOrDateTime(request.getCreatedBefore(), timeZone))
.facetMode(request.getFacetMode())
.timeZone(timeZone)
.codeVariants(request.getCodeVariants());
List<ComponentDto> allComponents = new ArrayList<>();
boolean effectiveOnComponentOnly = mergeDeprecatedComponentParameters(dbSession, request, allComponents);
addComponentParameters(builder, dbSession, effectiveOnComponentOnly, allComponents, request);
setCreatedAfterFromRequest(dbSession, builder, request, allComponents, timeZone);
String sort = request.getSort();
if (!isNullOrEmpty(sort)) {
builder.sort(sort);
builder.asc(request.getAsc());
}
return builder.build();
}
}
private static Optional<ZoneId> parseTimeZone(@Nullable String timeZone) {
if (timeZone == null) {
return Optional.empty();
}
try {
return Optional.of(ZoneId.of(timeZone));
} catch (DateTimeException e) {
LOGGER.warn("TimeZone '" + timeZone + "' cannot be parsed as a valid zone ID");
return Optional.empty();
}
}
private void setCreatedAfterFromDates(IssueQuery.Builder builder, @Nullable Date createdAfter, @Nullable String createdInLast, boolean createdAfterInclusive) {
Date actualCreatedAfter = createdAfter;
if (createdInLast != null) {
actualCreatedAfter = Date.from(
OffsetDateTime.now(clock)
.minus(Period.parse("P" + createdInLast.toUpperCase(Locale.ENGLISH)))
.toInstant());
}
builder.createdAfter(actualCreatedAfter, createdAfterInclusive);
}
private void setCreatedAfterFromRequest(DbSession dbSession, IssueQuery.Builder builder, SearchRequest request, List<ComponentDto> componentUuids, ZoneId timeZone) {
Date createdAfter = parseStartingDateOrDateTime(request.getCreatedAfter(), timeZone);
String createdInLast = request.getCreatedInLast();
if (notInNewCodePeriod(request)) {
checkArgument(createdAfter == null || createdInLast == null, format("Parameters %s and %s cannot be set simultaneously", PARAM_CREATED_AFTER, PARAM_CREATED_IN_LAST));
setCreatedAfterFromDates(builder, createdAfter, createdInLast, true);
} else {
// If the filter is on leak period
checkArgument(createdAfter == null, "Parameters '%s' and '%s' cannot be set simultaneously", PARAM_CREATED_AFTER, PARAM_IN_NEW_CODE_PERIOD);
checkArgument(createdInLast == null,
format("Parameters '%s' and '%s' cannot be set simultaneously", PARAM_CREATED_IN_LAST, PARAM_IN_NEW_CODE_PERIOD));
checkArgument(componentUuids.size() == 1, "One and only one component must be provided when searching in new code period");
ComponentDto component = componentUuids.iterator().next();
if (!QUALIFIERS_WITHOUT_LEAK_PERIOD.contains(component.qualifier()) && request.getPullRequest() == null) {
Optional<SnapshotDto> snapshot = getLastAnalysis(dbSession, component);
if (!snapshot.isEmpty() && isLastAnalysisFromReAnalyzedReferenceBranch(dbSession, snapshot.get())) {
builder.newCodeOnReference(true);
return;
}
// if last analysis has no period date, then no issue should be considered new.
Date createdAfterFromSnapshot = findCreatedAfterFromComponentUuid(snapshot);
setCreatedAfterFromDates(builder, createdAfterFromSnapshot, null, false);
}
}
}
private static boolean notInNewCodePeriod(SearchRequest request) {
Boolean inNewCodePeriod = request.getInNewCodePeriod();
inNewCodePeriod = Boolean.TRUE.equals(inNewCodePeriod);
return !inNewCodePeriod;
}
private Date findCreatedAfterFromComponentUuid(Optional<SnapshotDto> snapshot) {
return snapshot.map(s -> longToDate(s.getPeriodDate())).orElseGet(() -> new Date(clock.millis()));
}
private static boolean isLastAnalysisUsingReferenceBranch(SnapshotDto snapshot) {
return !isNullOrEmpty(snapshot.getPeriodMode()) && snapshot.getPeriodMode().equals(REFERENCE_BRANCH.name());
}
private boolean isLastAnalysisFromSonarQube94Onwards(DbSession dbSession, String componentUuid) {
return dbClient.liveMeasureDao().selectMeasure(dbSession, componentUuid, ANALYSIS_FROM_SONARQUBE_9_4_KEY).isPresent();
}
private Optional<SnapshotDto> getLastAnalysis(DbSession dbSession, ComponentDto component) {
return dbClient.snapshotDao().selectLastAnalysisByComponentUuid(dbSession, component.uuid());
}
private List<SnapshotDto> getLastAnalysis(DbSession dbSession, Set<String> projectUuids) {
return dbClient.snapshotDao().selectLastAnalysesByRootComponentUuids(dbSession, projectUuids);
}
private boolean mergeDeprecatedComponentParameters(DbSession session, SearchRequest request, List<ComponentDto> allComponents) {
Boolean onComponentOnly = request.getOnComponentOnly();
Collection<String> componentKeys = request.getComponentKeys();
Collection<String> componentUuids = request.getComponentUuids();
String branch = request.getBranch();
String pullRequest = request.getPullRequest();
boolean effectiveOnComponentOnly = false;
checkArgument(atMostOneNonNullElement(componentKeys, componentUuids),
"At most one of the following parameters can be provided: %s and %s", PARAM_COMPONENT_KEYS, PARAM_COMPONENT_UUIDS);
if (componentKeys != null) {
allComponents.addAll(getComponentsFromKeys(session, componentKeys, branch, pullRequest));
effectiveOnComponentOnly = BooleanUtils.isTrue(onComponentOnly);
} else if (componentUuids != null) {
allComponents.addAll(getComponentsFromUuids(session, componentUuids));
effectiveOnComponentOnly = BooleanUtils.isTrue(onComponentOnly);
}
return effectiveOnComponentOnly;
}
private static boolean atMostOneNonNullElement(Object... objects) {
return Arrays.stream(objects)
.filter(Objects::nonNull)
.count() <= 1;
}
private void addComponentParameters(IssueQuery.Builder builder, DbSession session, boolean onComponentOnly, List<ComponentDto> components,
SearchRequest request) {
builder.onComponentOnly(onComponentOnly);
if (onComponentOnly) {
builder.componentUuids(components.stream().map(ComponentDto::uuid).toList());
setBranch(builder, components.get(0), request.getBranch(), request.getPullRequest(), session);
return;
}
List<String> projectKeys = request.getProjectKeys();
if (projectKeys != null) {
List<ComponentDto> branchComponents = getComponentsFromKeys(session, projectKeys, request.getBranch(), request.getPullRequest());
Set<String> projectUuids = retrieveProjectUuidsFromComponents(session, branchComponents);
builder.projectUuids(projectUuids);
setBranch(builder, branchComponents.get(0), request.getBranch(), request.getPullRequest(), session);
}
builder.directories(request.getDirectories());
builder.files(request.getFiles());
addComponentsBasedOnQualifier(builder, session, components, request);
}
@NotNull
private Set<String> retrieveProjectUuidsFromComponents(DbSession session, List<ComponentDto> branchComponents) {
Set<String> branchUuids = branchComponents.stream().map(ComponentDto::branchUuid).collect(Collectors.toSet());
return dbClient.branchDao().selectByUuids(session, branchUuids).stream()
.map(BranchDto::getProjectUuid)
.collect(Collectors.toSet());
}
private void addComponentsBasedOnQualifier(IssueQuery.Builder builder, DbSession dbSession, List<ComponentDto> components, SearchRequest request) {
if (components.isEmpty()) {
return;
}
if (components.stream().map(ComponentDto::uuid).anyMatch(uuid -> uuid.equals(UNKNOWN))) {
builder.componentUuids(singleton(UNKNOWN));
return;
}
Set<String> qualifiers = components.stream().map(ComponentDto::qualifier).collect(Collectors.toSet());
checkArgument(qualifiers.size() == 1, "All components must have the same qualifier, found %s", String.join(",", qualifiers));
setBranch(builder, components.get(0), request.getBranch(), request.getPullRequest(), dbSession);
String qualifier = qualifiers.iterator().next();
switch (qualifier) {
case Qualifiers.VIEW, Qualifiers.SUBVIEW:
addViewsOrSubViews(builder, components);
break;
case Qualifiers.APP:
addApplications(builder, dbSession, components, request);
addProjectUuidsForApplication(builder, dbSession, request);
break;
case Qualifiers.PROJECT:
builder.projectUuids(retrieveProjectUuidsFromComponents(dbSession, components));
break;
case Qualifiers.DIRECTORY:
addDirectories(builder, components);
break;
case Qualifiers.FILE, Qualifiers.UNIT_TEST_FILE:
builder.componentUuids(components.stream().map(ComponentDto::uuid).toList());
break;
default:
throw new IllegalArgumentException("Unable to set search root context for components " + Joiner.on(',').join(components));
}
}
private BranchDto findComponentBranch(DbSession dbSession, ComponentDto componentDto) {
Optional<BranchDto> optionalBranch = dbClient.branchDao().selectByUuid(dbSession, componentDto.branchUuid());
checkArgument(optionalBranch.isPresent(), "All components must belong to a branch. This error may indicate corrupted data.");
return optionalBranch.get();
}
private void addProjectUuidsForApplication(IssueQuery.Builder builder, DbSession session, SearchRequest request) {
List<String> projectKeys = request.getProjectKeys();
if (projectKeys != null) {
// On application, branch should only be applied on the application, not on projects
List<ComponentDto> appBranchComponents = getComponentsFromKeys(session, projectKeys, null, null);
Set<String> appUuids = retrieveProjectUuidsFromComponents(session, appBranchComponents);
builder.projectUuids(appUuids);
}
}
private void addViewsOrSubViews(IssueQuery.Builder builder, Collection<ComponentDto> viewOrSubViewUuids) {
List<String> filteredViewUuids = viewOrSubViewUuids.stream()
.filter(uuid -> userSession.hasComponentPermission(USER, uuid))
.map(ComponentDto::uuid)
.collect(Collectors.toCollection(ArrayList::new));
if (filteredViewUuids.isEmpty()) {
filteredViewUuids.add(UNKNOWN);
}
builder.viewUuids(filteredViewUuids);
}
private void addApplications(IssueQuery.Builder builder, DbSession dbSession, List<ComponentDto> appBranchComponents, SearchRequest request) {
Set<String> authorizedAppBranchUuids = appBranchComponents.stream()
.filter(app -> userSession.hasComponentPermission(USER, app) && userSession.hasChildProjectsPermission(USER, app))
.map(ComponentDto::uuid)
.collect(Collectors.toSet());
builder.viewUuids(authorizedAppBranchUuids.isEmpty() ? singleton(UNKNOWN) : authorizedAppBranchUuids);
addCreatedAfterByProjects(builder, dbSession, request, authorizedAppBranchUuids);
}
private void addCreatedAfterByProjects(IssueQuery.Builder builder, DbSession dbSession, SearchRequest request, Set<String> appBranchUuids) {
if (notInNewCodePeriod(request) || request.getPullRequest() != null) {
return;
}
Set<String> projectBranchUuids = appBranchUuids.stream()
.flatMap(app -> dbClient.componentDao().selectProjectBranchUuidsFromView(dbSession, app, app).stream())
.collect(Collectors.toSet());
List<SnapshotDto> snapshots = getLastAnalysis(dbSession, projectBranchUuids);
Set<String> newCodeReferenceByProjects = snapshots
.stream()
.filter(s -> isLastAnalysisFromReAnalyzedReferenceBranch(dbSession, s))
.map(SnapshotDto::getRootComponentUuid)
.collect(Collectors.toSet());
Map<String, PeriodStart> leakByProjects = snapshots
.stream()
.filter(s -> s.getPeriodDate() != null && !isLastAnalysisFromReAnalyzedReferenceBranch(dbSession, s))
.collect(Collectors.toMap(SnapshotDto::getRootComponentUuid, s1 -> new PeriodStart(longToDate(s1.getPeriodDate()), false)));
builder.createdAfterByProjectUuids(leakByProjects);
builder.newCodeOnReferenceByProjectUuids(newCodeReferenceByProjects);
}
private boolean isLastAnalysisFromReAnalyzedReferenceBranch(DbSession dbSession, SnapshotDto snapshot) {
return isLastAnalysisUsingReferenceBranch(snapshot) &&
isLastAnalysisFromSonarQube94Onwards(dbSession, snapshot.getRootComponentUuid());
}
private static void addDirectories(IssueQuery.Builder builder, List<ComponentDto> directories) {
Set<String> paths = directories.stream().map(ComponentDto::path).collect(Collectors.toSet());
builder.directories(paths);
}
private List<ComponentDto> getComponentsFromKeys(DbSession dbSession, Collection<String> componentKeys, @Nullable String branch, @Nullable String pullRequest) {
List<ComponentDto> componentDtos = dbClient.componentDao().selectByKeys(dbSession, componentKeys, branch, pullRequest);
if (!componentKeys.isEmpty() && componentDtos.isEmpty()) {
return singletonList(UNKNOWN_COMPONENT);
}
return componentDtos;
}
private List<ComponentDto> getComponentsFromUuids(DbSession dbSession, Collection<String> componentUuids) {
List<ComponentDto> componentDtos = dbClient.componentDao().selectByUuids(dbSession, componentUuids);
if (!componentUuids.isEmpty() && componentDtos.isEmpty()) {
return singletonList(UNKNOWN_COMPONENT);
}
return componentDtos;
}
private Collection<RuleDto> ruleKeysToRuleId(DbSession dbSession, @Nullable Collection<String> rules) {
if (rules != null) {
return dbClient.ruleDao().selectByKeys(dbSession, transform(rules, RuleKey::parse));
}
return Collections.emptyList();
}
private void setBranch(IssueQuery.Builder builder, ComponentDto component, @Nullable String branch, @Nullable String pullRequest,
DbSession session) {
builder.branchUuid(branch == null && pullRequest == null ? null : component.branchUuid());
if (UNKNOWN_COMPONENT.equals(component) || (pullRequest == null && branch == null)) {
builder.mainBranch(true);
} else {
BranchDto branchDto = findComponentBranch(session, component);
builder.mainBranch(branchDto.isMain());
}
}
}
| 20,748 | 45.522422 | 172 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/issue/index/IssueSyncProgress.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.issue.index;
public class IssueSyncProgress {
private static final int PERCENT_100 = 100;
private final int completed;
private final int total;
private final boolean hasFailures;
private final boolean isCompleted;
public IssueSyncProgress(boolean isCompleted, int completed, int total, boolean hasFailures) {
this.completed = completed;
this.hasFailures = hasFailures;
this.isCompleted = isCompleted;
this.total = total;
}
public int getCompleted() {
return completed;
}
public boolean hasFailures() {
return hasFailures;
}
public int getTotal() {
return total;
}
public int toPercentCompleted() {
if (total != 0) {
return (int) Math.floor(PERCENT_100 * (double) completed / total);
}
return PERCENT_100;
}
public boolean isCompleted() {
return completed == total || isCompleted;
}
}
| 1,745 | 27.622951 | 96 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/issue/index/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.issue.index;
import javax.annotation.ParametersAreNonnullByDefault;
| 968 | 39.375 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/measure/index/ProjectMeasuresIndex.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.measure.index;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.FiltersAggregator.KeyedFilter;
import org.elasticsearch.search.aggregations.bucket.nested.Nested;
import org.elasticsearch.search.aggregations.bucket.range.RangeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.IncludeExclude;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Sum;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.NestedSortBuilder;
import org.sonar.api.measures.Metric;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.SearchIdResult;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.es.newindex.DefaultIndexSettingsElement;
import org.sonar.server.es.searchrequest.NestedFieldTopAggregationDefinition;
import org.sonar.server.es.searchrequest.RequestFiltersComputer;
import org.sonar.server.es.searchrequest.RequestFiltersComputer.AllFilters;
import org.sonar.server.es.searchrequest.SimpleFieldTopAggregationDefinition;
import org.sonar.server.es.searchrequest.SubAggregationHelper;
import org.sonar.server.es.searchrequest.TopAggregationDefinition;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.NestedFieldFilterScope;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.SimpleFieldFilterScope;
import org.sonar.server.es.searchrequest.TopAggregationHelper;
import org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion;
import org.sonar.server.permission.index.WebAuthorizationTypeSupport;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Collections.emptyList;
import static java.util.Optional.ofNullable;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.nestedQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;
import static org.elasticsearch.search.aggregations.AggregationBuilders.filters;
import static org.elasticsearch.search.aggregations.AggregationBuilders.sum;
import static org.elasticsearch.search.sort.SortOrder.ASC;
import static org.elasticsearch.search.sort.SortOrder.DESC;
import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY;
import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_DENSITY_KEY;
import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_COVERAGE_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_DENSITY_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_MAINTAINABILITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_RELIABILITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_REVIEW_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.RELIABILITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_REVIEW_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.SQALE_RATING_KEY;
import static org.sonar.server.es.EsUtils.escapeSpecialRegexChars;
import static org.sonar.server.es.EsUtils.termsToMap;
import static org.sonar.server.es.IndexType.FIELD_INDEX_TYPE;
import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE;
import static org.sonar.server.es.searchrequest.TopAggregationDefinition.STICKY;
import static org.sonar.server.es.searchrequest.TopAggregationHelper.NO_EXTRA_FILTER;
import static org.sonar.server.measure.index.ProjectMeasuresDoc.QUALITY_GATE_STATUS;
import static org.sonar.server.measure.index.ProjectMeasuresIndex.Facet.ALERT_STATUS;
import static org.sonar.server.measure.index.ProjectMeasuresIndex.Facet.LANGUAGES;
import static org.sonar.server.measure.index.ProjectMeasuresIndex.Facet.TAGS;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_ANALYSED_AT;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_KEY;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_LANGUAGES;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_MEASURES;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_MEASURES_MEASURE_KEY;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_MEASURES_MEASURE_VALUE;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_NAME;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_NCLOC_DISTRIBUTION;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_NCLOC_DISTRIBUTION_LANGUAGE;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_NCLOC_DISTRIBUTION_NCLOC;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_QUALIFIER;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_QUALITY_GATE_STATUS;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_TAGS;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.SUB_FIELD_MEASURES_KEY;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.TYPE_PROJECT_MEASURES;
import static org.sonar.server.measure.index.ProjectMeasuresQuery.SORT_BY_LAST_ANALYSIS_DATE;
import static org.sonar.server.measure.index.ProjectMeasuresQuery.SORT_BY_NAME;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.FILTER_LANGUAGES;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.FILTER_QUALIFIER;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.FILTER_TAGS;
@ServerSide
public class ProjectMeasuresIndex {
private static final int FACET_DEFAULT_SIZE = 10;
private static final double[] LINES_THRESHOLDS = {1_000D, 10_000D, 100_000D, 500_000D};
private static final double[] COVERAGE_THRESHOLDS = {30D, 50D, 70D, 80D};
private static final double[] SECURITY_REVIEW_RATING_THRESHOLDS = {30D, 50D, 70D, 80D};
private static final double[] DUPLICATIONS_THRESHOLDS = {3D, 5D, 10D, 20D};
private static final int SCROLL_SIZE = 5000;
private static final TimeValue KEEP_ALIVE_SCROLL_DURATION = TimeValue.timeValueMinutes(1L);
public enum Facet {
NCLOC(new RangeMeasureFacet(NCLOC_KEY, LINES_THRESHOLDS)),
NEW_LINES(new RangeMeasureFacet(NEW_LINES_KEY, LINES_THRESHOLDS)),
DUPLICATED_LINES_DENSITY(new RangeWithNoDataMeasureFacet(DUPLICATED_LINES_DENSITY_KEY, DUPLICATIONS_THRESHOLDS)),
NEW_DUPLICATED_LINES_DENSITY(new RangeWithNoDataMeasureFacet(NEW_DUPLICATED_LINES_DENSITY_KEY, DUPLICATIONS_THRESHOLDS)),
COVERAGE(new RangeWithNoDataMeasureFacet(COVERAGE_KEY, COVERAGE_THRESHOLDS)),
NEW_COVERAGE(new RangeWithNoDataMeasureFacet(NEW_COVERAGE_KEY, COVERAGE_THRESHOLDS)),
SQALE_RATING(new RatingMeasureFacet(SQALE_RATING_KEY)),
NEW_MAINTAINABILITY_RATING(new RatingMeasureFacet(NEW_MAINTAINABILITY_RATING_KEY)),
RELIABILITY_RATING(new RatingMeasureFacet(RELIABILITY_RATING_KEY)),
NEW_RELIABILITY_RATING(new RatingMeasureFacet(NEW_RELIABILITY_RATING_KEY)),
SECURITY_RATING(new RatingMeasureFacet(SECURITY_RATING_KEY)),
NEW_SECURITY_RATING(new RatingMeasureFacet(NEW_SECURITY_RATING_KEY)),
SECURITY_REVIEW_RATING(new RatingMeasureFacet(SECURITY_REVIEW_RATING_KEY)),
NEW_SECURITY_REVIEW_RATING(new RatingMeasureFacet(NEW_SECURITY_REVIEW_RATING_KEY)),
SECURITY_HOTSPOTS_REVIEWED(new RangeMeasureFacet(SECURITY_HOTSPOTS_REVIEWED_KEY, SECURITY_REVIEW_RATING_THRESHOLDS)),
NEW_SECURITY_HOTSPOTS_REVIEWED(new RangeMeasureFacet(NEW_SECURITY_HOTSPOTS_REVIEWED_KEY, SECURITY_REVIEW_RATING_THRESHOLDS)),
ALERT_STATUS(new MeasureFacet(ALERT_STATUS_KEY, ProjectMeasuresIndex::buildAlertStatusFacet)),
LANGUAGES(FILTER_LANGUAGES, FIELD_LANGUAGES, STICKY, ProjectMeasuresIndex::buildLanguageFacet),
QUALIFIER(FILTER_QUALIFIER, FIELD_QUALIFIER, STICKY, ProjectMeasuresIndex::buildQualifierFacet),
TAGS(FILTER_TAGS, FIELD_TAGS, STICKY, ProjectMeasuresIndex::buildTagsFacet);
private final String name;
private final TopAggregationDefinition<?> topAggregation;
private final FacetBuilder facetBuilder;
Facet(String name, String fieldName, boolean sticky, FacetBuilder facetBuilder) {
this.name = name;
this.topAggregation = new SimpleFieldTopAggregationDefinition(fieldName, sticky);
this.facetBuilder = facetBuilder;
}
Facet(MeasureFacet measureFacet) {
this.name = measureFacet.metricKey;
this.topAggregation = measureFacet.topAggregation;
this.facetBuilder = measureFacet.facetBuilder;
}
public String getName() {
return name;
}
public TopAggregationDefinition<?> getTopAggregationDef() {
return topAggregation;
}
public TopAggregationDefinition.FilterScope getFilterScope() {
return topAggregation.getFilterScope();
}
public FacetBuilder getFacetBuilder() {
return facetBuilder;
}
}
private static final Map<String, Facet> FACETS_BY_NAME = Arrays.stream(Facet.values())
.collect(Collectors.toMap(Facet::getName, Function.identity()));
private final EsClient client;
private final WebAuthorizationTypeSupport authorizationTypeSupport;
private final System2 system2;
public ProjectMeasuresIndex(EsClient client, WebAuthorizationTypeSupport authorizationTypeSupport, System2 system2) {
this.client = client;
this.authorizationTypeSupport = authorizationTypeSupport;
this.system2 = system2;
}
public SearchIdResult<String> search(ProjectMeasuresQuery query, SearchOptions searchOptions) {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
.fetchSource(false)
.trackTotalHits(true)
.from(searchOptions.getOffset())
.size(searchOptions.getLimit());
AllFilters allFilters = createFilters(query);
RequestFiltersComputer filtersComputer = createFiltersComputer(searchOptions, allFilters);
addFacets(searchSourceBuilder, searchOptions, filtersComputer, query);
addSort(query, searchSourceBuilder);
filtersComputer.getQueryFilters().ifPresent(searchSourceBuilder::query);
filtersComputer.getPostFilters().ifPresent(searchSourceBuilder::postFilter);
SearchResponse response = client.search(EsClient.prepareSearch(TYPE_PROJECT_MEASURES.getMainType())
.source(searchSourceBuilder));
return new SearchIdResult<>(response, id -> id, system2.getDefaultTimeZone().toZoneId());
}
private static RequestFiltersComputer createFiltersComputer(SearchOptions searchOptions, AllFilters allFilters) {
Collection<String> facetNames = searchOptions.getFacets();
Set<TopAggregationDefinition<?>> facets = facetNames.stream()
.map(FACETS_BY_NAME::get)
.filter(Objects::nonNull)
.map(Facet::getTopAggregationDef)
.collect(Collectors.toSet());
return new RequestFiltersComputer(allFilters, facets);
}
public ProjectMeasuresStatistics searchSupportStatistics() {
SearchRequest projectMeasuresSearchRequest = buildProjectMeasureSearchRequest();
SearchResponse projectMeasures = client.search(projectMeasuresSearchRequest);
return buildProjectMeasuresStatistics(projectMeasures);
}
private static SearchRequest buildProjectMeasureSearchRequest() {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
.fetchSource(false)
.size(0);
BoolQueryBuilder esFilter = boolQuery()
.filter(termQuery(FIELD_INDEX_TYPE, TYPE_PROJECT_MEASURES.getName()))
.filter(termQuery(FIELD_QUALIFIER, Qualifiers.PROJECT));
searchSourceBuilder.query(esFilter);
searchSourceBuilder.aggregation(AggregationBuilders.terms(FIELD_LANGUAGES)
.field(FIELD_LANGUAGES)
.size(MAX_PAGE_SIZE)
.minDocCount(1)
.order(BucketOrder.count(false)));
searchSourceBuilder.aggregation(AggregationBuilders.nested(FIELD_NCLOC_DISTRIBUTION, FIELD_NCLOC_DISTRIBUTION)
.subAggregation(AggregationBuilders.terms(FIELD_NCLOC_DISTRIBUTION + "_terms")
.field(FIELD_NCLOC_DISTRIBUTION_LANGUAGE)
.size(MAX_PAGE_SIZE)
.minDocCount(1)
.order(BucketOrder.count(false))
.subAggregation(sum(FIELD_NCLOC_DISTRIBUTION_NCLOC).field(FIELD_NCLOC_DISTRIBUTION_NCLOC))));
searchSourceBuilder.aggregation(AggregationBuilders.nested(NCLOC_KEY, FIELD_MEASURES)
.subAggregation(AggregationBuilders.filter(NCLOC_KEY + "_filter", termQuery(FIELD_MEASURES_MEASURE_KEY, NCLOC_KEY))
.subAggregation(sum(NCLOC_KEY + "_filter_sum").field(FIELD_MEASURES_MEASURE_VALUE))));
searchSourceBuilder.size(SCROLL_SIZE);
return EsClient.prepareSearch(TYPE_PROJECT_MEASURES.getMainType()).source(searchSourceBuilder).scroll(KEEP_ALIVE_SCROLL_DURATION);
}
private static ProjectMeasuresStatistics buildProjectMeasuresStatistics(SearchResponse response) {
ProjectMeasuresStatistics.Builder statistics = ProjectMeasuresStatistics.builder();
statistics.setProjectCount(getTotalHits(response.getHits().getTotalHits()).value);
statistics.setProjectCountByLanguage(termsToMap(response.getAggregations().get(FIELD_LANGUAGES)));
Function<Terms.Bucket, Long> bucketToNcloc = bucket -> Math.round(((Sum) bucket.getAggregations().get(FIELD_NCLOC_DISTRIBUTION_NCLOC)).getValue());
Map<String, Long> nclocByLanguage = Stream.of((Nested) response.getAggregations().get(FIELD_NCLOC_DISTRIBUTION))
.map(nested -> (Terms) nested.getAggregations().get(nested.getName() + "_terms"))
.flatMap(terms -> terms.getBuckets().stream())
.collect(Collectors.toMap(Bucket::getKeyAsString, bucketToNcloc));
statistics.setNclocByLanguage(nclocByLanguage);
return statistics.build();
}
private static TotalHits getTotalHits(@Nullable TotalHits totalHits) {
return ofNullable(totalHits).orElseThrow(() -> new IllegalStateException("Could not get total hits of search results"));
}
private static void addSort(ProjectMeasuresQuery query, SearchSourceBuilder requestBuilder) {
String sort = query.getSort();
if (SORT_BY_NAME.equals(sort)) {
requestBuilder.sort(DefaultIndexSettingsElement.SORTABLE_ANALYZER.subField(FIELD_NAME), query.isAsc() ? ASC : DESC);
} else if (SORT_BY_LAST_ANALYSIS_DATE.equals(sort)) {
requestBuilder.sort(FIELD_ANALYSED_AT, query.isAsc() ? ASC : DESC);
} else if (ALERT_STATUS_KEY.equals(sort)) {
requestBuilder.sort(FIELD_QUALITY_GATE_STATUS, query.isAsc() ? ASC : DESC);
requestBuilder.sort(DefaultIndexSettingsElement.SORTABLE_ANALYZER.subField(FIELD_NAME), ASC);
} else {
addMetricSort(query, requestBuilder, sort);
requestBuilder.sort(DefaultIndexSettingsElement.SORTABLE_ANALYZER.subField(FIELD_NAME), ASC);
}
// last sort is by key in order to be deterministic when same value
requestBuilder.sort(FIELD_KEY, ASC);
}
private static void addMetricSort(ProjectMeasuresQuery query, SearchSourceBuilder requestBuilder, String sort) {
requestBuilder.sort(
new FieldSortBuilder(FIELD_MEASURES_MEASURE_VALUE)
.setNestedSort(
new NestedSortBuilder(FIELD_MEASURES)
.setFilter(termQuery(FIELD_MEASURES_MEASURE_KEY, sort)))
.order(query.isAsc() ? ASC : DESC));
}
private static void addFacets(SearchSourceBuilder esRequest, SearchOptions options, RequestFiltersComputer filtersComputer, ProjectMeasuresQuery query) {
TopAggregationHelper topAggregationHelper = new TopAggregationHelper(filtersComputer, new SubAggregationHelper());
options.getFacets().stream()
.map(FACETS_BY_NAME::get)
.filter(Objects::nonNull)
.map(facet -> facet.getFacetBuilder().buildFacet(facet, query, topAggregationHelper))
.forEach(esRequest::aggregation);
}
private static AbstractAggregationBuilder<?> createRangeFacet(String metricKey, double[] thresholds) {
RangeAggregationBuilder rangeAgg = AggregationBuilders.range(metricKey)
.field(FIELD_MEASURES_MEASURE_VALUE);
final int lastIndex = thresholds.length - 1;
IntStream.range(0, thresholds.length)
.forEach(i -> {
if (i == 0) {
rangeAgg.addUnboundedTo(thresholds[0]);
rangeAgg.addRange(thresholds[0], thresholds[1]);
} else if (i == lastIndex) {
rangeAgg.addUnboundedFrom(thresholds[lastIndex]);
} else {
rangeAgg.addRange(thresholds[i], thresholds[i + 1]);
}
});
return AggregationBuilders.nested("nested_" + metricKey, FIELD_MEASURES)
.subAggregation(
AggregationBuilders.filter("filter_" + metricKey, termsQuery(FIELD_MEASURES_MEASURE_KEY, metricKey))
.subAggregation(rangeAgg));
}
private static AbstractAggregationBuilder<?> createQualityGateFacet(ProjectMeasuresQuery projectMeasuresQuery) {
return filters(
ALERT_STATUS_KEY,
QUALITY_GATE_STATUS
.entrySet()
.stream()
.filter(qgs -> !(projectMeasuresQuery.isIgnoreWarning() && qgs.getKey().equals(Metric.Level.WARN.name())))
.map(entry -> new KeyedFilter(entry.getKey(), termQuery(FIELD_QUALITY_GATE_STATUS, entry.getValue())))
.toArray(KeyedFilter[]::new));
}
private static AbstractAggregationBuilder<?> createQualifierFacet() {
return filters(
FILTER_QUALIFIER,
Stream.of(Qualifiers.APP, Qualifiers.PROJECT)
.map(qualifier -> new KeyedFilter(qualifier, termQuery(FIELD_QUALIFIER, qualifier)))
.toArray(KeyedFilter[]::new));
}
private AllFilters createFilters(ProjectMeasuresQuery query) {
AllFilters filters = RequestFiltersComputer.newAllFilters();
filters.addFilter(
"__indexType", new SimpleFieldFilterScope(FIELD_INDEX_TYPE),
termQuery(FIELD_INDEX_TYPE, TYPE_PROJECT_MEASURES.getName()));
if (!query.isIgnoreAuthorization()) {
filters.addFilter("__authorization", new SimpleFieldFilterScope("parent"), authorizationTypeSupport.createQueryFilter());
}
Multimap<String, MetricCriterion> metricCriterionMultimap = ArrayListMultimap.create();
query.getMetricCriteria()
.forEach(metricCriterion -> metricCriterionMultimap.put(metricCriterion.getMetricKey(), metricCriterion));
metricCriterionMultimap.asMap().forEach((key, value) -> {
BoolQueryBuilder metricFilters = boolQuery();
value
.stream()
.map(ProjectMeasuresIndex::toQuery)
.forEach(metricFilters::must);
filters.addFilter(key, new NestedFieldFilterScope<>(FIELD_MEASURES, SUB_FIELD_MEASURES_KEY, key), metricFilters);
});
query.getQualityGateStatus().ifPresent(qualityGateStatus -> filters.addFilter(
ALERT_STATUS_KEY, ALERT_STATUS.getFilterScope(),
termQuery(FIELD_QUALITY_GATE_STATUS, QUALITY_GATE_STATUS.get(qualityGateStatus.name()))));
query.getProjectUuids().ifPresent(projectUuids -> filters.addFilter(
"ids", new SimpleFieldFilterScope("_id"),
termsQuery("_id", projectUuids)));
query.getLanguages()
.ifPresent(languages -> filters.addFilter(FILTER_LANGUAGES, LANGUAGES.getFilterScope(), termsQuery(FIELD_LANGUAGES, languages)));
query.getTags().ifPresent(tags -> filters.addFilter(FIELD_TAGS, TAGS.getFilterScope(), termsQuery(FIELD_TAGS, tags)));
query.getQualifiers()
.ifPresent(qualifiers -> filters.addFilter(FIELD_QUALIFIER, new SimpleFieldFilterScope(FIELD_QUALIFIER), termsQuery(FIELD_QUALIFIER, qualifiers)));
query.getQueryText()
.map(ProjectsTextSearchQueryFactory::createQuery)
.ifPresent(queryBuilder -> filters.addFilter("textQuery", new SimpleFieldFilterScope(FIELD_NAME), queryBuilder));
return filters;
}
private static QueryBuilder toQuery(MetricCriterion criterion) {
if (criterion.isNoData()) {
return boolQuery().mustNot(
nestedQuery(
FIELD_MEASURES,
termQuery(FIELD_MEASURES_MEASURE_KEY, criterion.getMetricKey()),
ScoreMode.Avg));
}
return nestedQuery(
FIELD_MEASURES,
boolQuery()
.filter(termQuery(FIELD_MEASURES_MEASURE_KEY, criterion.getMetricKey()))
.filter(toValueQuery(criterion)),
ScoreMode.Avg);
}
private static QueryBuilder toValueQuery(MetricCriterion criterion) {
String fieldName = FIELD_MEASURES_MEASURE_VALUE;
switch (criterion.getOperator()) {
case GT:
return rangeQuery(fieldName).gt(criterion.getValue());
case GTE:
return rangeQuery(fieldName).gte(criterion.getValue());
case LT:
return rangeQuery(fieldName).lt(criterion.getValue());
case LTE:
return rangeQuery(fieldName).lte(criterion.getValue());
case EQ:
return termQuery(fieldName, criterion.getValue());
default:
throw new IllegalStateException("Metric criteria non supported: " + criterion.getOperator().name());
}
}
public List<String> searchTags(@Nullable String textQuery, int page, int size) {
int maxPageSize = 100;
int maxPage = 20;
checkArgument(size <= maxPageSize, "Page size must be lower than or equals to " + maxPageSize);
checkArgument(page > 0 && page <= maxPage, "Page must be between 0 and " + maxPage);
if (size <= 0) {
return emptyList();
}
TermsAggregationBuilder tagFacet = AggregationBuilders.terms(FIELD_TAGS)
.field(FIELD_TAGS)
.size(size*page)
.minDocCount(1)
.order(BucketOrder.key(true));
if (textQuery != null) {
tagFacet.includeExclude(new IncludeExclude(".*" + escapeSpecialRegexChars(textQuery) + ".*", null));
}
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
.query(authorizationTypeSupport.createQueryFilter())
.fetchSource(false)
.aggregation(tagFacet);
SearchResponse response = client.search(EsClient.prepareSearch(TYPE_PROJECT_MEASURES.getMainType())
.source(searchSourceBuilder));
Terms aggregation = response.getAggregations().get(FIELD_TAGS);
return aggregation.getBuckets().stream()
.skip((page-1) * size)
.map(Bucket::getKeyAsString)
.toList();
}
private interface FacetBuilder {
FilterAggregationBuilder buildFacet(Facet facet, ProjectMeasuresQuery query, TopAggregationHelper topAggregationHelper);
}
/**
* A sticky facet on field {@link ProjectMeasuresIndexDefinition#FIELD_MEASURES_MEASURE_KEY}.
*/
private static class MeasureFacet {
private final String metricKey;
private final TopAggregationDefinition<?> topAggregation;
private final FacetBuilder facetBuilder;
private MeasureFacet(String metricKey, FacetBuilder facetBuilder) {
this.metricKey = metricKey;
this.topAggregation = new NestedFieldTopAggregationDefinition<>(FIELD_MEASURES_MEASURE_KEY, metricKey, STICKY);
this.facetBuilder = facetBuilder;
}
}
private static final class RangeMeasureFacet extends MeasureFacet {
private RangeMeasureFacet(String metricKey, double[] thresholds) {
super(metricKey, new MetricRangeFacetBuilder(metricKey, thresholds));
}
private static final class MetricRangeFacetBuilder implements FacetBuilder {
private final String metricKey;
private final double[] thresholds;
private MetricRangeFacetBuilder(String metricKey, double[] thresholds) {
this.metricKey = metricKey;
this.thresholds = thresholds;
}
@Override
public FilterAggregationBuilder buildFacet(Facet facet, ProjectMeasuresQuery query, TopAggregationHelper topAggregationHelper) {
return topAggregationHelper.buildTopAggregation(
facet.getName(), facet.getTopAggregationDef(),
NO_EXTRA_FILTER,
t -> t.subAggregation(createRangeFacet(metricKey, thresholds)));
}
}
}
private static final class RangeWithNoDataMeasureFacet extends MeasureFacet {
private RangeWithNoDataMeasureFacet(String metricKey, double[] thresholds) {
super(metricKey, new MetricRangeWithNoDataFacetBuilder(metricKey, thresholds));
}
private static final class MetricRangeWithNoDataFacetBuilder implements FacetBuilder {
private final String metricKey;
private final double[] thresholds;
private MetricRangeWithNoDataFacetBuilder(String metricKey, double[] thresholds) {
this.metricKey = metricKey;
this.thresholds = thresholds;
}
@Override
public FilterAggregationBuilder buildFacet(Facet facet, ProjectMeasuresQuery query, TopAggregationHelper topAggregationHelper) {
return topAggregationHelper.buildTopAggregation(
facet.getName(), facet.getTopAggregationDef(),
NO_EXTRA_FILTER,
t -> t.subAggregation(createRangeFacet(metricKey, thresholds))
.subAggregation(createNoDataFacet(metricKey)));
}
private static AbstractAggregationBuilder<?> createNoDataFacet(String metricKey) {
return AggregationBuilders.filter(
"no_data_" + metricKey,
boolQuery().mustNot(nestedQuery(FIELD_MEASURES, termQuery(FIELD_MEASURES_MEASURE_KEY, metricKey), ScoreMode.Avg)));
}
}
}
private static class RatingMeasureFacet extends MeasureFacet {
private RatingMeasureFacet(String metricKey) {
super(metricKey, new MetricRatingFacetBuilder(metricKey));
}
private static class MetricRatingFacetBuilder implements FacetBuilder {
private final String metricKey;
private MetricRatingFacetBuilder(String metricKey) {
this.metricKey = metricKey;
}
@Override
public FilterAggregationBuilder buildFacet(Facet facet, ProjectMeasuresQuery query, TopAggregationHelper topAggregationHelper) {
return topAggregationHelper.buildTopAggregation(
facet.getName(), facet.getTopAggregationDef(),
NO_EXTRA_FILTER,
t -> t.subAggregation(createMeasureRatingFacet(metricKey)));
}
private static AbstractAggregationBuilder<?> createMeasureRatingFacet(String metricKey) {
return AggregationBuilders.nested("nested_" + metricKey, FIELD_MEASURES)
.subAggregation(
AggregationBuilders.filter("filter_" + metricKey, termsQuery(FIELD_MEASURES_MEASURE_KEY, metricKey))
.subAggregation(filters(metricKey,
new KeyedFilter("1", termQuery(FIELD_MEASURES_MEASURE_VALUE, 1D)),
new KeyedFilter("2", termQuery(FIELD_MEASURES_MEASURE_VALUE, 2D)),
new KeyedFilter("3", termQuery(FIELD_MEASURES_MEASURE_VALUE, 3D)),
new KeyedFilter("4", termQuery(FIELD_MEASURES_MEASURE_VALUE, 4D)),
new KeyedFilter("5", termQuery(FIELD_MEASURES_MEASURE_VALUE, 5D)))));
}
}
}
private static FilterAggregationBuilder buildLanguageFacet(Facet facet, ProjectMeasuresQuery query, TopAggregationHelper topAggregationHelper) {
// optional selected languages sub-aggregation
Consumer<FilterAggregationBuilder> extraSubAgg = t -> query.getLanguages()
.flatMap(languages -> topAggregationHelper.getSubAggregationHelper()
.buildSelectedItemsAggregation(FILTER_LANGUAGES, facet.getTopAggregationDef(), languages.toArray()))
.ifPresent(t::subAggregation);
return topAggregationHelper.buildTermTopAggregation(
FILTER_LANGUAGES, facet.getTopAggregationDef(), FACET_DEFAULT_SIZE,
NO_EXTRA_FILTER, extraSubAgg);
}
private static FilterAggregationBuilder buildAlertStatusFacet(Facet facet, ProjectMeasuresQuery query, TopAggregationHelper topAggregationHelper) {
return topAggregationHelper.buildTopAggregation(
facet.getName(), facet.getTopAggregationDef(),
NO_EXTRA_FILTER,
t -> t.subAggregation(createQualityGateFacet(query)));
}
private static FilterAggregationBuilder buildTagsFacet(Facet facet, ProjectMeasuresQuery query, TopAggregationHelper topAggregationHelper) {
// optional selected tags sub-aggregation
Consumer<FilterAggregationBuilder> extraSubAgg = t -> query.getTags()
.flatMap(tags -> topAggregationHelper.getSubAggregationHelper()
.buildSelectedItemsAggregation(FILTER_TAGS, facet.getTopAggregationDef(), tags.toArray()))
.ifPresent(t::subAggregation);
return topAggregationHelper.buildTermTopAggregation(
FILTER_TAGS, facet.getTopAggregationDef(), FACET_DEFAULT_SIZE,
NO_EXTRA_FILTER, extraSubAgg);
}
private static FilterAggregationBuilder buildQualifierFacet(Facet facet, ProjectMeasuresQuery query, TopAggregationHelper topAggregationHelper) {
return topAggregationHelper.buildTopAggregation(
facet.getName(), facet.getTopAggregationDef(),
NO_EXTRA_FILTER,
t -> t.subAggregation(createQualifierFacet()));
}
}
| 31,554 | 48.61478 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/measure/index/ProjectMeasuresQuery.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.measure.index;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.sonar.api.measures.Metric;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static java.util.Arrays.stream;
import static java.util.Objects.requireNonNull;
public class ProjectMeasuresQuery {
public static final String SORT_BY_NAME = "name";
public static final String SORT_BY_LAST_ANALYSIS_DATE = "analysisDate";
private List<MetricCriterion> metricCriteria = new ArrayList<>();
private Metric.Level qualityGateStatus = null;
private Set<String> projectUuids = null;
private Set<String> languages = null;
private Set<String> tags = null;
private Set<String> qualifiers = null;
private String sort = SORT_BY_NAME;
private boolean asc = true;
private String queryText = null;
private boolean ignoreAuthorization = false;
private boolean ignoreWarning = false;
public ProjectMeasuresQuery addMetricCriterion(MetricCriterion metricCriterion) {
this.metricCriteria.add(metricCriterion);
return this;
}
public List<MetricCriterion> getMetricCriteria() {
return metricCriteria;
}
public ProjectMeasuresQuery setQualityGateStatus(Metric.Level qualityGateStatus) {
this.qualityGateStatus = requireNonNull(qualityGateStatus);
return this;
}
public Optional<Metric.Level> getQualityGateStatus() {
return Optional.ofNullable(qualityGateStatus);
}
public ProjectMeasuresQuery setProjectUuids(@Nullable Set<String> projectUuids) {
this.projectUuids = projectUuids;
return this;
}
public Optional<Set<String>> getProjectUuids() {
return Optional.ofNullable(projectUuids);
}
public ProjectMeasuresQuery setLanguages(@Nullable Set<String> languages) {
this.languages = languages;
return this;
}
public Optional<Set<String>> getLanguages() {
return Optional.ofNullable(languages);
}
public ProjectMeasuresQuery setTags(@Nullable Set<String> tags) {
this.tags = tags;
return this;
}
public Optional<Set<String>> getTags() {
return Optional.ofNullable(tags);
}
public Optional<String> getQueryText() {
return Optional.ofNullable(queryText);
}
public ProjectMeasuresQuery setQueryText(@Nullable String queryText) {
this.queryText = queryText;
return this;
}
public String getSort() {
return sort;
}
public ProjectMeasuresQuery setSort(String sort) {
this.sort = requireNonNull(sort, "Sort cannot be null");
return this;
}
public boolean isAsc() {
return asc;
}
public ProjectMeasuresQuery setAsc(boolean asc) {
this.asc = asc;
return this;
}
public boolean isIgnoreAuthorization() {
return ignoreAuthorization;
}
public ProjectMeasuresQuery setIgnoreAuthorization(boolean ignoreAuthorization) {
this.ignoreAuthorization = ignoreAuthorization;
return this;
}
public boolean isIgnoreWarning() {
return ignoreWarning;
}
public ProjectMeasuresQuery setIgnoreWarning(boolean ignoreWarning) {
this.ignoreWarning = ignoreWarning;
return this;
}
public Optional<Set<String>> getQualifiers() {
return Optional.ofNullable(qualifiers);
}
public ProjectMeasuresQuery setQualifiers(@Nullable Set<String> qualifiers) {
this.qualifiers = qualifiers;
return this;
}
public static class MetricCriterion {
private final String metricKey;
private final Operator operator;
@Nullable
private final Double value;
private MetricCriterion(String metricKey, @Nullable Operator operator, @Nullable Double value) {
this.metricKey = metricKey;
this.operator = operator;
this.value = value;
}
public String getMetricKey() {
return metricKey;
}
public Operator getOperator() {
checkDataAvailable();
return operator;
}
public double getValue() {
checkDataAvailable();
return value;
}
public boolean isNoData() {
return value == null;
}
public static MetricCriterion createNoData(String metricKey) {
return new MetricCriterion(requireNonNull(metricKey), null, null);
}
public static MetricCriterion create(String metricKey, Operator operator, double value) {
return new MetricCriterion(requireNonNull(metricKey), requireNonNull(operator), value);
}
private void checkDataAvailable() {
checkState(!isNoData(), "The criterion for metric %s has no data", metricKey);
}
}
public enum Operator {
LT("<"), LTE("<="), GT(">"), GTE(">="), EQ("="), IN("in");
String value;
Operator(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static Operator getByValue(String value) {
return stream(Operator.values())
.filter(operator -> operator.getValue().equalsIgnoreCase(value))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException(format("Unknown operator '%s'", value)));
}
}
}
| 5,970 | 26.643519 | 100 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/measure/index/ProjectMeasuresStatistics.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.measure.index;
import java.util.Map;
import static java.util.Objects.requireNonNull;
public class ProjectMeasuresStatistics {
private final long projectCount;
private final Map<String, Long> projectCountByLanguage;
private final Map<String, Long> nclocByLanguage;
private ProjectMeasuresStatistics(Builder builder) {
projectCount = builder.projectCount;
projectCountByLanguage = builder.projectCountByLanguage;
nclocByLanguage = builder.nclocByLanguage;
}
public long getProjectCount() {
return projectCount;
}
public Map<String, Long> getProjectCountByLanguage() {
return projectCountByLanguage;
}
public Map<String, Long> getNclocByLanguage() {
return nclocByLanguage;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Long projectCount;
private Map<String, Long> projectCountByLanguage;
private Map<String, Long> nclocByLanguage;
private Builder() {
// enforce static factory method
}
public Builder setProjectCount(long projectCount) {
this.projectCount = projectCount;
return this;
}
public Builder setProjectCountByLanguage(Map<String, Long> projectCountByLanguage) {
this.projectCountByLanguage = projectCountByLanguage;
return this;
}
public Builder setNclocByLanguage(Map<String, Long> nclocByLanguage) {
this.nclocByLanguage = nclocByLanguage;
return this;
}
public ProjectMeasuresStatistics build() {
requireNonNull(projectCount);
requireNonNull(projectCountByLanguage);
requireNonNull(nclocByLanguage);
return new ProjectMeasuresStatistics(this);
}
}
}
| 2,571 | 29.258824 | 88 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/measure/index/ProjectsEsModule.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.measure.index;
import org.sonar.core.platform.Module;
public class ProjectsEsModule extends Module {
@Override
protected void configureModule() {
add(
ProjectMeasuresIndexDefinition.class,
ProjectMeasuresIndex.class,
ProjectMeasuresIndexer.class);
}
}
| 1,150 | 33.878788 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/measure/index/ProjectsTextSearchQueryFactory.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.measure.index;
import java.util.Arrays;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.sonar.server.es.newindex.DefaultIndexSettings;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.prefixQuery;
import static org.elasticsearch.index.query.QueryBuilders.wildcardQuery;
import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SEARCH_GRAMS_ANALYZER;
import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SORTABLE_ANALYZER;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_KEY;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_NAME;
/**
* This class is used in order to do some advanced full text search on projects key and name
*/
class ProjectsTextSearchQueryFactory {
private ProjectsTextSearchQueryFactory() {
// Only static methods
}
static QueryBuilder createQuery(String queryText) {
BoolQueryBuilder featureQuery = boolQuery();
Arrays.stream(ComponentTextSearchFeature.values())
.map(f -> f.getQuery(queryText))
.forEach(featureQuery::should);
return featureQuery;
}
private enum ComponentTextSearchFeature {
EXACT_IGNORE_CASE {
@Override
QueryBuilder getQuery(String queryText) {
return matchQuery(SORTABLE_ANALYZER.subField(FIELD_NAME), queryText)
.boost(2.5F);
}
},
PREFIX {
@Override
QueryBuilder getQuery(String queryText) {
return prefixAndPartialQuery(queryText, FIELD_NAME, FIELD_NAME)
.boost(2F);
}
},
PREFIX_IGNORE_CASE {
@Override
QueryBuilder getQuery(String queryText) {
String lowerCaseQueryText = queryText.toLowerCase(Locale.ENGLISH);
return prefixAndPartialQuery(lowerCaseQueryText, SORTABLE_ANALYZER.subField(FIELD_NAME), FIELD_NAME)
.boost(3F);
}
},
PARTIAL {
@Override
QueryBuilder getQuery(String queryText) {
BoolQueryBuilder queryBuilder = boolQuery();
split(queryText)
.map(text -> partialTermQuery(text, FIELD_NAME))
.forEach(queryBuilder::must);
return queryBuilder
.boost(0.5F);
}
},
KEY {
@Override
QueryBuilder getQuery(String queryText) {
return wildcardQuery(SORTABLE_ANALYZER.subField(FIELD_KEY), "*" + queryText + "*")
.caseInsensitive(true)
.boost(50F);
}
};
abstract QueryBuilder getQuery(String queryText);
protected Stream<String> split(String queryText) {
return Arrays.stream(
queryText.split(DefaultIndexSettings.SEARCH_TERM_TOKENIZER_PATTERN))
.filter(StringUtils::isNotEmpty);
}
protected BoolQueryBuilder prefixAndPartialQuery(String queryText, String fieldName, String originalFieldName) {
BoolQueryBuilder queryBuilder = boolQuery();
AtomicBoolean first = new AtomicBoolean(true);
split(queryText)
.map(queryTerm -> {
if (first.getAndSet(false)) {
return prefixQuery(fieldName, queryTerm);
}
return partialTermQuery(queryTerm, originalFieldName);
})
.forEach(queryBuilder::must);
return queryBuilder;
}
protected MatchQueryBuilder partialTermQuery(String queryTerm, String fieldName) {
// We will truncate the search to the maximum length of nGrams in the index.
// Otherwise the search would for sure not find any results.
String truncatedQuery = StringUtils.left(queryTerm, DefaultIndexSettings.MAXIMUM_NGRAM_LENGTH);
return matchQuery(SEARCH_GRAMS_ANALYZER.subField(fieldName), truncatedQuery);
}
}
}
| 4,936 | 36.401515 | 116 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/measure/index/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.measure.index;
import javax.annotation.ParametersAreNonnullByDefault;
| 970 | 39.458333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/permission/index/PermissionIndexer.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.permission.index;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.es.EsQueueDto;
import org.sonar.server.es.BulkIndexer;
import org.sonar.server.es.BulkIndexer.Size;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.EventIndexer;
import org.sonar.server.es.IndexType;
import org.sonar.server.es.Indexers;
import org.sonar.server.es.IndexingResult;
import org.sonar.server.es.OneToOneResilientIndexingListener;
import org.springframework.beans.factory.annotation.Autowired;
import static java.util.Collections.emptyList;
/**
* Populates the types "authorization" of each index requiring entity
* authorization.
*/
public class PermissionIndexer implements EventIndexer {
private final DbClient dbClient;
private final EsClient esClient;
private final Collection<AuthorizationScope> authorizationScopes;
private final Map<String, IndexType> indexTypeByFormat;
@Autowired(required = false)
public PermissionIndexer(DbClient dbClient, EsClient esClient, NeedAuthorizationIndexer... needAuthorizationIndexers) {
this(dbClient, esClient, Arrays.stream(needAuthorizationIndexers)
.map(NeedAuthorizationIndexer::getAuthorizationScope)
.toList());
}
@VisibleForTesting
@Autowired(required = false)
public PermissionIndexer(DbClient dbClient, EsClient esClient, Collection<AuthorizationScope> authorizationScopes) {
this.dbClient = dbClient;
this.esClient = esClient;
this.authorizationScopes = authorizationScopes;
this.indexTypeByFormat = authorizationScopes.stream()
.map(AuthorizationScope::getIndexType)
.collect(Collectors.toMap(IndexType.IndexMainType::format, Function.identity()));
}
@Override
public Set<IndexType> getIndexTypes() {
return ImmutableSet.copyOf(indexTypeByFormat.values());
}
@Override
public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) {
// TODO do not load everything in memory. Db rows should be scrolled.
List<IndexPermissions> authorizations = getAllAuthorizations();
Stream<AuthorizationScope> scopes = getScopes(uninitializedIndexTypes);
index(authorizations, scopes, Size.LARGE);
}
public void indexAll(Set<IndexType> uninitializedIndexTypes) {
// TODO do not load everything in memory. Db rows should be scrolled.
List<IndexPermissions> authorizations = getAllAuthorizations();
Stream<AuthorizationScope> scopes = getScopes(uninitializedIndexTypes);
index(authorizations, scopes, Size.REGULAR);
}
@VisibleForTesting
void index(List<IndexPermissions> authorizations) {
index(authorizations, authorizationScopes.stream(), Size.REGULAR);
}
@Override
public Collection<EsQueueDto> prepareForRecoveryOnEntityEvent(DbSession dbSession, Collection<String> entityUuids, Indexers.EntityEvent cause) {
return switch (cause) {
case PROJECT_KEY_UPDATE, PROJECT_TAGS_UPDATE ->
// nothing to change. project key and tags are not part of this index
emptyList();
case CREATION, DELETION, PERMISSION_CHANGE -> insertIntoEsQueue(dbSession, entityUuids);
};
}
@Override
public Collection<EsQueueDto> prepareForRecoveryOnBranchEvent(DbSession dbSession, Collection<String> branchUuids, Indexers.BranchEvent cause) {
return emptyList();
}
private Collection<EsQueueDto> insertIntoEsQueue(DbSession dbSession, Collection<String> projectUuids) {
List<EsQueueDto> items = indexTypeByFormat.values().stream()
.flatMap(indexType -> projectUuids.stream().map(projectUuid -> EsQueueDto.create(indexType.format(), AuthorizationDoc.idOf(projectUuid), null, projectUuid)))
.toList();
dbClient.esQueueDao().insert(dbSession, items);
return items;
}
private void index(Collection<IndexPermissions> authorizations, Stream<AuthorizationScope> scopes, Size bulkSize) {
if (authorizations.isEmpty()) {
return;
}
// index each authorization in each scope
scopes.forEach(scope -> {
IndexType indexType = scope.getIndexType();
BulkIndexer bulkIndexer = new BulkIndexer(esClient, indexType, bulkSize);
bulkIndexer.start();
authorizations.stream()
.filter(scope.getEntityPredicate())
.map(dto -> AuthorizationDoc.fromDto(indexType, dto).toIndexRequest())
.forEach(bulkIndexer::add);
bulkIndexer.stop();
});
}
@Override
public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) {
IndexingResult result = new IndexingResult();
List<BulkIndexer> bulkIndexers = items.stream()
.map(EsQueueDto::getDocType)
.distinct()
.map(indexTypeByFormat::get)
.filter(Objects::nonNull)
.map(indexType -> new BulkIndexer(esClient, indexType, Size.REGULAR, new OneToOneResilientIndexingListener(dbClient, dbSession, items)))
.toList();
if (bulkIndexers.isEmpty()) {
return result;
}
bulkIndexers.forEach(BulkIndexer::start);
PermissionIndexerDao permissionIndexerDao = new PermissionIndexerDao();
Set<String> remainingEntityUuids = items.stream().map(EsQueueDto::getDocId)
.map(AuthorizationDoc::entityUuidOf)
.collect(Collectors.toSet());
permissionIndexerDao.selectByUuids(dbClient, dbSession, remainingEntityUuids).forEach(p -> {
remainingEntityUuids.remove(p.getEntityUuid());
bulkIndexers.forEach(bi -> bi.add(AuthorizationDoc.fromDto(bi.getIndexType(), p).toIndexRequest()));
});
// the remaining references on entities that don't exist in db. They must
// be deleted from the index.
remainingEntityUuids.forEach(entityUuid -> bulkIndexers.forEach(bi -> {
String authorizationDocId = AuthorizationDoc.idOf(entityUuid);
bi.addDeletion(bi.getIndexType(), authorizationDocId, authorizationDocId);
}));
bulkIndexers.forEach(b -> result.add(b.stop()));
return result;
}
private Stream<AuthorizationScope> getScopes(Set<IndexType> indexTypes) {
return authorizationScopes.stream()
.filter(scope -> indexTypes.contains(scope.getIndexType()));
}
private List<IndexPermissions> getAllAuthorizations() {
try (DbSession dbSession = dbClient.openSession(false)) {
return new PermissionIndexerDao().selectAll(dbClient, dbSession);
}
}
}
| 7,498 | 37.260204 | 163 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/permission/index/PermissionIndexerDao.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.permission.index;
import com.google.common.collect.ImmutableList;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import static org.apache.commons.lang.StringUtils.repeat;
import static org.sonar.db.DatabaseUtils.executeLargeInputs;
/**
* No streaming because of union of joins -> no need to use ResultSetIterator
*/
public class PermissionIndexerDao {
private enum RowKind {
USER, GROUP, ANYONE, NONE
}
private static final String SQL_TEMPLATE = """
with entity as ((select prj.uuid as uuid,
prj.private as isPrivate,
prj.qualifier as qualifier
from projects prj)
union
(select p.uuid as uuid,
p.private as isPrivate,
'VW' as qualifier
from portfolios p
where p.parent_uuid is null))
SELECT entity_authorization.kind as kind,
entity_authorization.entity as entity,
entity_authorization.user_uuid as user_uuid,
entity_authorization.group_uuid as group_uuid,
entity_authorization.qualifier as qualifier
FROM (SELECT '%s' as kind,
e.uuid AS entity,
e.qualifier AS qualifier,
user_roles.user_uuid AS user_uuid,
NULL AS group_uuid
FROM entity e
INNER JOIN user_roles ON user_roles.entity_uuid = e.uuid AND user_roles.role = 'user'
WHERE (1 = 1)
{entitiesCondition}
UNION
SELECT '%s' as kind, e.uuid AS entity, e.qualifier AS qualifier, NULL AS user_uuid, groups.uuid AS group_uuid
FROM entity e
INNER JOIN group_roles
ON group_roles.entity_uuid = e.uuid AND group_roles.role = 'user'
INNER JOIN groups ON groups.uuid = group_roles.group_uuid
WHERE group_uuid IS NOT NULL
{entitiesCondition}
UNION
SELECT '%s' as kind, e.uuid AS entity, e.qualifier AS qualifier, NULL AS user_uuid, NULL AS group_uuid
FROM entity e
WHERE e.isPrivate = ?
{entitiesCondition}
UNION
SELECT '%s' as kind, e.uuid AS entity, e.qualifier AS qualifier, NULL AS user_uuid, NULL AS group_uuid
FROM entity e
WHERE e.isPrivate = ?
{entitiesCondition}
) entity_authorization""".formatted(RowKind.USER, RowKind.GROUP, RowKind.ANYONE, RowKind.NONE);
List<IndexPermissions> selectAll(DbClient dbClient, DbSession session) {
return doSelectByEntities(dbClient, session, Collections.emptyList());
}
public List<IndexPermissions> selectByUuids(DbClient dbClient, DbSession session, Collection<String> entitiesUuid) {
// we use a smaller partitionSize because the SQL_TEMPLATE contain 4x the list of entity uuid.
// the MsSQL jdbc driver accept a maximum of 2100 prepareStatement parameter. To stay under the limit,
// we go with batch of 1000/2=500 entities uuids, to stay under the limit (4x500 < 2100)
return executeLargeInputs(entitiesUuid, entity -> doSelectByEntities(dbClient, session, entity), i -> i / 2);
}
private static List<IndexPermissions> doSelectByEntities(DbClient dbClient, DbSession session, List<String> entitiesUuids) {
try {
Map<String, IndexPermissions> dtosByEntityUuid = new HashMap<>();
try (PreparedStatement stmt = createStatement(dbClient, session, entitiesUuids);
ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
processRow(rs, dtosByEntityUuid);
}
return ImmutableList.copyOf(dtosByEntityUuid.values());
}
} catch (SQLException e) {
throw new IllegalStateException("Fail to select authorizations", e);
}
}
private static PreparedStatement createStatement(DbClient dbClient, DbSession session, List<String> entityUuids) throws SQLException {
String sql;
if (entityUuids.isEmpty()) {
sql = StringUtils.replace(SQL_TEMPLATE, "{entitiesCondition}", "");
} else {
sql = StringUtils.replace(SQL_TEMPLATE, "{entitiesCondition}", " AND e.uuid in (" + repeat("?", ", ", entityUuids.size()) + ")");
}
PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(session, sql);
int index = 1;
// query for RowKind.USER
index = populateEntityUuidPlaceholders(stmt, entityUuids, index);
// query for RowKind.GROUP
index = populateEntityUuidPlaceholders(stmt, entityUuids, index);
// query for RowKind.ANYONE
index = setPrivateEntityPlaceHolder(stmt, index, false);
index = populateEntityUuidPlaceholders(stmt, entityUuids, index);
// query for RowKind.NONE
index = setPrivateEntityPlaceHolder(stmt, index, true);
populateEntityUuidPlaceholders(stmt, entityUuids, index);
return stmt;
}
private static int populateEntityUuidPlaceholders(PreparedStatement stmt, List<String> entityUuids, int index) throws SQLException {
int newIndex = index;
for (String entityUuid : entityUuids) {
stmt.setString(newIndex, entityUuid);
newIndex++;
}
return newIndex;
}
private static int setPrivateEntityPlaceHolder(PreparedStatement stmt, int index, boolean isPrivate) throws SQLException {
int newIndex = index;
stmt.setBoolean(newIndex, isPrivate);
newIndex++;
return newIndex;
}
private static void processRow(ResultSet rs, Map<String, IndexPermissions> dtosByEntityUuid) throws SQLException {
RowKind rowKind = RowKind.valueOf(rs.getString(1));
String entityUuid = rs.getString(2);
IndexPermissions dto = dtosByEntityUuid.get(entityUuid);
if (dto == null) {
String qualifier = rs.getString(5);
dto = new IndexPermissions(entityUuid, qualifier);
dtosByEntityUuid.put(entityUuid, dto);
}
switch (rowKind) {
case NONE:
break;
case USER:
dto.addUserUuid(rs.getString(3));
break;
case GROUP:
dto.addGroupUuid(rs.getString(4));
break;
case ANYONE:
dto.allowAnyone();
break;
}
}
}
| 7,428 | 40.044199 | 136 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/permission/index/WebAuthorizationTypeSupport.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.permission.index;
import java.util.Optional;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.join.query.JoinQueryBuilders;
import org.sonar.api.server.ServerSide;
import org.sonar.db.user.GroupDto;
import org.sonar.server.user.UserSession;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.sonar.server.permission.index.IndexAuthorizationConstants.FIELD_ALLOW_ANYONE;
import static org.sonar.server.permission.index.IndexAuthorizationConstants.FIELD_GROUP_IDS;
import static org.sonar.server.permission.index.IndexAuthorizationConstants.FIELD_USER_IDS;
import static org.sonar.server.permission.index.IndexAuthorizationConstants.TYPE_AUTHORIZATION;
@ServerSide
public class WebAuthorizationTypeSupport {
private final UserSession userSession;
public WebAuthorizationTypeSupport(UserSession userSession) {
this.userSession = userSession;
}
/**
* Build a filter to restrict query to the documents on which
* user has read access.
*/
public QueryBuilder createQueryFilter() {
BoolQueryBuilder filter = boolQuery();
// anyone
filter.should(QueryBuilders.termQuery(FIELD_ALLOW_ANYONE, true));
// users
Optional.ofNullable(userSession.getUuid())
.ifPresent(uuid -> filter.should(termQuery(FIELD_USER_IDS, uuid)));
// groups
userSession.getGroups()
.stream()
.map(GroupDto::getUuid)
.forEach(groupUuid -> filter.should(termQuery(FIELD_GROUP_IDS, groupUuid)));
return JoinQueryBuilders.hasParentQuery(
TYPE_AUTHORIZATION,
QueryBuilders.boolQuery().filter(filter),
false);
}
}
| 2,686 | 35.808219 | 95 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/main/java/org/sonar/server/permission/index/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.permission.index;
import javax.annotation.ParametersAreNonnullByDefault;
| 973 | 39.583333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexCombinationTest.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.component.index;
import java.util.stream.IntStream;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import org.sonar.db.project.ProjectDto;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
public class ComponentIndexCombinationTest extends ComponentIndexTest {
@Test
public void return_empty_list_if_no_fields_match_query() {
indexProject("struts", "Apache Struts");
assertThat(index.searchSuggestions(SuggestionQuery.builder().setQuery("missing").build()).isEmpty()).isTrue();
}
@Test
public void should_not_return_components_that_do_not_match_at_all() {
indexProject("banana", "Banana Project 1");
assertNoSearchResults("Apple");
}
@Test
public void index_whenQualifierMatchesWhatIsTheIndex_shouldReturnTheProject() {
ProjectDto project = indexProject("struts", "Apache Struts");
assertSearchResults(SuggestionQuery.builder().setQuery("struts").setQualifiers(singletonList(Qualifiers.PROJECT)).build(), project);
}
@Test
public void index_whenQualifierDoesNotMatchWhatIsTheIndex_shouldReturnTheProject() {
ProjectDto project = indexProject("struts", "Apache Struts");
SuggestionQuery query = SuggestionQuery.builder().setQuery("struts").setQualifiers(singletonList(Qualifiers.VIEW)).build();
assertNoSearchResults(query.getQuery(), Qualifiers.VIEW);
}
@Test
public void should_limit_the_number_of_results() {
IntStream.rangeClosed(0, 10).forEach(i -> indexProject("sonarqube" + i, "SonarQube" + i));
assertSearch(SuggestionQuery.builder().setQuery("sonarqube").setLimit(5).setQualifiers(singletonList(Qualifiers.PROJECT)).build()).hasSize(5);
}
@Test
public void should_not_support_wildcards() {
indexProject("theKey", "the name");
assertNoSearchResults("*t*");
assertNoSearchResults("th?Key");
}
}
| 2,755 | 34.792208 | 146 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexFeatureExactTest.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.component.index;
import java.util.Collections;
import org.junit.Before;
import org.junit.Test;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.es.textsearch.ComponentTextSearchFeatureRepertoire;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.sonar.api.resources.Qualifiers.PROJECT;
public class ComponentIndexFeatureExactTest extends ComponentIndexTest {
@Before
public void before() {
features.set(query -> matchAllQuery(), ComponentTextSearchFeatureRepertoire.EXACT_IGNORE_CASE);
}
@Test
public void scoring_cares_about_exact_matches() {
ProjectDto project1 = indexProject("project1", "LongNameLongNameLongNameLongNameSonarQube");
ProjectDto project2 = indexProject("project2", "LongNameLongNameLongNameLongNameSonarQubeX");
SuggestionQuery query1 = SuggestionQuery.builder()
.setQuery("LongNameLongNameLongNameLongNameSonarQube")
.setQualifiers(Collections.singletonList(PROJECT))
.build();
assertSearch(query1).containsExactly(uuids(project1, project2));
}
}
| 1,947 | 37.96 | 99 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexFeatureFavoriteTest.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.component.index;
import org.junit.Before;
import org.junit.Test;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.es.textsearch.ComponentTextSearchFeatureRepertoire;
import static com.google.common.collect.ImmutableSet.of;
import static java.util.Collections.singletonList;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.server.component.index.ComponentIndexDefinition.FIELD_KEY;
public class ComponentIndexFeatureFavoriteTest extends ComponentIndexTest {
@Before
public void before() {
features.set(q -> matchAllQuery(), ComponentTextSearchFeatureRepertoire.FAVORITE);
}
@Test
public void scoring_cares_about_favorites() {
ProjectDto project1 = indexProject("sonarqube", "SonarQube");
ProjectDto project2 = indexProject("recent", "SonarQube Recently");
SuggestionQuery query1 = SuggestionQuery.builder()
.setQuery("SonarQube")
.setQualifiers(singletonList(PROJECT))
.setFavoriteKeys(of(project1.getKey()))
.build();
assertSearch(query1).containsExactly(uuids(project1, project2));
SuggestionQuery query2 = SuggestionQuery.builder()
.setQuery("SonarQube")
.setQualifiers(singletonList(PROJECT))
.setFavoriteKeys(of(project2.getKey()))
.build();
assertSearch(query2).containsExactly(uuids(project2, project1));
}
@Test
public void irrelevant_favorites_are_not_returned() {
features.set(q -> termQuery(FIELD_KEY, "non-existing-value"), ComponentTextSearchFeatureRepertoire.FAVORITE);
ProjectDto project1 = indexProject("foo", "foo");
SuggestionQuery query1 = SuggestionQuery.builder()
.setQuery("bar")
.setQualifiers(singletonList(PROJECT))
.setFavoriteKeys(of(project1.getKey()))
.build();
assertSearch(query1).isEmpty();
}
}
| 2,828 | 37.22973 | 113 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexFeatureKeyTest.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.component.index;
import org.junit.Before;
import org.junit.Test;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.es.textsearch.ComponentTextSearchFeatureRepertoire;
public class ComponentIndexFeatureKeyTest extends ComponentIndexTest {
@Before
public void before() {
features.set(ComponentTextSearchFeatureRepertoire.KEY);
}
@Test
public void should_search_projects_by_exact_case_insensitive_key() {
ProjectDto project1 = indexProject("keyOne", "Project One");
indexProject("keyTwo", "Project Two");
assertSearchResults("keyOne", project1);
assertSearchResults("keyone", project1);
assertSearchResults("KEYone", project1);
}
@Test
public void should_search_project_with_dot_in_key() {
ProjectDto project = indexProject("org.sonarqube", "SonarQube");
assertSearchResults("org.sonarqube", project);
assertNoSearchResults("orgsonarqube");
}
@Test
public void should_search_project_with_dash_in_key() {
ProjectDto project = indexProject("org-sonarqube", "SonarQube");
assertSearchResults("org-sonarqube", project);
assertNoSearchResults("orgsonarqube");
}
@Test
public void should_search_project_with_colon_in_key() {
ProjectDto project = indexProject("org:sonarqube", "Quality Product");
assertSearchResults("org:sonarqube", project);
assertNoSearchResults("orgsonarqube");
assertNoSearchResults("org-sonarqube");
assertNoSearchResults("org_sonarqube");
}
@Test
public void should_search_project_with_all_special_characters_in_key() {
ProjectDto project = indexProject("org.sonarqube:sonar-sérvèr_ç", "SonarQube");
assertSearchResults("org.sonarqube:sonar-sérvèr_ç", project);
}
@Test
public void should_not_return_results_when_searching_by_partial_key() {
indexProject("theKey", "some name");
assertNoSearchResults("theke");
assertNoSearchResults("hekey");
}
}
| 2,788 | 31.811765 | 83 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexFeaturePartialTest.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.component.index;
import org.junit.Before;
import org.junit.Test;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.es.textsearch.ComponentTextSearchFeatureRepertoire;
public class ComponentIndexFeaturePartialTest extends ComponentIndexTest {
@Before
public void before() {
features.set(ComponentTextSearchFeatureRepertoire.PARTIAL);
}
@Test
public void search_projects_by_exact_name() {
ProjectDto struts = indexProject("struts", "Apache Struts");
indexProject("sonarqube", "SonarQube");
assertSearchResults("Apache Struts", struts);
assertSearchResults("APACHE STRUTS", struts);
assertSearchResults("APACHE struTS", struts);
}
@Test
public void should_search_by_name_with_two_characters() {
ProjectDto project = indexProject("struts", "Apache Struts");
assertSearchResults("st", project);
assertSearchResults("tr", project);
}
@Test
public void search_projects_by_partial_name() {
ProjectDto struts = indexProject("struts", "Apache Struts");
assertSearchResults("truts", struts);
assertSearchResults("pache", struts);
assertSearchResults("apach", struts);
assertSearchResults("che stru", struts);
}
@Test
public void search_projects_and_files_by_partial_name() {
ProjectDto project = indexProject("struts", "Apache Struts");
assertSearchResults("struts", project);
assertSearchResults("Struts", project);
}
@Test
public void should_search_for_word_and_suffix() {
assertResultOrder("plugin java", "AbstractPluginFactory.java");
}
@Test
public void should_search_for_word_and_suffix_in_any_order() {
assertResultOrder("java plugin", "AbstractPluginFactory.java");
}
@Test
public void should_search_for_two_words() {
assertResultOrder("abstract factory", "AbstractPluginFactory.java");
}
@Test
public void should_search_for_two_words_in_any_order() {
assertResultOrder("factory abstract", "AbstractPluginFactory.java");
}
@Test
public void should_require_at_least_one_matching_word() {
indexProject("AbstractPluginFactory");
assertNoSearchResults("monitor object");
}
}
| 3,019 | 30.134021 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexFeaturePrefixTest.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.component.index;
import org.junit.Before;
import org.junit.Test;
import org.sonar.server.es.textsearch.ComponentTextSearchFeatureRepertoire;
public class ComponentIndexFeaturePrefixTest extends ComponentIndexTest {
@Before
public void before() {
features.set(ComponentTextSearchFeatureRepertoire.PREFIX, ComponentTextSearchFeatureRepertoire.PREFIX_IGNORE_CASE);
}
@Test
public void should_find_prefix() {
assertResultOrder("comp", "component");
}
@Test
public void should_find_exact_match() {
assertResultOrder("component.js", "component.js");
}
@Test
public void should_not_find_partially() {
indexProject("my_component");
assertNoSearchResults("component.js");
}
@Test
public void should_be_able_to_ignore_case() {
features.set(ComponentTextSearchFeatureRepertoire.PREFIX_IGNORE_CASE);
assertResultOrder("cOmPoNeNt.Js", "CoMpOnEnT.jS");
}
@Test
public void should_prefer_matching_case() {
assertResultOrder("cOmPoNeNt.Js", "cOmPoNeNt.Js", "CoMpOnEnT.jS");
}
}
| 1,907 | 30.278689 | 119 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexFeatureRecentlyBrowsedTest.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.component.index;
import java.util.Collections;
import org.junit.Before;
import org.junit.Test;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.es.textsearch.ComponentTextSearchFeatureRepertoire;
import static com.google.common.collect.ImmutableSet.of;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.sonar.api.resources.Qualifiers.PROJECT;
public class ComponentIndexFeatureRecentlyBrowsedTest extends ComponentIndexTest {
@Before
public void before() {
features.set(query -> matchAllQuery(), ComponentTextSearchFeatureRepertoire.RECENTLY_BROWSED);
}
@Test
public void scoring_cares_about_recently_browsed() {
ProjectDto project1 = indexProject("sonarqube", "SonarQube");
ProjectDto project2 = indexProject("recent", "SonarQube Recently");
SuggestionQuery query1 = SuggestionQuery.builder()
.setQuery("SonarQube")
.setQualifiers(Collections.singletonList(PROJECT))
.setRecentlyBrowsedKeys(of(project1.getKey()))
.build();
assertSearch(query1).containsExactly(uuids(project1, project2));
SuggestionQuery query2 = SuggestionQuery.builder()
.setQuery("SonarQube")
.setQualifiers(Collections.singletonList(PROJECT))
.setRecentlyBrowsedKeys(of(project2.getKey()))
.build();
assertSearch(query2).containsExactly(uuids(project2, project1));
}
}
| 2,260 | 37.322034 | 98 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexHighlightTest.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.component.index;
import java.util.Collections;
import java.util.Optional;
import java.util.stream.Stream;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import static org.assertj.core.api.Assertions.assertThat;
public class ComponentIndexHighlightTest extends ComponentIndexTest {
@Test
public void should_escape_html() {
assertHighlighting("quick< brown fox", "brown", "quick< <mark>brown</mark> fox");
}
@Test
public void should_highlight_partial_name() {
assertHighlighting("quickbrownfox", "brown", "quick<mark>brown</mark>fox");
}
@Test
public void should_highlight_prefix() {
assertHighlighting("quickbrownfox", "quick", "<mark>quick</mark>brownfox");
}
@Test
public void should_highlight_suffix() {
assertHighlighting("quickbrownfox", "fox", "quickbrown<mark>fox</mark>");
}
@Test
public void should_highlight_multiple_words() {
assertHighlighting("quickbrownfox", "fox bro", "quick<mark>bro</mark>wn<mark>fox</mark>");
}
@Test
public void should_highlight_multiple_connected_words() {
assertHighlighting("quickbrownfox", "fox brown", "quick<mark>brownfox</mark>");
}
private void assertHighlighting(String projectName, String search, String expectedHighlighting) {
indexProject(projectName, projectName);
SuggestionQuery query = SuggestionQuery.builder()
.setQuery(search)
.setQualifiers(Collections.singletonList(Qualifiers.PROJECT))
.build();
Stream<ComponentHitsPerQualifier> results = index.searchSuggestions(query, features.get()).getQualifiers();
assertThat(results).flatExtracting(ComponentHitsPerQualifier::getHits)
.extracting(ComponentHit::getHighlightedText)
.extracting(Optional::get)
.containsExactly(expectedHighlighting);
}
}
| 2,667 | 33.649351 | 111 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexLoginTest.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.component.index;
import org.junit.Test;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import static org.sonar.db.user.GroupTesting.newGroupDto;
import static org.sonar.db.user.UserTesting.newUserDto;
public class ComponentIndexLoginTest extends ComponentIndexTest {
@Test
public void should_filter_unauthorized_results() {
indexer.index(newProject("sonarqube", "Quality Product"));
// do not give any permissions to that project
assertNoSearchResults("sonarqube");
assertNoSearchResults("Quality Product");
}
@Test
public void should_find_project_for_which_the_user_has_direct_permission() {
UserDto user = newUserDto();
userSession.logIn(user);
EntityDto project = newProject("sonarqube", "Quality Product");
indexer.index(project);
assertNoSearchResults("sonarqube");
// give the user explicit access
authorizationIndexerTester.allowOnlyUser(project, user);
assertSearchResults("sonarqube", project);
}
@Test
public void should_find_project_for_which_the_user_has_indirect_permission_through_group() {
GroupDto group = newGroupDto();
userSession.logIn().setGroups(group);
EntityDto project = newProject("sonarqube", "Quality Product");
indexer.index(project);
assertNoSearchResults("sonarqube");
// give the user implicit access (though group)
authorizationIndexerTester.allowOnlyGroup(project, group);
assertSearchResults("sonarqube", project);
}
}
| 2,394 | 31.808219 | 94 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexMultipleWordsTest.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.component.index;
import org.junit.Test;
import org.sonar.server.es.textsearch.ComponentTextSearchFeatureRepertoire;
public class ComponentIndexMultipleWordsTest extends ComponentIndexTest {
@Test
public void should_find_perfect_match() {
assertResultOrder("struts java",
"Struts.java");
}
@Test
public void should_find_partial_match() {
features.set(ComponentTextSearchFeatureRepertoire.PARTIAL);
assertResultOrder("struts java",
"Xstrutsx.Xjavax");
}
@Test
public void should_find_partial_match_prefix_word1() {
assertResultOrder("struts java",
"MyStruts.java");
}
@Test
public void should_find_partial_match_suffix_word1() {
assertResultOrder("struts java",
"StrutsObject.java");
}
@Test
public void should_find_partial_match_prefix_word2() {
assertResultOrder("struts java",
"MyStruts.xjava");
}
@Test
public void should_find_partial_match_suffix_word2() {
assertResultOrder("struts java",
"MyStruts.javax");
}
@Test
public void should_find_partial_match_prefix_and_suffix_everywhere() {
assertResultOrder("struts java",
"MyStrutsObject.xjavax");
}
@Test
public void should_find_subset_of_document_terms() {
assertResultOrder("struts java",
"Some.Struts.Class.java.old");
}
}
| 2,191 | 27.102564 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexScoreTest.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.component.index;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.es.textsearch.ComponentTextSearchFeatureRepertoire;
import static org.sonar.api.resources.Qualifiers.PROJECT;
public class ComponentIndexScoreTest extends ComponentIndexTest {
@Test
public void should_prefer_components_without_prefix() {
assertResultOrder("File.java",
"File.java",
"MyFile.java");
}
@Test
public void should_prefer_components_without_suffix() {
assertResultOrder("File",
"File",
"Filex");
}
@Test
public void should_prefer_key_matching_over_name_matching() {
es.recreateIndexes();
ProjectDto project1 = indexProject("quality", "SonarQube");
ProjectDto project2 = indexProject("sonarqube", "Quality Product");
assertExactResults("sonarqube", project2, project1);
}
@Test
public void should_prefer_prefix_matching_over_partial_matching() {
assertResultOrder("corem",
"CoreMetrics.java",
"ScoreMatrix.java");
}
@Test
public void should_prefer_case_sensitive_prefix() {
assertResultOrder("caSe",
"caSeBla.java",
"CaseBla.java");
}
@Test
public void scoring_prefix_with_multiple_words() {
assertResultOrder("index java",
"IndexSomething.java",
"MyIndex.java");
}
@Test
public void scoring_prefix_with_multiple_words_and_case() {
assertResultOrder("Index JAVA",
"IndexSomething.java",
"index_java.js");
}
@Test
public void scoring_long_items() {
assertResultOrder("ThisIsAVeryLongNameToSearchForAndItExceeds15Characters.java",
"ThisIsAVeryLongNameToSearchForAndItExceeds15Characters.java",
"ThisIsAVeryLongNameToSearchForAndItEndsDifferently.java");
}
@Test
public void scoring_perfect_match() {
assertResultOrder("SonarQube",
"SonarQube",
"SonarQube SCM Git");
}
@Test
public void scoring_perfect_match_dispite_case_changes() {
assertResultOrder("sonarqube",
"SonarQube",
"SonarQube SCM Git");
}
@Test
public void scoring_perfect_match_with_matching_case_higher_than_without_matching_case() {
assertResultOrder("sonarqube",
"sonarqube",
"SonarQube");
}
@Test
public void should_prefer_favorite_over_recently_browsed() {
ProjectDto project1 = db.components().insertPrivateProject(c -> c.setName("File1")).getProjectDto();
index(project1);
ProjectDto project2 = db.components().insertPrivateProject(c -> c.setName("File2")).getProjectDto();
index(project2);
assertSearch(SuggestionQuery.builder()
.setQuery("File")
.setQualifiers(List.of(PROJECT))
.setRecentlyBrowsedKeys(Set.of(project1.getKey()))
.setFavoriteKeys(Set.of(project2.getKey()))
.build()).containsExactly(uuids(project2, project1));
assertSearch(SuggestionQuery.builder()
.setQuery("File")
.setQualifiers(List.of(PROJECT))
.setRecentlyBrowsedKeys(Set.of(project2.getKey()))
.setFavoriteKeys(Set.of(project1.getKey()))
.build()).containsExactly(uuids(project1, project2));
}
@Test
public void if_relevancy_is_equal_fall_back_to_alphabetical_ordering() {
assertResultOrder("sonarqube",
"sonarqubeA",
"sonarqubeB");
}
@Test
public void scoring_test_DbTester() {
features.set(ComponentTextSearchFeatureRepertoire.PARTIAL);
ProjectDto project = indexProject("key-1", "Quality Product");
assertSearch("dbt").isEmpty();
}
}
| 4,402 | 28.550336 | 104 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexSearchTest.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.component.index;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ProjectData;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.SearchIdResult;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.es.textsearch.ComponentTextSearchFeatureRule;
import org.sonar.server.permission.index.PermissionIndexerTester;
import org.sonar.server.permission.index.WebAuthorizationTypeSupport;
import org.sonar.server.tester.UserSessionRule;
import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
public class ComponentIndexSearchTest {
@Rule
public EsTester es = EsTester.create();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone().logIn();
@Rule
public ComponentTextSearchFeatureRule features = new ComponentTextSearchFeatureRule();
private final EntityDefinitionIndexer indexer = new EntityDefinitionIndexer(db.getDbClient(), es.client());
private final PermissionIndexerTester authorizationIndexerTester = new PermissionIndexerTester(es, indexer);
private final ComponentIndex underTest = new ComponentIndex(es.client(), new WebAuthorizationTypeSupport(userSession), System2.INSTANCE);
@Test
public void filter_by_name() {
ProjectData ignoredProject = db.components().insertPrivateProject(p -> p.setName("ignored project"));
ProjectData project = db.components().insertPrivateProject(p -> p.setName("Project Shiny name"));
index(ignoredProject.getProjectDto(), project.getProjectDto());
SearchIdResult<String> result = underTest.search(ComponentQuery.builder().setQuery("shiny").build(), new SearchOptions());
assertThat(result.getUuids()).containsExactlyInAnyOrder(project.projectUuid());
}
@Test
public void filter_by_key_with_exact_match() {
ProjectData ignoredProject = db.components().insertPrivateProject(p -> p.setKey("ignored-project"));
ProjectData project = db.components().insertPrivateProject(p -> p.setKey("shiny-project"));
db.components().insertPrivateProject(p -> p.setKey("another-shiny-project")).getMainBranchComponent();
index(ignoredProject.getProjectDto(), project.getProjectDto());
SearchIdResult<String> result = underTest.search(ComponentQuery.builder().setQuery("shiny-project").build(), new SearchOptions());
assertThat(result.getUuids()).containsExactlyInAnyOrder(project.projectUuid());
}
@Test
public void filter_by_qualifier() {
ProjectData project = db.components().insertPrivateProject();
ComponentDto portfolio = db.components().insertPrivatePortfolio();
index(project.getProjectDto());
index(db.components().getPortfolioDto(portfolio));
SearchIdResult<String> result = underTest.search(ComponentQuery.builder().setQualifiers(singleton(Qualifiers.PROJECT)).build(), new SearchOptions());
assertThat(result.getUuids()).containsExactlyInAnyOrder(project.projectUuid());
}
@Test
public void order_by_name_case_insensitive() {
ProjectData project2 = db.components().insertPrivateProject(p -> p.setName("PROJECT 2"));
ProjectData project3 = db.components().insertPrivateProject(p -> p.setName("project 3"));
ProjectData project1 = db.components().insertPrivateProject(p -> p.setName("Project 1"));
index(project1.getProjectDto(), project2.getProjectDto(), project3.getProjectDto());
SearchIdResult<String> result = underTest.search(ComponentQuery.builder().build(), new SearchOptions());
assertThat(result.getUuids()).containsExactly(project1.projectUuid(),
project2.projectUuid(),
project3.projectUuid());
}
@Test
public void paginate_results() {
List<ProjectData> projects = IntStream.range(0, 9)
.mapToObj(i -> db.components().insertPrivateProject(p -> p.setName("project " + i)))
.toList();
ProjectDto[] projectDtos = projects.stream().map(p -> p.getProjectDto()).toArray(ProjectDto[]::new);
index(projectDtos);
SearchIdResult<String> result = underTest.search(ComponentQuery.builder().build(), new SearchOptions().setPage(2, 3));
assertThat(result.getUuids()).containsExactlyInAnyOrder(projects.get(3).projectUuid(),
projects.get(4).projectUuid(),
projects.get(5).projectUuid());
}
@Test
public void filter_unauthorized_components() {
ProjectDto unauthorizedProject = db.components().insertPrivateProject().getProjectDto();
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
ProjectDto project2 = db.components().insertPrivateProject().getProjectDto();
indexer.indexAll();
authorizationIndexerTester.allowOnlyAnyone(project1);
authorizationIndexerTester.allowOnlyAnyone(project2);
SearchIdResult<String> result = underTest.search(ComponentQuery.builder().build(), new SearchOptions());
assertThat(result.getUuids()).containsExactlyInAnyOrder(project1.getUuid(), project2.getUuid())
.doesNotContain(unauthorizedProject.getUuid());
}
private void index(EntityDto... components) {
indexer.indexAll();
Arrays.stream(components).forEach(authorizationIndexerTester::allowOnlyAnyone);
}
}
| 6,382 | 43.636364 | 153 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexSearchWindowExceededTest.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.component.index;
import java.util.stream.IntStream;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.SearchIdResult;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.permission.index.WebAuthorizationTypeSupport;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.server.component.index.ComponentIndexDefinition.TYPE_COMPONENT;
public class ComponentIndexSearchWindowExceededTest {
@Rule
public EsTester es = EsTester.create();
private final WebAuthorizationTypeSupport authorizationTypeSupport = mock(WebAuthorizationTypeSupport.class);
private final ComponentIndex underTest = new ComponentIndex(es.client(), authorizationTypeSupport, System2.INSTANCE);
@Test
public void returns_correct_total_number_if_default_index_window_exceeded() {
// bypassing the permission check, to have easily 12_000 elements searcheable without having to inserting them + permission.
when(authorizationTypeSupport.createQueryFilter()).thenReturn(QueryBuilders.matchAllQuery());
index(IntStream.range(0, 12_000)
.mapToObj(i -> newDoc(ComponentTesting.newPublicProjectDto()))
.toArray(ComponentDoc[]::new));
SearchIdResult<String> result = underTest.search(ComponentQuery.builder().build(), new SearchOptions().setPage(2, 3));
assertThat(result.getTotal()).isEqualTo(12_000);
}
private void index(ComponentDoc... componentDocs) {
es.putDocuments(TYPE_COMPONENT.getMainType(), componentDocs);
}
private ComponentDoc newDoc(ComponentDto componentDoc) {
return new ComponentDoc()
.setId(componentDoc.uuid())
.setKey(componentDoc.getKey())
.setName(componentDoc.name())
.setQualifier(componentDoc.qualifier());
}
}
| 2,921 | 40.15493 | 128 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/component/index/ComponentIndexTest.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.component.index;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import org.assertj.core.api.ListAssert;
import org.junit.Rule;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.textsearch.ComponentTextSearchFeatureRule;
import org.sonar.server.permission.index.PermissionIndexerTester;
import org.sonar.server.permission.index.WebAuthorizationTypeSupport;
import org.sonar.server.tester.UserSessionRule;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.resources.Qualifiers.FILE;
import static org.sonar.api.resources.Qualifiers.PROJECT;
public abstract class ComponentIndexTest {
@Rule
public EsTester es = EsTester.create();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public ComponentTextSearchFeatureRule features = new ComponentTextSearchFeatureRule();
protected EntityDefinitionIndexer indexer = new EntityDefinitionIndexer(db.getDbClient(), es.client());
protected ComponentIndex index = new ComponentIndex(es.client(), new WebAuthorizationTypeSupport(userSession), System2.INSTANCE);
protected PermissionIndexerTester authorizationIndexerTester = new PermissionIndexerTester(es, indexer);
protected void assertResultOrder(String query, String... resultsInOrder) {
List<ProjectDto> projects = Arrays.stream(resultsInOrder)
.map(r -> db.components().insertPublicProject(c -> c.setName(r)).getProjectDto())
.toList();
// index them, but not in the expected order
projects.stream()
.sorted(Comparator.comparing(ProjectDto::getUuid).reversed())
.forEach(this::index);
assertExactResults(query, projects.toArray(new ProjectDto[0]));
}
protected ListAssert<String> assertSearch(String query) {
return assertSearch(SuggestionQuery.builder().setQuery(query).setQualifiers(asList(PROJECT, FILE)).build());
}
protected ListAssert<String> assertSearch(SuggestionQuery query) {
return (ListAssert<String>) assertThat(index.searchSuggestions(query, features.get()).getQualifiers())
.flatExtracting(ComponentHitsPerQualifier::getHits)
.extracting(ComponentHit::getUuid);
}
protected void assertSearchResults(String query, EntityDto... expectedComponents) {
assertSearchResults(query, List.of(PROJECT), expectedComponents);
}
protected void assertSearchResults(String query, List<String> queryQualifiers, EntityDto... expectedComponents) {
assertSearchResults(SuggestionQuery.builder().setQuery(query).setQualifiers(queryQualifiers).build(), expectedComponents);
}
protected void assertSearchResults(SuggestionQuery query, EntityDto... expectedComponents) {
assertSearch(query).containsOnly(uuids(expectedComponents));
}
protected void assertExactResults(String query, ProjectDto... expectedComponents) {
assertSearch(query).containsExactly(uuids(expectedComponents));
}
protected void assertNoSearchResults(String query, String... qualifiers) {
assertSearchResults(query, List.of(qualifiers));
}
protected ProjectDto indexProject(String name) {
return indexProject(name, name);
}
protected ProjectDto indexProject(String key, String name) {
return index(db.components().insertPublicProject("UUID" + key, c -> c.setKey(key).setName(name)).getProjectDto());
}
protected EntityDto newProject(String key, String name) {
return db.components().insertPublicProject("UUID_" + key, c -> c.setKey(key).setName(name)).getProjectDto();
}
protected ProjectDto index(ProjectDto dto) {
indexer.index(dto);
authorizationIndexerTester.allowOnlyAnyone(dto);
return dto;
}
protected static String[] uuids(EntityDto... expectedComponents) {
return Arrays.stream(expectedComponents).map(EntityDto::getUuid).toArray(String[]::new);
}
}
| 4,940 | 39.170732 | 131 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/es/IndexCreatorTest.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.es;
import java.util.Map;
import java.util.function.Consumer;
import javax.annotation.CheckForNull;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest;
import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.indices.GetMappingsRequest;
import org.elasticsearch.cluster.metadata.MappingMetadata;
import org.elasticsearch.common.settings.Settings;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.server.es.IndexType.IndexMainType;
import org.sonar.server.es.metadata.MetadataIndex;
import org.sonar.server.es.metadata.MetadataIndexDefinition;
import org.sonar.server.es.metadata.MetadataIndexImpl;
import org.sonar.server.es.newindex.NewRegularIndex;
import org.sonar.server.es.newindex.SettingsConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.es.IndexType.main;
import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder;
public class IndexCreatorTest {
private static final SettingsConfiguration SETTINGS_CONFIGURATION = newBuilder(new MapSettings().asConfig()).build();
private static final String LOG_DB_VENDOR_CHANGED = "Delete Elasticsearch indices (DB vendor changed)";
private static final String LOG_DB_SCHEMA_CHANGED = "Delete Elasticsearch indices (DB schema changed)";
@Rule
public LogTester logTester = new LogTester();
@Rule
public EsTester es = EsTester.createCustom();
private final MetadataIndexDefinition metadataIndexDefinition = new MetadataIndexDefinition(new MapSettings().asConfig());
private final MetadataIndex metadataIndex = new MetadataIndexImpl(es.client());
private final TestEsDbCompatibility esDbCompatibility = new TestEsDbCompatibility();
private final MapSettings settings = new MapSettings();
@Test
public void create_index() {
IndexCreator underTest = run(new FakeIndexDefinition());
// check that index is created with related mapping
verifyFakeIndexV1();
// of course do not delete indices on stop
underTest.stop();
assertThat(mappings()).isNotEmpty();
}
@Test
public void recreate_index_on_definition_changes() {
// v1
run(new FakeIndexDefinition());
IndexMainType fakeIndexType = main(Index.simple("fakes"), "fake");
String id = "1";
es.client().index(new IndexRequest(fakeIndexType.getIndex().getName()).id(id).source(new FakeDoc().getFields())
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE));
assertThat(es.client().get(new GetRequest(fakeIndexType.getIndex().getName()).id(id)).isExists()).isTrue();
// v2
run(new FakeIndexDefinitionV2());
Map<String, MappingMetadata> mappings = mappings();
MappingMetadata mapping = mappings.get("fakes");
assertThat(countMappingFields(mapping)).isEqualTo(3);
assertThat(field(mapping, "updatedAt")).containsEntry("type", "date");
assertThat(field(mapping, "newField")).containsEntry("type", "integer");
assertThat(es.client().get(new GetRequest(fakeIndexType.getIndex().getName()).id(id)).isExists()).isFalse();
}
@Test
public void mark_all_non_existing_index_types_as_uninitialized() {
Index fakesIndex = Index.simple("fakes");
Index fakersIndex = Index.simple("fakers");
run(context -> {
context.create(fakesIndex, SETTINGS_CONFIGURATION)
.createTypeMapping(IndexType.main(fakesIndex, "fake"));
context.create(fakersIndex, SETTINGS_CONFIGURATION)
.createTypeMapping(IndexType.main(fakersIndex, "faker"));
});
assertThat(metadataIndex.getHash(fakesIndex)).isNotEmpty();
assertThat(metadataIndex.getHash(fakersIndex)).isNotEmpty();
assertThat(metadataIndex.getInitialized(main(fakesIndex, "fake"))).isFalse();
assertThat(metadataIndex.getInitialized(main(fakersIndex, "faker"))).isFalse();
}
@Test
public void delete_existing_indices_if_db_vendor_changed() {
testDeleteOnDbChange(LOG_DB_VENDOR_CHANGED,
c -> c.setHasSameDbVendor(false));
}
@Test
public void do_not_check_db_compatibility_on_fresh_es() {
// supposed to be ignored
esDbCompatibility.setHasSameDbVendor(false);
run(new FakeIndexDefinition());
assertThat(logTester.logs(Level.INFO))
.doesNotContain(LOG_DB_VENDOR_CHANGED)
.doesNotContain(LOG_DB_SCHEMA_CHANGED)
.contains("Create mapping fakes")
.contains("Create mapping metadatas");
}
@Test
public void start_makes_metadata_index_read_write_if_read_only() {
run(new FakeIndexDefinition());
IndexMainType mainType = MetadataIndexDefinition.TYPE_METADATA;
makeReadOnly(mainType);
run(new FakeIndexDefinition());
assertThat(isNotReadOnly(mainType)).isTrue();
}
@Test
public void start_makes_index_read_write_if_read_only() {
FakeIndexDefinition fakeIndexDefinition = new FakeIndexDefinition();
IndexMainType fakeIndexMainType = FakeIndexDefinition.INDEX_TYPE.getMainType();
run(fakeIndexDefinition);
IndexMainType mainType = MetadataIndexDefinition.TYPE_METADATA;
makeReadOnly(mainType);
makeReadOnly(fakeIndexMainType);
run(fakeIndexDefinition);
assertThat(isNotReadOnly(mainType)).isTrue();
assertThat(isNotReadOnly(fakeIndexMainType)).isTrue();
}
private boolean isNotReadOnly(IndexMainType mainType) {
String indexName = mainType.getIndex().getName();
String readOnly = es.client().getSettings(new GetSettingsRequest().indices(indexName))
.getSetting(indexName, "index.blocks.read_only_allow_delete");
return readOnly == null;
}
private void makeReadOnly(IndexMainType mainType) {
Settings.Builder builder = Settings.builder();
builder.put("index.blocks.read_only_allow_delete", "true");
es.client().putSettings(new UpdateSettingsRequest().indices(mainType.getIndex().getName()).settings(builder.build()));
}
private void testDeleteOnDbChange(String expectedLog, Consumer<TestEsDbCompatibility> afterFirstStart) {
run(new FakeIndexDefinition());
assertThat(logTester.logs(Level.INFO))
.doesNotContain(expectedLog)
.contains("Create mapping fakes")
.contains("Create mapping metadatas");
putFakeDocument();
assertThat(es.countDocuments(FakeIndexDefinition.INDEX_TYPE)).isOne();
afterFirstStart.accept(esDbCompatibility);
logTester.clear();
run(new FakeIndexDefinition());
assertThat(logTester.logs(Level.INFO))
.contains(expectedLog)
.contains("Create mapping fakes")
// keep existing metadata
.doesNotContain("Create mapping metadatas");
// index has been dropped and re-created
assertThat(es.countDocuments(FakeIndexDefinition.INDEX_TYPE)).isZero();
}
private Map<String, MappingMetadata> mappings() {
return es.client().getMapping(new GetMappingsRequest()).mappings();
}
@CheckForNull
@SuppressWarnings("unchecked")
private Map<String, Object> field(MappingMetadata mapping, String field) {
Map<String, Object> props = (Map<String, Object>) mapping.getSourceAsMap().get("properties");
return (Map<String, Object>) props.get(field);
}
private int countMappingFields(MappingMetadata mapping) {
return ((Map) mapping.getSourceAsMap().get("properties")).size();
}
private IndexCreator run(IndexDefinition... definitions) {
IndexDefinitions defs = new IndexDefinitions(definitions, new MapSettings().asConfig());
defs.start();
IndexCreator creator = new IndexCreator(es.client(), defs, metadataIndexDefinition, metadataIndex, esDbCompatibility);
creator.start();
return creator;
}
private void putFakeDocument() {
es.putDocuments(FakeIndexDefinition.INDEX_TYPE, Map.of("key", "foo"));
}
private void verifyFakeIndexV1() {
Map<String, MappingMetadata> mappings = mappings();
MappingMetadata mapping = mappings.get("fakes");
assertThat(mapping.getSourceAsMap()).isNotEmpty();
assertThat(countMappingFields(mapping)).isEqualTo(2);
assertThat(field(mapping, "updatedAt")).containsEntry("type", "date");
}
private static class FakeIndexDefinition implements IndexDefinition {
static final IndexMainType INDEX_TYPE = main(Index.simple("fakes"), "fake");
@Override
public void define(IndexDefinitionContext context) {
Index index = Index.simple("fakes");
NewRegularIndex newIndex = context.create(index, SETTINGS_CONFIGURATION);
newIndex.createTypeMapping(IndexType.main(index, "fake"))
.keywordFieldBuilder("key").build()
.createDateTimeField("updatedAt");
}
}
private static class FakeIndexDefinitionV2 implements IndexDefinition {
@Override
public void define(IndexDefinitionContext context) {
Index index = Index.simple("fakes");
NewRegularIndex newIndex = context.create(index, SETTINGS_CONFIGURATION);
newIndex.createTypeMapping(IndexType.main(index, "fake"))
.keywordFieldBuilder("key").build()
.createDateTimeField("updatedAt")
.createIntegerField("newField");
}
}
}
| 10,172 | 38.126923 | 124 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/es/RecoveryIndexerTest.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.es;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.slf4j.event.Level;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.utils.MessageException;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.es.EsQueueDto;
import org.sonar.server.es.IndexType.IndexMainType;
import org.sonar.server.rule.index.RuleIndexer;
import static java.util.stream.IntStream.rangeClosed;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import static org.slf4j.event.Level.ERROR;
import static org.slf4j.event.Level.INFO;
import static org.slf4j.event.Level.TRACE;
public class RecoveryIndexerTest {
private static final long PAST = 1_000L;
private static final IndexMainType FOO_TYPE = IndexType.main(Index.simple("foos"), "foo");
private TestSystem2 system2 = new TestSystem2().setNow(PAST);
private MapSettings emptySettings = new MapSettings();
@Rule
public EsTester es = EsTester.createCustom();
@Rule
public DbTester db = DbTester.create(system2);
@Rule
public LogTester logTester = new LogTester().setLevel(TRACE);
@Rule
public TestRule safeguard = new DisableOnDebug(Timeout.builder().withTimeout(60, TimeUnit.SECONDS).withLookingForStuckThread(true).build());
private RecoveryIndexer underTest;
@Before
public void before() {
logTester.setLevel(TRACE);
}
@After
public void tearDown() {
if (underTest != null) {
underTest.stop();
}
}
@Test
public void display_default_configuration_at_startup() {
underTest = newRecoveryIndexer(emptySettings.asConfig());
underTest.start();
underTest.stop();
assertThat(logTester.logs(Level.DEBUG)).contains(
"Elasticsearch recovery - sonar.search.recovery.delayInMs=300000",
"Elasticsearch recovery - sonar.search.recovery.minAgeInMs=300000");
}
@Test
public void start_triggers_recovery_run_at_fixed_rate() throws Exception {
MapSettings settings = new MapSettings()
.setProperty("sonar.search.recovery.initialDelayInMs", "0")
.setProperty("sonar.search.recovery.delayInMs", "1");
underTest = spy(new RecoveryIndexer(system2, settings.asConfig(), db.getDbClient()));
AtomicInteger calls = new AtomicInteger(0);
doAnswer(invocation -> {
calls.incrementAndGet();
return null;
}).when(underTest).recover();
underTest.start();
// wait for 2 runs
while (calls.get() < 2) {
Thread.sleep(1L);
}
}
@Test
public void successfully_recover_indexing_requests() {
EsQueueDto item1a = insertItem(FOO_TYPE, "f1");
EsQueueDto item1b = insertItem(FOO_TYPE, "f2");
IndexMainType type2 = IndexType.main(Index.simple("bars"), "bar");
EsQueueDto item2 = insertItem(type2, "b1");
SuccessfulFakeIndexer indexer1 = new SuccessfulFakeIndexer(FOO_TYPE);
SuccessfulFakeIndexer indexer2 = new SuccessfulFakeIndexer(type2);
advanceInTime();
underTest = newRecoveryIndexer(indexer1, indexer2);
underTest.recover();
assertThatQueueHasSize(0);
assertThatLogsContain(INFO, "Elasticsearch recovery - 3 documents processed [0 failures]");
assertThat(indexer1.called).hasSize(1);
assertThat(indexer1.called.get(0))
.extracting(EsQueueDto::getUuid)
.containsExactlyInAnyOrder(item1a.getUuid(), item1b.getUuid());
assertThatLogsContain(TRACE, "Elasticsearch recovery - processing 2 [foos/foo]");
assertThat(indexer2.called).hasSize(1);
assertThat(indexer2.called.get(0))
.extracting(EsQueueDto::getUuid)
.containsExactlyInAnyOrder(item2.getUuid());
assertThatLogsContain(TRACE, "Elasticsearch recovery - processing 1 [bars/bar]");
}
@Test
public void recent_records_are_not_recovered() {
EsQueueDto item = insertItem(FOO_TYPE, "f1");
SuccessfulFakeIndexer indexer = new SuccessfulFakeIndexer(FOO_TYPE);
// do not advance in time
underTest = newRecoveryIndexer(indexer);
underTest.recover();
assertThatQueueHasSize(1);
assertThat(indexer.called).isEmpty();
assertThatLogsDoNotContain(TRACE, "Elasticsearch recovery - processing 2 [foos/foo]");
assertThatLogsDoNotContain(INFO, "documents processed");
}
@Test
public void do_nothing_if_queue_is_empty() {
underTest = newRecoveryIndexer();
underTest.recover();
assertThatNoLogsFromRecovery(INFO);
assertThatNoLogsFromRecovery(ERROR);
assertThatQueueHasSize(0);
}
@Test
public void hard_failures_are_logged_and_do_not_stop_recovery_scheduling() throws Exception {
insertItem(FOO_TYPE, "f1");
HardFailingFakeIndexer indexer = new HardFailingFakeIndexer(FOO_TYPE);
advanceInTime();
underTest = newRecoveryIndexer(indexer);
underTest.start();
// all runs fail, but they are still scheduled
// -> waiting for 2 runs
while (indexer.called.size() < 2) {
Thread.sleep(1L);
}
underTest.stop();
// No rows treated
assertThatQueueHasSize(1);
assertThatLogsContain(ERROR, "Elasticsearch recovery - fail to recover documents");
}
@Test
public void soft_failures_are_logged_and_do_not_stop_recovery_scheduling() throws Exception {
insertItem(FOO_TYPE, "f1");
SoftFailingFakeIndexer indexer = new SoftFailingFakeIndexer(FOO_TYPE);
advanceInTime();
underTest = newRecoveryIndexer(indexer);
underTest.start();
// all runs fail, but they are still scheduled
// -> waiting for 2 runs
while (indexer.called.size() < 2) {
Thread.sleep(1L);
}
underTest.stop();
// No rows treated
assertThatQueueHasSize(1);
assertThatLogsContain(INFO, "Elasticsearch recovery - 1 documents processed [1 failures]");
}
@Test
public void unsupported_types_are_kept_in_queue_for_manual_fix_operation() {
insertItem(FOO_TYPE, "f1");
ResilientIndexer indexer = new SuccessfulFakeIndexer(IndexType.main(Index.simple("bars"), "bar"));
advanceInTime();
underTest = newRecoveryIndexer(indexer);
underTest.recover();
assertThatQueueHasSize(1);
assertThatLogsContain(ERROR, "Elasticsearch recovery - ignore 1 items with unsupported type [foos/foo]");
}
@Test
public void stop_run_if_too_many_failures() {
IntStream.range(0, 10).forEach(i -> insertItem(FOO_TYPE, "" + i));
advanceInTime();
// 10 docs to process, by groups of 3.
// The first group successfully recovers only 1 docs --> above 30% of failures --> stop run
PartiallyFailingIndexer indexer = new PartiallyFailingIndexer(FOO_TYPE, 1);
MapSettings settings = new MapSettings()
.setProperty("sonar.search.recovery.loopLimit", "3");
underTest = newRecoveryIndexer(settings.asConfig(), indexer);
underTest.recover();
assertThatLogsContain(ERROR, "Elasticsearch recovery - too many failures [2/3 documents], waiting for next run");
assertThatQueueHasSize(9);
// The indexer must have been called once and only once.
assertThat(indexer.called).hasSize(3);
}
@Test
public void do_not_stop_run_if_success_rate_is_greater_than_circuit_breaker() {
IntStream.range(0, 10).forEach(i -> insertItem(FOO_TYPE, "" + i));
advanceInTime();
// 10 docs to process, by groups of 5.
// Each group successfully recovers 4 docs --> below 30% of failures --> continue run
PartiallyFailingIndexer indexer = new PartiallyFailingIndexer(FOO_TYPE, 4, 4, 2);
MapSettings settings = new MapSettings()
.setProperty("sonar.search.recovery.loopLimit", "5");
underTest = newRecoveryIndexer(settings.asConfig(), indexer);
underTest.recover();
assertThatLogsDoNotContain(ERROR, "too many failures");
assertThatQueueHasSize(0);
assertThat(indexer.indexed).hasSize(10);
assertThat(indexer.called).hasSize(10 + 2 /* retries */);
}
@Test
public void failing_always_on_same_document_does_not_generate_infinite_loop() {
EsQueueDto buggy = insertItem(FOO_TYPE, "buggy");
IntStream.range(0, 10).forEach(i -> insertItem(FOO_TYPE, "" + i));
advanceInTime();
FailingAlwaysOnSameElementIndexer indexer = new FailingAlwaysOnSameElementIndexer(FOO_TYPE, buggy);
underTest = newRecoveryIndexer(indexer);
underTest.recover();
assertThatLogsContain(ERROR, "Elasticsearch recovery - too many failures [1/1 documents], waiting for next run");
assertThatQueueHasSize(1);
}
@Test
public void recover_multiple_times_the_same_document() {
EsQueueDto item1 = insertItem(FOO_TYPE, "f1");
EsQueueDto item2 = insertItem(FOO_TYPE, item1.getDocId());
EsQueueDto item3 = insertItem(FOO_TYPE, item1.getDocId());
advanceInTime();
SuccessfulFakeIndexer indexer = new SuccessfulFakeIndexer(FOO_TYPE);
underTest = newRecoveryIndexer(indexer);
underTest.recover();
assertThatQueueHasSize(0);
assertThat(indexer.called).hasSize(1);
assertThat(indexer.called.get(0)).extracting(EsQueueDto::getUuid)
.containsExactlyInAnyOrder(item1.getUuid(), item2.getUuid(), item3.getUuid());
assertThatLogsContain(TRACE, "Elasticsearch recovery - processing 3 [foos/foo]");
assertThatLogsContain(INFO, "Elasticsearch recovery - 3 documents processed [0 failures]");
}
private class FailingAlwaysOnSameElementIndexer implements ResilientIndexer {
private final IndexType indexType;
private final EsQueueDto failing;
FailingAlwaysOnSameElementIndexer(IndexType indexType, EsQueueDto failing) {
this.indexType = indexType;
this.failing = failing;
}
@Override
public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) {
IndexingResult result = new IndexingResult();
items.forEach(item -> {
result.incrementRequests();
if (!item.getUuid().equals(failing.getUuid())) {
result.incrementSuccess();
db.getDbClient().esQueueDao().delete(dbSession, item);
dbSession.commit();
}
});
return result;
}
@Override
public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) {
throw new UnsupportedOperationException();
}
@Override
public Set<IndexType> getIndexTypes() {
return ImmutableSet.of(indexType);
}
}
private class PartiallyFailingIndexer implements ResilientIndexer {
private final IndexType indexType;
private final List<EsQueueDto> called = new ArrayList<>();
private final List<EsQueueDto> indexed = new ArrayList<>();
private final Iterator<Integer> successfulReturns;
PartiallyFailingIndexer(IndexType indexType, int... successfulReturns) {
this.indexType = indexType;
this.successfulReturns = IntStream.of(successfulReturns).iterator();
}
@Override
public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) {
called.addAll(items);
int success = successfulReturns.next();
IndexingResult result = new IndexingResult();
items.stream().limit(success).forEach(i -> {
db.getDbClient().esQueueDao().delete(dbSession, i);
result.incrementSuccess();
indexed.add(i);
});
rangeClosed(1, items.size()).forEach(i -> result.incrementRequests());
dbSession.commit();
return result;
}
@Override
public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) {
throw new UnsupportedOperationException();
}
@Override
public Set<IndexType> getIndexTypes() {
return ImmutableSet.of(indexType);
}
}
private void advanceInTime() {
system2.setNow(system2.now() + 100_000_000L);
}
private void assertThatLogsContain(Level loggerLevel, String message) {
assertThat(logTester.logs(loggerLevel)).filteredOn(m -> m.contains(message)).isNotEmpty();
}
private void assertThatLogsDoNotContain(Level loggerLevel, String message) {
assertThat(logTester.logs(loggerLevel)).filteredOn(m -> m.contains(message)).isEmpty();
}
private void assertThatNoLogsFromRecovery(Level loggerLevel) {
assertThat(logTester.logs(loggerLevel)).filteredOn(m -> m.contains("Elasticsearch recovery - ")).isEmpty();
}
private void assertThatQueueHasSize(int number) {
assertThat(db.countRowsOfTable(db.getSession(), "es_queue")).isEqualTo(number);
}
private RecoveryIndexer newRecoveryIndexer() {
RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient());
return newRecoveryIndexer(ruleIndexer);
}
private RecoveryIndexer newRecoveryIndexer(ResilientIndexer... indexers) {
MapSettings settings = new MapSettings()
.setProperty("sonar.search.recovery.initialDelayInMs", "0")
.setProperty("sonar.search.recovery.delayInMs", "1")
.setProperty("sonar.search.recovery.minAgeInMs", "1");
return newRecoveryIndexer(settings.asConfig(), indexers);
}
private RecoveryIndexer newRecoveryIndexer(Configuration config, ResilientIndexer... indexers) {
return new RecoveryIndexer(system2, config, db.getDbClient(), indexers);
}
private EsQueueDto insertItem(IndexType indexType, String docUuid) {
EsQueueDto item = EsQueueDto.create(indexType.format(), docUuid);
db.getDbClient().esQueueDao().insert(db.getSession(), item);
db.commit();
return item;
}
private class SuccessfulFakeIndexer implements ResilientIndexer {
private final Set<IndexType> types;
private final List<Collection<EsQueueDto>> called = new ArrayList<>();
private SuccessfulFakeIndexer(IndexType type) {
this.types = ImmutableSet.of(type);
}
@Override
public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) {
throw new UnsupportedOperationException();
}
@Override
public Set<IndexType> getIndexTypes() {
return types;
}
@Override
public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) {
called.add(items);
IndexingResult result = new IndexingResult();
items.forEach(i -> result.incrementSuccess().incrementRequests());
db.getDbClient().esQueueDao().delete(dbSession, items);
dbSession.commit();
return result;
}
}
private static class HardFailingFakeIndexer implements ResilientIndexer {
private final Set<IndexType> types;
private final List<Collection<EsQueueDto>> called = new ArrayList<>();
private HardFailingFakeIndexer(IndexType type) {
this.types = ImmutableSet.of(type);
}
@Override
public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) {
throw new UnsupportedOperationException();
}
@Override
public Set<IndexType> getIndexTypes() {
return types;
}
@Override
public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) {
called.add(items);
// MessageException is used just to reduce noise in test logs
throw MessageException.of("BOOM");
}
}
private static class SoftFailingFakeIndexer implements ResilientIndexer {
private final Set<IndexType> types;
private final List<Collection<EsQueueDto>> called = new ArrayList<>();
private SoftFailingFakeIndexer(IndexType type) {
this.types = ImmutableSet.of(type);
}
@Override
public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) {
throw new UnsupportedOperationException();
}
@Override
public Set<IndexType> getIndexTypes() {
return types;
}
@Override
public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) {
called.add(items);
IndexingResult result = new IndexingResult();
items.forEach(i -> result.incrementRequests());
return result;
}
}
}
| 17,160 | 32.64902 | 142 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/es/TestEsDbCompatibility.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.es;
import org.sonar.server.es.metadata.EsDbCompatibility;
public class TestEsDbCompatibility implements EsDbCompatibility {
private boolean hasSameDbVendor = true;
public TestEsDbCompatibility setHasSameDbVendor(boolean b) {
this.hasSameDbVendor = b;
return this;
}
@Override
public boolean hasSameDbVendor() {
return hasSameDbVendor;
}
@Override
public void markAsCompatible() {
}
}
| 1,290 | 29.023256 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.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.es.metadata;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.db.DbClient;
import org.sonar.server.es.Index;
import org.sonar.server.es.IndexType;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class EsDbCompatibilityImplTest {
private DbClient dbClient = mock(DbClient.class, Mockito.RETURNS_DEEP_STUBS);
private MetadataIndex metadataIndex = spy(new TestMetadataIndex());
private EsDbCompatibilityImpl underTest = new EsDbCompatibilityImpl(dbClient, metadataIndex);
@Test
public void hasSameDbVendor_is_true_if_values_match() {
prepareDb("mssql");
prepareEs("mssql");
assertThat(underTest.hasSameDbVendor()).isTrue();
}
@Test
public void hasSameDbVendor_is_false_if_values_dont_match() {
prepareDb("mssql");
prepareEs("postgres");
assertThat(underTest.hasSameDbVendor()).isFalse();
}
@Test
public void hasSameDbVendor_is_false_if_value_is_absent_from_es() {
prepareDb("mssql");
assertThat(underTest.hasSameDbVendor()).isFalse();
}
@Test
public void markAsCompatible_db_metadata_in_es() {
prepareDb("mssql");
underTest.markAsCompatible();
assertThat(metadataIndex.getDbVendor()).hasValue("mssql");
}
@Test
public void markAsCompatible_updates_db_metadata_in_es() {
prepareEs("mssql");
prepareDb("postgres");
underTest.markAsCompatible();
assertThat(metadataIndex.getDbVendor()).hasValue("postgres");
}
@Test
public void markAsCompatible_marks_es_as_compatible_with_db() {
prepareDb("postgres");
underTest.markAsCompatible();
assertThat(underTest.hasSameDbVendor()).isTrue();
}
@Test
public void markAsCompatible_has_no_effect_if_vendor_is_the_same() {
String vendor = randomAlphabetic(12);
prepareEs(vendor);
prepareDb(vendor);
underTest.markAsCompatible();
assertThat(underTest.hasSameDbVendor()).isTrue();
verify(metadataIndex, times(0)).setDbMetadata(anyString());
}
private void prepareDb(String dbVendor) {
when(dbClient.getDatabase().getDialect().getId()).thenReturn(dbVendor);
}
private void prepareEs(String dbVendor) {
metadataIndex.setDbMetadata(dbVendor);
// reset spy to not perturbate assertions on spy from verified code
reset(metadataIndex);
}
private static class TestMetadataIndex implements MetadataIndex {
private final Map<Index, String> hashes = new HashMap<>();
private final Map<IndexType, Boolean> initializeds = new HashMap<>();
@CheckForNull
private String dbVendor = null;
@Override
public Optional<String> getHash(Index index) {
return Optional.ofNullable(hashes.get(index));
}
@Override
public void setHash(Index index, String hash) {
hashes.put(index, hash);
}
@Override
public boolean getInitialized(IndexType indexType) {
return initializeds.getOrDefault(indexType, false);
}
@Override
public void setInitialized(IndexType indexType, boolean initialized) {
initializeds.put(indexType, initialized);
}
@Override
public Optional<String> getDbVendor() {
return Optional.ofNullable(dbVendor);
}
@Override
public void setDbMetadata(String vendor) {
this.dbVendor = vendor;
}
}
}
| 4,623 | 28.265823 | 95 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexDebtTest.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.issue.index;
import java.util.Map;
import org.junit.Test;
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.Severity;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.server.es.Facets;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.issue.IssueDocTesting;
import org.sonar.server.issue.index.IssueQuery.Builder;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.sonar.api.issue.Issue.STATUS_CLOSED;
import static org.sonar.api.issue.Issue.STATUS_OPEN;
import static org.sonar.api.utils.DateUtils.parseDateTime;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.FACET_MODE_EFFORT;
public class IssueIndexDebtTest extends IssueIndexTestCommon {
@Test
public void facets_on_projects() {
ComponentDto project = ComponentTesting.newPrivateProjectDto("ABCD");
ComponentDto project2 = ComponentTesting.newPrivateProjectDto("EFGH");
indexIssues(
IssueDocTesting.newDoc("I1", project.uuid(), ComponentTesting.newFileDto(project)).setEffort(10L),
IssueDocTesting.newDoc("I2", project.uuid(), ComponentTesting.newFileDto(project)).setEffort(10L),
IssueDocTesting.newDoc("I3", project2.uuid(), ComponentTesting.newFileDto(project2)).setEffort(10L));
Facets facets = search("projects");
assertThat(facets.getNames()).containsOnly("projects", FACET_MODE_EFFORT);
assertThat(facets.get("projects")).containsOnly(entry("ABCD", 20L), entry("EFGH", 10L));
assertThat(facets.get(FACET_MODE_EFFORT)).containsOnly(entry("total", 30L));
}
@Test
public void facets_on_components() {
ComponentDto project = ComponentTesting.newPrivateProjectDto("A");
ComponentDto file1 = ComponentTesting.newFileDto(project, null, "ABCD");
ComponentDto file2 = ComponentTesting.newFileDto(project, null, "BCDE");
ComponentDto file3 = ComponentTesting.newFileDto(project, null, "CDEF");
indexIssues(
IssueDocTesting.newDocForProject("I1", project).setEffort(10L),
IssueDocTesting.newDoc("I2", project.uuid(), file1).setEffort(10L),
IssueDocTesting.newDoc("I3", project.uuid(), file2).setEffort(10L),
IssueDocTesting.newDoc("I4", project.uuid(), file2).setEffort(10L),
IssueDocTesting.newDoc("I5", project.uuid(), file3).setEffort(10L));
Facets facets = search("files");
assertThat(facets.getNames()).containsOnly("files", FACET_MODE_EFFORT);
assertThat(facets.get("files"))
.containsOnly(entry(file1.path(), 10L), entry(file2.path(), 20L), entry(file3.path(), 10L));
assertThat(facets.get(FACET_MODE_EFFORT)).containsOnly(entry("total", 50L));
}
@Test
public void facets_on_directories() {
ComponentDto project = ComponentTesting.newPrivateProjectDto();
ComponentDto file1 = ComponentTesting.newFileDto(project).setPath("src/main/xoo/F1.xoo");
ComponentDto file2 = ComponentTesting.newFileDto(project).setPath("F2.xoo");
indexIssues(
IssueDocTesting.newDoc("I1", project.uuid(), file1).setDirectoryPath("/src/main/xoo").setEffort(10L),
IssueDocTesting.newDoc("I2", project.uuid(), file2).setDirectoryPath("/").setEffort(10L));
Facets facets = search("directories");
assertThat(facets.getNames()).containsOnly("directories", FACET_MODE_EFFORT);
assertThat(facets.get("directories")).containsOnly(entry("/src/main/xoo", 10L), entry("/", 10L));
assertThat(facets.get(FACET_MODE_EFFORT)).containsOnly(entry("total", 20L));
}
@Test
public void facets_on_severities() {
ComponentDto project = ComponentTesting.newPrivateProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
indexIssues(
IssueDocTesting.newDoc("I1", project.uuid(), file).setSeverity(Severity.INFO).setEffort(10L),
IssueDocTesting.newDoc("I2", project.uuid(), file).setSeverity(Severity.INFO).setEffort(10L),
IssueDocTesting.newDoc("I3", project.uuid(), file).setSeverity(Severity.MAJOR).setEffort(10L));
Facets facets = search("severities");
assertThat(facets.getNames()).containsOnly("severities", FACET_MODE_EFFORT);
assertThat(facets.get("severities")).containsOnly(entry("INFO", 20L), entry("MAJOR", 10L));
assertThat(facets.get(FACET_MODE_EFFORT)).containsOnly(entry("total", 30L));
}
@Test
public void facets_on_statuses() {
ComponentDto project = ComponentTesting.newPrivateProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
indexIssues(
IssueDocTesting.newDoc("I1", project.uuid(), file).setStatus(STATUS_CLOSED).setEffort(10L),
IssueDocTesting.newDoc("I2", project.uuid(), file).setStatus(STATUS_CLOSED).setEffort(10L),
IssueDocTesting.newDoc("I3", project.uuid(), file).setStatus(STATUS_OPEN).setEffort(10L));
Facets facets = search("statuses");
assertThat(facets.getNames()).containsOnly("statuses", FACET_MODE_EFFORT);
assertThat(facets.get("statuses")).containsOnly(entry("CLOSED", 20L), entry("OPEN", 10L));
assertThat(facets.get(FACET_MODE_EFFORT)).containsOnly(entry("total", 30L));
}
@Test
public void facets_on_resolutions() {
ComponentDto project = ComponentTesting.newPrivateProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
indexIssues(
IssueDocTesting.newDoc("I1", project.uuid(), file).setResolution(Issue.RESOLUTION_FALSE_POSITIVE).setEffort(10L),
IssueDocTesting.newDoc("I2", project.uuid(), file).setResolution(Issue.RESOLUTION_FALSE_POSITIVE).setEffort(10L),
IssueDocTesting.newDoc("I3", project.uuid(), file).setResolution(Issue.RESOLUTION_FIXED).setEffort(10L));
Facets facets = search("resolutions");
assertThat(facets.getNames()).containsOnly("resolutions", FACET_MODE_EFFORT);
assertThat(facets.get("resolutions")).containsOnly(entry("FALSE-POSITIVE", 20L), entry("FIXED", 10L));
assertThat(facets.get(FACET_MODE_EFFORT)).containsOnly(entry("total", 30L));
}
@Test
public void facets_on_languages() {
ComponentDto project = ComponentTesting.newPrivateProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
indexIssues(IssueDocTesting.newDoc("I1", project.uuid(), file).setLanguage("xoo").setEffort(10L));
Facets facets = search("languages");
assertThat(facets.getNames()).containsOnly("languages", FACET_MODE_EFFORT);
assertThat(facets.get("languages")).containsOnly(entry("xoo", 10L));
assertThat(facets.get(FACET_MODE_EFFORT)).containsOnly(entry("total", 10L));
}
@Test
public void facets_on_assignees() {
ComponentDto project = ComponentTesting.newPrivateProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
indexIssues(
IssueDocTesting.newDoc("I1", project.uuid(), file).setAssigneeUuid("uuid-steph").setEffort(10L),
IssueDocTesting.newDoc("I2", project.uuid(), file).setAssigneeUuid("uuid-simon").setEffort(10L),
IssueDocTesting.newDoc("I3", project.uuid(), file).setAssigneeUuid("uuid-simon").setEffort(10L),
IssueDocTesting.newDoc("I4", project.uuid(), file).setAssigneeUuid(null).setEffort(10L));
Facets facets = new Facets(underTest.search(newQueryBuilder().build(), new SearchOptions().addFacets(singletonList("assignees"))), system2.getDefaultTimeZone().toZoneId());
assertThat(facets.getNames()).containsOnly("assignees", FACET_MODE_EFFORT);
assertThat(facets.get("assignees")).containsOnly(entry("uuid-steph", 10L), entry("uuid-simon", 20L), entry("", 10L));
assertThat(facets.get(FACET_MODE_EFFORT)).containsOnly(entry("total", 40L));
}
@Test
public void facets_on_author() {
ComponentDto project = ComponentTesting.newPrivateProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
indexIssues(
IssueDocTesting.newDoc("I1", project.uuid(), file).setAuthorLogin("steph").setEffort(10L),
IssueDocTesting.newDoc("I2", project.uuid(), file).setAuthorLogin("simon").setEffort(10L),
IssueDocTesting.newDoc("I3", project.uuid(), file).setAuthorLogin("simon").setEffort(10L),
IssueDocTesting.newDoc("I4", project.uuid(), file).setAuthorLogin(null).setEffort(10L));
Facets facets = new Facets(underTest.search(newQueryBuilder().build(), new SearchOptions().addFacets(singletonList("author"))), system2.getDefaultTimeZone().toZoneId());
assertThat(facets.getNames()).containsOnly("author", FACET_MODE_EFFORT);
assertThat(facets.get("author")).containsOnly(entry("steph", 10L), entry("simon", 20L));
assertThat(facets.get(FACET_MODE_EFFORT)).containsOnly(entry("total", 40L));
}
@Test
public void facet_on_created_at() {
SearchOptions searchOptions = fixtureForCreatedAtFacet();
Builder query = newQueryBuilder().createdBefore(parseDateTime("2016-01-01T00:00:00+0100"));
Map<String, Long> createdAt = new Facets(underTest.search(query.build(), searchOptions), system2.getDefaultTimeZone().toZoneId()).get("createdAt");
assertThat(createdAt).containsOnly(
entry("2011-01-01", 10L),
entry("2012-01-01", 0L),
entry("2013-01-01", 0L),
entry("2014-01-01", 50L),
entry("2015-01-01", 10L));
}
private SearchOptions fixtureForCreatedAtFacet() {
ComponentDto project = ComponentTesting.newPrivateProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
IssueDoc issue0 = IssueDocTesting.newDoc("ISSUE0", project.uuid(), file).setEffort(10L).setFuncCreationDate(parseDateTime("2011-04-25T01:05:13+0100"));
IssueDoc issue1 = IssueDocTesting.newDoc("I1", project.uuid(), file).setEffort(10L).setFuncCreationDate(parseDateTime("2014-09-01T12:34:56+0100"));
IssueDoc issue2 = IssueDocTesting.newDoc("I2", project.uuid(), file).setEffort(10L).setFuncCreationDate(parseDateTime("2014-09-01T23:46:00+0100"));
IssueDoc issue3 = IssueDocTesting.newDoc("I3", project.uuid(), file).setEffort(10L).setFuncCreationDate(parseDateTime("2014-09-02T12:34:56+0100"));
IssueDoc issue4 = IssueDocTesting.newDoc("I4", project.uuid(), file).setEffort(10L).setFuncCreationDate(parseDateTime("2014-09-05T12:34:56+0100"));
IssueDoc issue5 = IssueDocTesting.newDoc("I5", project.uuid(), file).setEffort(10L).setFuncCreationDate(parseDateTime("2014-09-20T12:34:56+0100"));
IssueDoc issue6 = IssueDocTesting.newDoc("I6", project.uuid(), file).setEffort(10L).setFuncCreationDate(parseDateTime("2015-01-18T12:34:56+0100"));
indexIssues(issue0, issue1, issue2, issue3, issue4, issue5, issue6);
return new SearchOptions().addFacets("createdAt");
}
private Facets search(String additionalFacet) {
return new Facets(underTest.search(newQueryBuilder().build(), new SearchOptions().addFacets(singletonList(additionalFacet))), system2.getDefaultTimeZone().toZoneId());
}
private Builder newQueryBuilder() {
return IssueQuery.builder().facetMode(FACET_MODE_EFFORT);
}
}
| 11,844 | 50.5 | 176 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexFacetsTest.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.issue.index;
import java.time.ZoneId;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import org.elasticsearch.action.search.SearchResponse;
import org.junit.Test;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.rule.RulesDefinition.OwaspAsvsVersion;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.Facets;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.security.SecurityStandards.SQCategory;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.stream.IntStream.rangeClosed;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.sonar.api.issue.Issue.RESOLUTION_FALSE_POSITIVE;
import static org.sonar.api.issue.Issue.RESOLUTION_FIXED;
import static org.sonar.api.issue.Issue.RESOLUTION_REMOVED;
import static org.sonar.api.issue.Issue.RESOLUTION_WONT_FIX;
import static org.sonar.api.issue.Issue.STATUS_CLOSED;
import static org.sonar.api.issue.Issue.STATUS_CONFIRMED;
import static org.sonar.api.issue.Issue.STATUS_OPEN;
import static org.sonar.api.issue.Issue.STATUS_REOPENED;
import static org.sonar.api.issue.Issue.STATUS_RESOLVED;
import static org.sonar.api.rule.Severity.BLOCKER;
import static org.sonar.api.rule.Severity.CRITICAL;
import static org.sonar.api.rule.Severity.INFO;
import static org.sonar.api.rule.Severity.MAJOR;
import static org.sonar.api.rule.Severity.MINOR;
import static org.sonar.api.server.rule.RulesDefinition.OwaspTop10Version.Y2017;
import static org.sonar.api.server.rule.RulesDefinition.OwaspTop10Version.Y2021;
import static org.sonar.api.server.rule.RulesDefinition.PciDssVersion.V3_2;
import static org.sonar.api.server.rule.RulesDefinition.PciDssVersion.V4_0;
import static org.sonar.api.utils.DateUtils.parseDateTime;
import static org.sonar.db.component.ComponentTesting.newDirectory;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.db.rule.RuleTesting.newRule;
import static org.sonar.server.issue.IssueDocTesting.newDoc;
import static org.sonar.server.issue.IssueDocTesting.newDocForProject;
public class IssueIndexFacetsTest extends IssueIndexTestCommon {
@Test
public void facet_on_projectUuids() {
ComponentDto project = newPrivateProjectDto("ABCD");
ComponentDto project2 = newPrivateProjectDto("EFGH");
indexIssues(
newDoc("I1", project.uuid(), newFileDto(project)),
newDoc("I2", project.uuid(), newFileDto(project)),
newDoc("I3", project2.uuid(), newFileDto(project2)));
assertThatFacetHasExactly(IssueQuery.builder(), "projects", entry("ABCD", 2L), entry("EFGH", 1L));
}
@Test
public void facet_on_projectUuids_return_100_entries_plus_selected_values() {
indexIssues(rangeClosed(1, 110).mapToObj(i -> newDocForProject(newPrivateProjectDto("a" + i))).toArray(IssueDoc[]::new));
IssueDoc issue1 = newDocForProject(newPrivateProjectDto("project1"));
IssueDoc issue2 = newDocForProject(newPrivateProjectDto("project2"));
indexIssues(issue1, issue2);
assertThatFacetHasSize(IssueQuery.builder().build(), "projects", 100);
assertThatFacetHasSize(IssueQuery.builder().projectUuids(asList(issue1.projectUuid(), issue2.projectUuid())).build(), "projects", 102);
}
@Test
public void facets_on_files() {
ComponentDto project = newPrivateProjectDto("A");
ComponentDto dir = newDirectory(project, "src");
ComponentDto file1 = newFileDto(project, dir, "ABCD");
ComponentDto file2 = newFileDto(project, dir, "BCDE");
ComponentDto file3 = newFileDto(project, dir, "CDEF");
indexIssues(
newDocForProject("I1", project),
newDoc("I2", project.uuid(), file1),
newDoc("I3", project.uuid(), file2),
newDoc("I4", project.uuid(), file2),
newDoc("I5", project.uuid(), file3));
assertThatFacetHasOnly(IssueQuery.builder(), "files", entry("src/NAME_ABCD", 1L), entry("src/NAME_BCDE", 2L), entry("src/NAME_CDEF", 1L));
}
@Test
public void facet_on_files_return_100_entries_plus_selected_values() {
ComponentDto project = newPrivateProjectDto();
indexIssues(rangeClosed(1, 110).mapToObj(i -> newDoc(newFileDto(project, null, "a" + i), project.uuid())).toArray(IssueDoc[]::new));
IssueDoc issue1 = newDoc(newFileDto(project, null, "file1"), project.uuid());
IssueDoc issue2 = newDoc(newFileDto(project, null, "file2"), project.uuid());
indexIssues(issue1, issue2);
assertThatFacetHasSize(IssueQuery.builder().build(), "files", 100);
assertThatFacetHasSize(IssueQuery.builder().files(asList(issue1.filePath(), issue2.filePath())).build(), "files", 102);
}
@Test
public void facets_on_directories() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file1 = newFileDto(project).setPath("src/main/xoo/F1.xoo");
ComponentDto file2 = newFileDto(project).setPath("F2.xoo");
indexIssues(
newDoc("I1", project.uuid(), file1).setDirectoryPath("/src/main/xoo"),
newDoc("I2", project.uuid(), file2).setDirectoryPath("/"));
assertThatFacetHasOnly(IssueQuery.builder(), "directories", entry("/src/main/xoo", 1L), entry("/", 1L));
}
@Test
public void facet_on_directories_return_100_entries_plus_selected_values() {
ComponentDto project = newPrivateProjectDto();
indexIssues(rangeClosed(1, 110).mapToObj(i -> newDoc(newFileDto(project, newDirectory(project, "dir" + i)), project.uuid()).setDirectoryPath("a" + i)).toArray(IssueDoc[]::new));
IssueDoc issue1 = newDoc(newFileDto(project, newDirectory(project, "path1")), project.uuid()).setDirectoryPath("directory1");
IssueDoc issue2 = newDoc(newFileDto(project, newDirectory(project, "path2")), project.uuid()).setDirectoryPath("directory2");
indexIssues(issue1, issue2);
assertThatFacetHasSize(IssueQuery.builder().build(), "directories", 100);
assertThatFacetHasSize(IssueQuery.builder().directories(asList(issue1.directoryPath(), issue2.directoryPath())).build(), "directories", 102);
}
@Test
public void facets_on_cwe() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setCwe(asList("20", "564", "89", "943")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setCwe(asList("943")),
newDoc("I3", project.uuid(), file));
assertThatFacetHasOnly(IssueQuery.builder(), "cwe",
entry("943", 2L),
entry("20", 1L),
entry("564", 1L),
entry("89", 1L));
}
@Test
public void facets_on_pciDss32() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setPciDss32(asList("1", "2")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setPciDss32(singletonList("3")),
newDoc("I3", project.uuid(), file));
assertThatFacetHasOnly(IssueQuery.builder(), V3_2.prefix(),
entry("1", 1L),
entry("2", 1L),
entry("3", 1L));
}
@Test
public void facets_on_pciDss40() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setPciDss40(asList("1", "2")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setPciDss40(singletonList("3")),
newDoc("I3", project.uuid(), file));
assertThatFacetHasOnly(IssueQuery.builder(), V4_0.prefix(),
entry("1", 1L),
entry("2", 1L),
entry("3", 1L));
}
@Test
public void facets_on_owaspAsvs40() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspAsvs40(asList("1", "2")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspAsvs40(singletonList("3")),
newDoc("I3", project.uuid(), file));
assertThatFacetHasOnly(IssueQuery.builder(), OwaspAsvsVersion.V4_0.prefix(),
entry("1", 1L),
entry("2", 1L),
entry("3", 1L));
}
@Test
public void facets_on_owaspTop10() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspTop10(asList("a1", "a2")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspTop10(singletonList("a3")),
newDoc("I3", project.uuid(), file));
assertThatFacetHasOnly(IssueQuery.builder(), Y2017.prefix(),
entry("a1", 1L),
entry("a2", 1L),
entry("a3", 1L));
}
@Test
public void facets_on_owaspTop10_2021() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspTop10For2021(asList("a1", "a2")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspTop10For2021(singletonList("a3")),
newDoc("I3", project.uuid(), file));
assertThatFacetHasExactly(IssueQuery.builder(), Y2021.prefix(),
entry("a1", 1L),
entry("a2", 1L),
entry("a3", 1L));
}
@Test
public void facets_on_owaspTop10_2021_stay_ordered() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspTop10For2021(asList("a1", "a2")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspTop10For2021(singletonList("a3")),
newDoc("I3", project.uuid(), file));
assertThatFacetHasExactly(IssueQuery.builder().owaspTop10For2021(Collections.singletonList("a3")), Y2021.prefix(),
entry("a1", 1L),
entry("a2", 1L),
entry("a3", 1L));
}
@Test
public void facets_on_sansTop25() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setSansTop25(asList("porous-defenses", "risky-resource", "insecure-interaction")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setSansTop25(singletonList("porous-defenses")),
newDoc("I3", project.uuid(), file));
assertThatFacetHasOnly(IssueQuery.builder(), "sansTop25",
entry("insecure-interaction", 1L),
entry("porous-defenses", 2L),
entry("risky-resource", 1L));
}
@Test
public void facets_on_sonarSourceSecurity() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setSonarSourceSecurityCategory(SQCategory.BUFFER_OVERFLOW),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setSonarSourceSecurityCategory(SQCategory.DOS),
newDoc("I3", project.uuid(), file));
assertThatFacetHasOnly(IssueQuery.builder(), "sonarsourceSecurity",
entry("buffer-overflow", 1L),
entry("dos", 1L));
}
@Test
public void facets_on_severities() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setSeverity(INFO),
newDoc("I2", project.uuid(), file).setSeverity(INFO),
newDoc("I3", project.uuid(), file).setSeverity(MAJOR));
assertThatFacetHasOnly(IssueQuery.builder(), "severities", entry("INFO", 2L), entry("MAJOR", 1L));
}
@Test
public void facet_on_severities_return_5_entries_max() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I2", project.uuid(), file).setSeverity(INFO),
newDoc("I1", project.uuid(), file).setSeverity(MINOR),
newDoc("I3", project.uuid(), file).setSeverity(MAJOR),
newDoc("I4", project.uuid(), file).setSeverity(CRITICAL),
newDoc("I5", project.uuid(), file).setSeverity(BLOCKER),
newDoc("I6", project.uuid(), file).setSeverity(MAJOR));
assertThatFacetHasSize(IssueQuery.builder().build(), "severities", 5);
}
@Test
public void facets_on_statuses() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setStatus(STATUS_CLOSED),
newDoc("I2", project.uuid(), file).setStatus(STATUS_CLOSED),
newDoc("I3", project.uuid(), file).setStatus(STATUS_OPEN));
assertThatFacetHasOnly(IssueQuery.builder(), "statuses", entry("CLOSED", 2L), entry("OPEN", 1L));
}
@Test
public void facet_on_statuses_return_5_entries_max() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setStatus(STATUS_OPEN),
newDoc("I2", project.uuid(), file).setStatus(STATUS_CONFIRMED),
newDoc("I3", project.uuid(), file).setStatus(STATUS_REOPENED),
newDoc("I4", project.uuid(), file).setStatus(STATUS_RESOLVED),
newDoc("I5", project.uuid(), file).setStatus(STATUS_CLOSED),
newDoc("I6", project.uuid(), file).setStatus(STATUS_OPEN));
assertThatFacetHasSize(IssueQuery.builder().build(), "statuses", 5);
}
@Test
public void facets_on_resolutions() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setResolution(RESOLUTION_FALSE_POSITIVE),
newDoc("I2", project.uuid(), file).setResolution(RESOLUTION_FALSE_POSITIVE),
newDoc("I3", project.uuid(), file).setResolution(RESOLUTION_FIXED));
assertThatFacetHasOnly(IssueQuery.builder(), "resolutions", entry("FALSE-POSITIVE", 2L), entry("FIXED", 1L));
}
@Test
public void facets_on_resolutions_return_5_entries_max() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setResolution(RESOLUTION_FIXED),
newDoc("I2", project.uuid(), file).setResolution(RESOLUTION_FALSE_POSITIVE),
newDoc("I3", project.uuid(), file).setResolution(RESOLUTION_REMOVED),
newDoc("I4", project.uuid(), file).setResolution(RESOLUTION_WONT_FIX),
newDoc("I5", project.uuid(), file).setResolution(null));
assertThatFacetHasSize(IssueQuery.builder().build(), "resolutions", 5);
}
@Test
public void facets_on_languages() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
RuleDto ruleDefinitionDto = newRule();
db.rules().insert(ruleDefinitionDto);
indexIssues(newDoc("I1", project.uuid(), file).setRuleUuid(ruleDefinitionDto.getUuid()).setLanguage("xoo"));
assertThatFacetHasOnly(IssueQuery.builder(), "languages", entry("xoo", 1L));
}
@Test
public void facets_on_languages_return_100_entries_plus_selected_values() {
ComponentDto project = newPrivateProjectDto();
indexIssues(rangeClosed(1, 100).mapToObj(i -> newDoc(newFileDto(project), project.uuid()).setLanguage("a" + i)).toArray(IssueDoc[]::new));
IssueDoc issue1 = newDoc(newFileDto(project), project.uuid()).setLanguage("language1");
IssueDoc issue2 = newDoc(newFileDto(project), project.uuid()).setLanguage("language2");
indexIssues(issue1, issue2);
assertThatFacetHasSize(IssueQuery.builder().build(), "languages", 100);
assertThatFacetHasSize(IssueQuery.builder().languages(asList(issue1.language(), issue2.language())).build(), "languages", 102);
}
@Test
public void facets_on_assignees() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setAssigneeUuid("steph-uuid"),
newDoc("I2", project.uuid(), file).setAssigneeUuid("marcel-uuid"),
newDoc("I3", project.uuid(), file).setAssigneeUuid("marcel-uuid"),
newDoc("I4", project.uuid(), file).setAssigneeUuid(null));
assertThatFacetHasOnly(IssueQuery.builder(), "assignees", entry("steph-uuid", 1L), entry("marcel-uuid", 2L), entry("", 1L));
}
@Test
public void facets_on_assignees_return_only_100_entries_plus_selected_values() {
ComponentDto project = newPrivateProjectDto();
indexIssues(rangeClosed(1, 110).mapToObj(i -> newDoc(newFileDto(project), project.uuid()).setAssigneeUuid("a" + i)).toArray(IssueDoc[]::new));
IssueDoc issue1 = newDoc(newFileDto(project), project.uuid()).setAssigneeUuid("user1");
IssueDoc issue2 = newDoc(newFileDto(project), project.uuid()).setAssigneeUuid("user2");
indexIssues(issue1, issue2);
assertThatFacetHasSize(IssueQuery.builder().build(), "assignees", 100);
assertThatFacetHasSize(IssueQuery.builder().assigneeUuids(asList(issue1.assigneeUuid(), issue2.assigneeUuid())).build(), "assignees", 102);
}
@Test
public void facets_on_assignees_supports_dashes() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setAssigneeUuid("j-b-uuid"),
newDoc("I2", project.uuid(), file).setAssigneeUuid("marcel-uuid"),
newDoc("I3", project.uuid(), file).setAssigneeUuid("marcel-uuid"),
newDoc("I4", project.uuid(), file).setAssigneeUuid(null));
assertThatFacetHasOnly(IssueQuery.builder().assigneeUuids(singletonList("j-b")),
"assignees", entry("j-b-uuid", 1L), entry("marcel-uuid", 2L), entry("", 1L));
}
@Test
public void facets_on_author() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setAuthorLogin("steph"),
newDoc("I2", project.uuid(), file).setAuthorLogin("marcel"),
newDoc("I3", project.uuid(), file).setAuthorLogin("marcel"),
newDoc("I4", project.uuid(), file).setAuthorLogin(null));
assertThatFacetHasOnly(IssueQuery.builder(), "author", entry("steph", 1L), entry("marcel", 2L));
}
@Test
public void facets_on_authors_return_100_entries_plus_selected_values() {
ComponentDto project = newPrivateProjectDto();
indexIssues(rangeClosed(1, 110).mapToObj(i -> newDoc(newFileDto(project), project.uuid()).setAuthorLogin("a" + i)).toArray(IssueDoc[]::new));
IssueDoc issue1 = newDoc(newFileDto(project), project.uuid()).setAuthorLogin("user1");
IssueDoc issue2 = newDoc(newFileDto(project), project.uuid()).setAuthorLogin("user2");
indexIssues(issue1, issue2);
assertThatFacetHasSize(IssueQuery.builder().build(), "author", 100);
assertThatFacetHasSize(IssueQuery.builder().authors(asList(issue1.authorLogin(), issue2.authorLogin())).build(), "author", 102);
}
@Test
public void facet_on_created_at_with_less_than_20_days_use_system_timezone_by_default() {
SearchOptions options = fixtureForCreatedAtFacet();
IssueQuery query = IssueQuery.builder()
.createdAfter(parseDateTime("2014-09-01T00:00:00+0100"))
.createdBefore(parseDateTime("2014-09-08T00:00:00+0100"))
.build();
SearchResponse result = underTest.search(query, options);
Map<String, Long> buckets = new Facets(result, system2.getDefaultTimeZone().toZoneId()).get("createdAt");
assertThat(buckets).containsOnly(
entry("2014-08-31", 0L),
entry("2014-09-01", 2L),
entry("2014-09-02", 1L),
entry("2014-09-03", 0L),
entry("2014-09-04", 0L),
entry("2014-09-05", 1L),
entry("2014-09-06", 0L),
entry("2014-09-07", 0L));
}
@Test
public void facet_on_created_at_with_less_than_20_days_use_user_timezone_if_provided() {
// Use timezones very far from each other in order to see some issues moving to a different calendar day
final ZoneId plus14 = ZoneId.of("Pacific/Kiritimati");
final ZoneId minus11 = ZoneId.of("Pacific/Pago_Pago");
SearchOptions options = fixtureForCreatedAtFacet();
final Date startDate = parseDateTime("2014-09-01T00:00:00+0000");
final Date endDate = parseDateTime("2014-09-08T00:00:00+0000");
IssueQuery queryPlus14 = IssueQuery.builder()
.createdAfter(startDate)
.createdBefore(endDate)
.timeZone(plus14)
.build();
SearchResponse resultPlus14 = underTest.search(queryPlus14, options);
Map<String, Long> bucketsPlus14 = new Facets(resultPlus14, plus14).get("createdAt");
assertThat(bucketsPlus14).containsOnly(
entry("2014-09-01", 0L),
entry("2014-09-02", 2L),
entry("2014-09-03", 1L),
entry("2014-09-04", 0L),
entry("2014-09-05", 0L),
entry("2014-09-06", 1L),
entry("2014-09-07", 0L),
entry("2014-09-08", 0L));
IssueQuery queryMinus11 = IssueQuery.builder()
.createdAfter(startDate)
.createdBefore(endDate)
.timeZone(minus11)
.build();
SearchResponse resultMinus11 = underTest.search(queryMinus11, options);
Map<String, Long> bucketsMinus11 = new Facets(resultMinus11, minus11).get("createdAt");
assertThat(bucketsMinus11).containsOnly(
entry("2014-08-31", 1L),
entry("2014-09-01", 1L),
entry("2014-09-02", 1L),
entry("2014-09-03", 0L),
entry("2014-09-04", 0L),
entry("2014-09-05", 1L),
entry("2014-09-06", 0L),
entry("2014-09-07", 0L));
}
@Test
public void facet_on_created_at_with_less_than_20_weeks() {
SearchOptions options = fixtureForCreatedAtFacet();
SearchResponse result = underTest.search(IssueQuery.builder()
.createdAfter(parseDateTime("2014-09-01T00:00:00+0100"))
.createdBefore(parseDateTime("2014-09-21T00:00:00+0100")).build(),
options);
Map<String, Long> createdAt = new Facets(result, system2.getDefaultTimeZone().toZoneId()).get("createdAt");
assertThat(createdAt).containsOnly(
entry("2014-08-25", 0L),
entry("2014-09-01", 4L),
entry("2014-09-08", 0L),
entry("2014-09-15", 1L));
}
@Test
public void facet_on_created_at_with_less_than_20_months() {
SearchOptions options = fixtureForCreatedAtFacet();
SearchResponse result = underTest.search(IssueQuery.builder()
.createdAfter(parseDateTime("2014-09-01T00:00:00+0100"))
.createdBefore(parseDateTime("2015-01-19T00:00:00+0100")).build(),
options);
Map<String, Long> createdAt = new Facets(result, system2.getDefaultTimeZone().toZoneId()).get("createdAt");
assertThat(createdAt).containsOnly(
entry("2014-08-01", 0L),
entry("2014-09-01", 5L),
entry("2014-10-01", 0L),
entry("2014-11-01", 0L),
entry("2014-12-01", 0L),
entry("2015-01-01", 1L));
}
@Test
public void facet_on_created_at_with_more_than_20_months() {
SearchOptions options = fixtureForCreatedAtFacet();
SearchResponse result = underTest.search(IssueQuery.builder()
.createdAfter(parseDateTime("2011-01-01T00:00:00+0100"))
.createdBefore(parseDateTime("2016-01-01T00:00:00+0100")).build(),
options);
Map<String, Long> createdAt = new Facets(result, system2.getDefaultTimeZone().toZoneId()).get("createdAt");
assertThat(createdAt).containsOnly(
entry("2010-01-01", 0L),
entry("2011-01-01", 1L),
entry("2012-01-01", 0L),
entry("2013-01-01", 0L),
entry("2014-01-01", 5L),
entry("2015-01-01", 1L));
}
@Test
public void facet_on_created_at_with_one_day() {
SearchOptions options = fixtureForCreatedAtFacet();
SearchResponse result = underTest.search(IssueQuery.builder()
.createdAfter(parseDateTime("2014-09-01T00:00:00-0100"))
.createdBefore(parseDateTime("2014-09-02T00:00:00-0100")).build(),
options);
Map<String, Long> createdAt = new Facets(result, system2.getDefaultTimeZone().toZoneId()).get("createdAt");
assertThat(createdAt).containsOnly(
entry("2014-09-01", 2L));
}
@Test
public void facet_on_created_at_with_bounds_outside_of_data() {
SearchOptions options = fixtureForCreatedAtFacet();
SearchResponse result = underTest.search(IssueQuery.builder()
.createdAfter(parseDateTime("2009-01-01T00:00:00+0100"))
.createdBefore(parseDateTime("2016-01-01T00:00:00+0100"))
.build(), options);
Map<String, Long> createdAt = new Facets(result, system2.getDefaultTimeZone().toZoneId()).get("createdAt");
assertThat(createdAt).containsOnly(
entry("2008-01-01", 0L),
entry("2009-01-01", 0L),
entry("2010-01-01", 0L),
entry("2011-01-01", 1L),
entry("2012-01-01", 0L),
entry("2013-01-01", 0L),
entry("2014-01-01", 5L),
entry("2015-01-01", 1L));
}
@Test
public void facet_on_created_at_without_start_bound() {
SearchOptions searchOptions = fixtureForCreatedAtFacet();
SearchResponse result = underTest.search(IssueQuery.builder()
.createdBefore(parseDateTime("2016-01-01T00:00:00+0100")).build(),
searchOptions);
Map<String, Long> createdAt = new Facets(result, system2.getDefaultTimeZone().toZoneId()).get("createdAt");
assertThat(createdAt).containsOnly(
entry("2011-01-01", 1L),
entry("2012-01-01", 0L),
entry("2013-01-01", 0L),
entry("2014-01-01", 5L),
entry("2015-01-01", 1L));
}
@Test
public void facet_on_created_at_without_issues() {
SearchOptions searchOptions = new SearchOptions().addFacets("createdAt");
SearchResponse result = underTest.search(IssueQuery.builder().build(), searchOptions);
Map<String, Long> createdAt = new Facets(result, system2.getDefaultTimeZone().toZoneId()).get("createdAt");
assertThat(createdAt).isNull();
}
@Test
public void search_shouldReturnCodeVariantsFacet() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setCodeVariants(asList("variant1", "variant2")),
newDoc("I2", project.uuid(), file).setCodeVariants(singletonList("variant2")),
newDoc("I3", project.uuid(), file).setCodeVariants(singletonList("variant3")),
newDoc("I4", project.uuid(), file));
assertThatFacetHasOnly(IssueQuery.builder(), "codeVariants",
entry("variant1", 1L),
entry("variant2", 2L),
entry("variant3", 1L));
}
private SearchOptions fixtureForCreatedAtFacet() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
IssueDoc issue0 = newDoc("ISSUE0", project.uuid(), file).setFuncCreationDate(parseDateTime("2011-04-25T00:05:13+0000"));
IssueDoc issue1 = newDoc("I1", project.uuid(), file).setFuncCreationDate(parseDateTime("2014-09-01T10:34:56+0000"));
IssueDoc issue2 = newDoc("I2", project.uuid(), file).setFuncCreationDate(parseDateTime("2014-09-01T22:46:00+0000"));
IssueDoc issue3 = newDoc("I3", project.uuid(), file).setFuncCreationDate(parseDateTime("2014-09-02T11:34:56+0000"));
IssueDoc issue4 = newDoc("I4", project.uuid(), file).setFuncCreationDate(parseDateTime("2014-09-05T11:34:56+0000"));
IssueDoc issue5 = newDoc("I5", project.uuid(), file).setFuncCreationDate(parseDateTime("2014-09-20T11:34:56+0000"));
IssueDoc issue6 = newDoc("I6", project.uuid(), file).setFuncCreationDate(parseDateTime("2015-01-18T11:34:56+0000"));
indexIssues(issue0, issue1, issue2, issue3, issue4, issue5, issue6);
return new SearchOptions().addFacets("createdAt");
}
@SafeVarargs
private final void assertThatFacetHasExactly(IssueQuery.Builder query, String facet, Map.Entry<String, Long>... expectedEntries) {
SearchResponse result = underTest.search(query.build(), new SearchOptions().addFacets(singletonList(facet)));
Facets facets = new Facets(result, system2.getDefaultTimeZone().toZoneId());
assertThat(facets.getNames()).containsOnly(facet, "effort");
assertThat(facets.get(facet)).containsExactly(expectedEntries);
}
@SafeVarargs
private final void assertThatFacetHasOnly(IssueQuery.Builder query, String facet, Map.Entry<String, Long>... expectedEntries) {
SearchResponse result = underTest.search(query.build(), new SearchOptions().addFacets(singletonList(facet)));
Facets facets = new Facets(result, system2.getDefaultTimeZone().toZoneId());
assertThat(facets.getNames()).containsOnly(facet, "effort");
assertThat(facets.get(facet)).containsOnly(expectedEntries);
}
private void assertThatFacetHasSize(IssueQuery issueQuery, String facet, int expectedSize) {
SearchResponse result = underTest.search(issueQuery, new SearchOptions().addFacets(singletonList(facet)));
Facets facets = new Facets(result, system2.getDefaultTimeZone().toZoneId());
assertThat(facets.get(facet)).hasSize(expectedSize);
}
}
| 29,985 | 41.654339 | 181 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexFiltersTest.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.issue.index;
import com.google.common.collect.ImmutableMap;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.assertj.core.api.Fail;
import org.junit.Test;
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.security.SecurityStandards.SQCategory;
import org.sonar.server.view.index.ViewDoc;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.resources.Qualifiers.APP;
import static org.sonar.api.utils.DateUtils.addDays;
import static org.sonar.api.utils.DateUtils.parseDate;
import static org.sonar.api.utils.DateUtils.parseDateTime;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.db.rule.RuleTesting.newRule;
import static org.sonar.server.issue.IssueDocTesting.newDoc;
import static org.sonar.server.issue.IssueDocTesting.newDocForProject;
public class IssueIndexFiltersTest extends IssueIndexTestCommon {
@Test
public void filter_by_keys() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDoc("I1", project.uuid(), newFileDto(project)),
newDoc("I2", project.uuid(), newFileDto(project)));
assertThatSearchReturnsOnly(IssueQuery.builder().issueKeys(asList("I1", "I2")), "I1", "I2");
assertThatSearchReturnsOnly(IssueQuery.builder().issueKeys(singletonList("I1")), "I1");
assertThatSearchReturnsEmpty(IssueQuery.builder().issueKeys(asList("I3", "I4")));
}
@Test
public void filter_by_projects() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("I1", project),
newDoc("I2", project.uuid(), newFileDto(project)));
assertThatSearchReturnsOnly(IssueQuery.builder().projectUuids(singletonList(project.uuid())), "I1", "I2");
assertThatSearchReturnsEmpty(IssueQuery.builder().projectUuids(singletonList("unknown")));
}
@Test
public void filter_by_components_on_contextualized_search() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file1 = newFileDto(project);
String view = "ABCD";
indexView(view, singletonList(project.uuid()));
indexIssues(
newDocForProject("I1", project),
newDoc("I2", project.uuid(), file1));
assertThatSearchReturnsOnly(IssueQuery.builder().files(asList(file1.path())), "I2");
assertThatSearchReturnsOnly(IssueQuery.builder().files(singletonList(file1.path())), "I2");
assertThatSearchReturnsOnly(IssueQuery.builder().projectUuids(singletonList(project.uuid())), "I1", "I2");
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(view)), "I1", "I2");
assertThatSearchReturnsEmpty(IssueQuery.builder().projectUuids(singletonList("unknown")));
}
@Test
public void filter_by_components_on_non_contextualized_search() {
ComponentDto project = newPrivateProjectDto("project");
ComponentDto file1 = newFileDto(project, null, "file1");
String view = "ABCD";
indexView(view, singletonList(project.uuid()));
indexIssues(
newDocForProject("I1", project),
newDoc("I2", project.uuid(), file1));
assertThatSearchReturnsEmpty(IssueQuery.builder().projectUuids(singletonList("unknown")));
assertThatSearchReturnsOnly(IssueQuery.builder().projectUuids(singletonList(project.uuid())), "I1", "I2");
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(view)), "I1", "I2");
assertThatSearchReturnsOnly(IssueQuery.builder().files(singletonList(file1.path())), "I2");
assertThatSearchReturnsOnly(IssueQuery.builder().files(asList(file1.path())), "I2");
}
@Test
public void filter_by_directories() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file1 = newFileDto(project).setPath("src/main/xoo/F1.xoo");
ComponentDto file2 = newFileDto(project).setPath("F2.xoo");
indexIssues(
newDoc("I1", project.uuid(), file1).setDirectoryPath("/src/main/xoo"),
newDoc("I2", project.uuid(), file2).setDirectoryPath("/"));
assertThatSearchReturnsOnly(IssueQuery.builder().directories(singletonList("/src/main/xoo")), "I1");
assertThatSearchReturnsOnly(IssueQuery.builder().directories(singletonList("/")), "I2");
assertThatSearchReturnsEmpty(IssueQuery.builder().directories(singletonList("unknown")));
}
@Test
public void filter_by_portfolios() {
ComponentDto portfolio1 = db.components().insertPrivateApplication().getMainBranchComponent();
ComponentDto portfolio2 = db.components().insertPrivateApplication().getMainBranchComponent();
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project1));
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
IssueDoc issueOnProject1 = newDocForProject(project1);
IssueDoc issueOnFile = newDoc(file, project1.uuid());
IssueDoc issueOnProject2 = newDocForProject(project2);
indexIssues(issueOnProject1, issueOnFile, issueOnProject2);
indexView(portfolio1.uuid(), singletonList(project1.uuid()));
indexView(portfolio2.uuid(), singletonList(project2.uuid()));
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(portfolio1.uuid())), issueOnProject1.key(), issueOnFile.key());
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(portfolio2.uuid())), issueOnProject2.key());
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(asList(portfolio1.uuid(), portfolio2.uuid())), issueOnProject1.key(), issueOnFile.key(), issueOnProject2.key());
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(portfolio1.uuid())).projectUuids(singletonList(project1.uuid())), issueOnProject1.key(),
issueOnFile.key());
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(portfolio1.uuid())).files(singletonList(file.path())), issueOnFile.key());
assertThatSearchReturnsEmpty(IssueQuery.builder().viewUuids(singletonList("unknown")));
}
@Test
public void filter_by_portfolios_not_having_projects() {
ComponentDto project1 = newPrivateProjectDto();
ComponentDto file1 = newFileDto(project1);
indexIssues(newDoc("I2", project1.uuid(), file1));
String view1 = "ABCD";
indexView(view1, emptyList());
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(view1)));
}
@Test
public void do_not_return_issues_from_project_branch_when_filtering_by_portfolios() {
ComponentDto portfolio = db.components().insertPrivateApplication().getMainBranchComponent();
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto projectBranch = db.components().insertProjectBranch(project);
ComponentDto fileOnProjectBranch = db.components().insertComponent(newFileDto(projectBranch));
indexView(portfolio.uuid(), singletonList(project.uuid()));
IssueDoc issueOnProject = newDocForProject(project);
IssueDoc issueOnProjectBranch = newDoc(projectBranch, project.uuid());
IssueDoc issueOnFileOnProjectBranch = newDoc(fileOnProjectBranch, projectBranch.uuid());
indexIssues(issueOnProject, issueOnFileOnProjectBranch, issueOnProjectBranch);
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(portfolio.uuid())), issueOnProject.key());
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(portfolio.uuid())).projectUuids(singletonList(project.uuid())),
issueOnProject.key());
assertThatSearchReturnsEmpty(IssueQuery.builder().viewUuids(singletonList(portfolio.uuid())).projectUuids(singletonList(projectBranch.uuid())));
}
@Test
public void filter_one_issue_by_project_and_branch() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project);
ComponentDto anotherbBranch = db.components().insertProjectBranch(project);
IssueDoc issueOnProject = newDocForProject(project);
IssueDoc issueOnBranch = newDoc(branch, project.uuid());
IssueDoc issueOnAnotherBranch = newDoc(anotherbBranch, project.uuid());
indexIssues(issueOnProject, issueOnBranch, issueOnAnotherBranch);
assertThatSearchReturnsOnly(IssueQuery.builder().branchUuid(branch.uuid()).mainBranch(false), issueOnBranch.key());
assertThatSearchReturnsOnly(IssueQuery.builder().componentUuids(singletonList(branch.uuid())).branchUuid(branch.uuid()).mainBranch(false), issueOnBranch.key());
assertThatSearchReturnsOnly(IssueQuery.builder().projectUuids(singletonList(project.uuid())).branchUuid(branch.uuid()).mainBranch(false), issueOnBranch.key());
assertThatSearchReturnsOnly(
IssueQuery.builder().componentUuids(singletonList(branch.uuid())).projectUuids(singletonList(project.uuid())).branchUuid(branch.uuid()).mainBranch(false),
issueOnBranch.key());
assertThatSearchReturnsOnly(IssueQuery.builder().projectUuids(singletonList(project.uuid())).mainBranch(null), issueOnProject.key(), issueOnBranch.key(),
issueOnAnotherBranch.key());
assertThatSearchReturnsEmpty(IssueQuery.builder().branchUuid("unknown"));
}
@Test
public void issues_from_branch_component_children() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto projectFile = db.components().insertComponent(newFileDto(project));
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
ComponentDto branchFile = db.components().insertComponent(newFileDto(branch, project.uuid()));
indexIssues(
newDocForProject("I1", project),
newDoc("I2", project.uuid(), projectFile),
newDoc("I3", project.uuid(), branch),
newDoc("I4", project.uuid(), branchFile));
assertThatSearchReturnsOnly(IssueQuery.builder().branchUuid(branch.uuid()).mainBranch(false), "I3", "I4");
assertThatSearchReturnsOnly(IssueQuery.builder().files(singletonList(branchFile.path())).branchUuid(branch.uuid()).mainBranch(false), "I4");
assertThatSearchReturnsEmpty(IssueQuery.builder().files(singletonList(branchFile.uuid())).mainBranch(false).branchUuid("unknown"));
}
@Test
public void issues_from_main_branch() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project);
IssueDoc issueOnProject = newDocForProject(project);
IssueDoc issueOnBranch = newDoc(branch, project.uuid());
indexIssues(issueOnProject, issueOnBranch);
assertThatSearchReturnsOnly(IssueQuery.builder().branchUuid(project.uuid()).mainBranch(true), issueOnProject.key());
assertThatSearchReturnsOnly(IssueQuery.builder().componentUuids(singletonList(project.uuid())).branchUuid(project.uuid()).mainBranch(true), issueOnProject.key());
assertThatSearchReturnsOnly(IssueQuery.builder().projectUuids(singletonList(project.uuid())).branchUuid(project.uuid()).mainBranch(true), issueOnProject.key());
assertThatSearchReturnsOnly(
IssueQuery.builder().componentUuids(singletonList(project.uuid())).projectUuids(singletonList(project.uuid())).branchUuid(project.uuid()).mainBranch(true),
issueOnProject.key());
}
@Test
public void branch_issues_are_ignored_when_no_branch_param() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
IssueDoc projectIssue = newDocForProject(project);
IssueDoc branchIssue = newDoc(branch, project.uuid());
indexIssues(projectIssue, branchIssue);
assertThatSearchReturnsOnly(IssueQuery.builder(), projectIssue.key());
}
@Test
public void filter_by_main_application() {
ComponentDto application1 = db.components().insertPrivateApplication().getMainBranchComponent();
ComponentDto application2 = db.components().insertPrivateApplication().getMainBranchComponent();
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project1));
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
indexView(application1.uuid(), singletonList(project1.uuid()));
indexView(application2.uuid(), singletonList(project2.uuid()));
IssueDoc issueOnProject1 = newDocForProject(project1);
IssueDoc issueOnFile = newDoc(file, project1.uuid());
IssueDoc issueOnProject2 = newDocForProject(project2);
indexIssues(issueOnProject1, issueOnFile, issueOnProject2);
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(application1.uuid())), issueOnProject1.key(), issueOnFile.key());
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(application2.uuid())), issueOnProject2.key());
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(asList(application1.uuid(), application2.uuid())), issueOnProject1.key(), issueOnFile.key(), issueOnProject2.key());
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(application1.uuid())).projectUuids(singletonList(project1.uuid())), issueOnProject1.key(),
issueOnFile.key());
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(application1.uuid())).files(singletonList(file.path())), issueOnFile.key());
assertThatSearchReturnsEmpty(IssueQuery.builder().viewUuids(singletonList("unknown")));
}
@Test
public void filter_by_application_branch() {
ComponentDto application = db.components().insertPublicProject(c -> c.setQualifier(APP)).getMainBranchComponent();
ComponentDto branch1 = db.components().insertProjectBranch(application);
ComponentDto branch2 = db.components().insertProjectBranch(application);
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project1));
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
indexView(branch1.uuid(), singletonList(project1.uuid()));
indexView(branch2.uuid(), singletonList(project2.uuid()));
IssueDoc issueOnProject1 = newDocForProject(project1);
IssueDoc issueOnFile = newDoc(file, project1.uuid());
IssueDoc issueOnProject2 = newDocForProject(project2);
indexIssues(issueOnProject1, issueOnFile, issueOnProject2);
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(branch1.uuid())).branchUuid(branch1.uuid()).mainBranch(false),
issueOnProject1.key(), issueOnFile.key());
assertThatSearchReturnsOnly(
IssueQuery.builder().viewUuids(singletonList(branch1.uuid())).projectUuids(singletonList(project1.uuid())).branchUuid(branch1.uuid()).mainBranch(false),
issueOnProject1.key(), issueOnFile.key());
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(branch1.uuid())).files(singletonList(file.path())).branchUuid(branch1.uuid()).mainBranch(false),
issueOnFile.key());
assertThatSearchReturnsEmpty(IssueQuery.builder().branchUuid("unknown"));
}
@Test
public void filter_by_application_branch_having_project_branches() {
ComponentDto application = db.components().insertPublicProject(c -> c.setQualifier(APP).setKey("app")).getMainBranchComponent();
ComponentDto applicationBranch1 = db.components().insertProjectBranch(application, a -> a.setKey("app-branch1"));
ComponentDto applicationBranch2 = db.components().insertProjectBranch(application, a -> a.setKey("app-branch2"));
ComponentDto project1 = db.components().insertPrivateProject(p -> p.setKey("prj1")).getMainBranchComponent();
ComponentDto project1Branch1 = db.components().insertProjectBranch(project1);
ComponentDto fileOnProject1Branch1 = db.components().insertComponent(newFileDto(project1Branch1));
ComponentDto project1Branch2 = db.components().insertProjectBranch(project1);
ComponentDto project2 = db.components().insertPrivateProject(p -> p.setKey("prj2")).getMainBranchComponent();
indexView(applicationBranch1.uuid(), asList(project1Branch1.uuid(), project2.uuid()));
indexView(applicationBranch2.uuid(), singletonList(project1Branch2.uuid()));
IssueDoc issueOnProject1 = newDocForProject(project1);
IssueDoc issueOnProject1Branch1 = newDoc(project1Branch1, project1.uuid());
IssueDoc issueOnFileOnProject1Branch1 = newDoc(fileOnProject1Branch1, project1.uuid());
IssueDoc issueOnProject1Branch2 = newDoc(project1Branch2, project1.uuid());
IssueDoc issueOnProject2 = newDocForProject(project2);
indexIssues(issueOnProject1, issueOnProject1Branch1, issueOnFileOnProject1Branch1, issueOnProject1Branch2, issueOnProject2);
assertThatSearchReturnsOnly(IssueQuery.builder().viewUuids(singletonList(applicationBranch1.uuid())).branchUuid(applicationBranch1.uuid()).mainBranch(false),
issueOnProject1Branch1.key(), issueOnFileOnProject1Branch1.key(), issueOnProject2.key());
assertThatSearchReturnsOnly(
IssueQuery.builder().viewUuids(singletonList(applicationBranch1.uuid())).projectUuids(singletonList(project1.uuid())).branchUuid(applicationBranch1.uuid()).mainBranch(false),
issueOnProject1Branch1.key(), issueOnFileOnProject1Branch1.key());
assertThatSearchReturnsOnly(
IssueQuery.builder().viewUuids(singletonList(applicationBranch1.uuid())).files(singletonList(fileOnProject1Branch1.path())).branchUuid(applicationBranch1.uuid())
.mainBranch(false),
issueOnFileOnProject1Branch1.key());
assertThatSearchReturnsEmpty(
IssueQuery.builder().viewUuids(singletonList(applicationBranch1.uuid())).projectUuids(singletonList("unknown")).branchUuid(applicationBranch1.uuid()).mainBranch(false));
}
@Test
public void filter_by_created_after_by_projects() {
Date now = new Date();
ComponentDto project1 = newPrivateProjectDto();
IssueDoc project1Issue1 = newDocForProject(project1).setFuncCreationDate(addDays(now, -10));
IssueDoc project1Issue2 = newDocForProject(project1).setFuncCreationDate(addDays(now, -20));
ComponentDto project2 = newPrivateProjectDto();
IssueDoc project2Issue1 = newDocForProject(project2).setFuncCreationDate(addDays(now, -15));
IssueDoc project2Issue2 = newDocForProject(project2).setFuncCreationDate(addDays(now, -30));
indexIssues(project1Issue1, project1Issue2, project2Issue1, project2Issue2);
// Search for issues of project 1 having less than 15 days
assertThatSearchReturnsOnly(IssueQuery.builder()
.createdAfterByProjectUuids(ImmutableMap.of(project1.uuid(), new IssueQuery.PeriodStart(addDays(now, -15), true))),
project1Issue1.key());
// Search for issues of project 1 having less than 14 days and project 2 having less then 25 days
assertThatSearchReturnsOnly(IssueQuery.builder()
.createdAfterByProjectUuids(ImmutableMap.of(
project1.uuid(), new IssueQuery.PeriodStart(addDays(now, -14), true),
project2.uuid(), new IssueQuery.PeriodStart(addDays(now, -25), true))),
project1Issue1.key(), project2Issue1.key());
// Search for issues of project 1 having less than 30 days
assertThatSearchReturnsOnly(IssueQuery.builder()
.createdAfterByProjectUuids(ImmutableMap.of(
project1.uuid(), new IssueQuery.PeriodStart(addDays(now, -30), true))),
project1Issue1.key(), project1Issue2.key());
// Search for issues of project 1 and project 2 having less than 5 days
assertThatSearchReturnsOnly(IssueQuery.builder()
.createdAfterByProjectUuids(ImmutableMap.of(
project1.uuid(), new IssueQuery.PeriodStart(addDays(now, -5), true),
project2.uuid(), new IssueQuery.PeriodStart(addDays(now, -5), true))));
}
@Test
public void filter_by_created_after_by_project_branches() {
Date now = new Date();
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
IssueDoc project1Issue1 = newDocForProject(project1).setFuncCreationDate(addDays(now, -10));
IssueDoc project1Issue2 = newDocForProject(project1).setFuncCreationDate(addDays(now, -20));
ComponentDto project1Branch1 = db.components().insertProjectBranch(project1);
IssueDoc project1Branch1Issue1 = newDoc(project1Branch1, project1.uuid()).setFuncCreationDate(addDays(now, -10));
IssueDoc project1Branch1Issue2 = newDoc(project1Branch1, project1.uuid()).setFuncCreationDate(addDays(now, -20));
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
IssueDoc project2Issue1 = newDocForProject(project2).setFuncCreationDate(addDays(now, -15));
IssueDoc project2Issue2 = newDocForProject(project2).setFuncCreationDate(addDays(now, -30));
ComponentDto project2Branch1 = db.components().insertProjectBranch(project2);
IssueDoc project2Branch1Issue1 = newDoc(project2Branch1, project2.uuid()).setFuncCreationDate(addDays(now, -15));
IssueDoc project2Branch1Issue2 = newDoc(project2Branch1, project2.uuid()).setFuncCreationDate(addDays(now, -30));
indexIssues(project1Issue1, project1Issue2, project2Issue1, project2Issue2,
project1Branch1Issue1, project1Branch1Issue2, project2Branch1Issue1, project2Branch1Issue2);
// Search for issues of project 1 branch 1 having less than 15 days
assertThatSearchReturnsOnly(IssueQuery.builder()
.mainBranch(false)
.createdAfterByProjectUuids(ImmutableMap.of(project1Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -15), true))),
project1Branch1Issue1.key());
// Search for issues of project 1 branch 1 having less than 14 days and project 2 branch 1 having less then 25 days
assertThatSearchReturnsOnly(IssueQuery.builder()
.mainBranch(false)
.createdAfterByProjectUuids(ImmutableMap.of(
project1Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -14), true),
project2Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -25), true))),
project1Branch1Issue1.key(), project2Branch1Issue1.key());
// Search for issues of project 1 branch 1 having less than 30 days
assertThatSearchReturnsOnly(IssueQuery.builder()
.mainBranch(false)
.createdAfterByProjectUuids(ImmutableMap.of(
project1Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -30), true))),
project1Branch1Issue1.key(), project1Branch1Issue2.key());
// Search for issues of project 1 branch 1 and project 2 branch 2 having less than 5 days
assertThatSearchReturnsOnly(IssueQuery.builder()
.mainBranch(false)
.createdAfterByProjectUuids(ImmutableMap.of(
project1Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -5), true),
project2Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -5), true))));
}
@Test
public void filter_by_new_code_reference_by_projects() {
ComponentDto project1 = newPrivateProjectDto();
IssueDoc project1Issue1 = newDocForProject(project1).setIsNewCodeReference(true);
IssueDoc project1Issue2 = newDocForProject(project1).setIsNewCodeReference(false);
ComponentDto project2 = newPrivateProjectDto();
IssueDoc project2Issue1 = newDocForProject(project2).setIsNewCodeReference(false);
IssueDoc project2Issue2 = newDocForProject(project2).setIsNewCodeReference(true);
indexIssues(project1Issue1, project1Issue2, project2Issue1, project2Issue2);
// Search for issues of project 1 and project 2 that are new code on a branch using reference for new code
assertThatSearchReturnsOnly(IssueQuery.builder()
.newCodeOnReferenceByProjectUuids(Set.of(project1.uuid(), project2.uuid())),
project1Issue1.key(), project2Issue2.key());
}
@Test
public void filter_by_new_code_reference_branches() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
IssueDoc project1Issue1 = newDocForProject(project1).setIsNewCodeReference(true);
IssueDoc project1Issue2 = newDocForProject(project1).setIsNewCodeReference(false);
ComponentDto project1Branch1 = db.components().insertProjectBranch(project1);
IssueDoc project1Branch1Issue1 = newDoc(project1Branch1, project1.uuid()).setIsNewCodeReference(false);
IssueDoc project1Branch1Issue2 = newDoc(project1Branch1, project1.uuid()).setIsNewCodeReference(true);
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
IssueDoc project2Issue1 = newDocForProject(project2).setIsNewCodeReference(true);
IssueDoc project2Issue2 = newDocForProject(project2).setIsNewCodeReference(false);
ComponentDto project2Branch1 = db.components().insertProjectBranch(project2);
IssueDoc project2Branch1Issue1 = newDoc(project2Branch1, project2.uuid()).setIsNewCodeReference(false);
IssueDoc project2Branch1Issue2 = newDoc(project2Branch1, project2.uuid()).setIsNewCodeReference(true);
indexIssues(project1Issue1, project1Issue2, project2Issue1, project2Issue2,
project1Branch1Issue1, project1Branch1Issue2, project2Branch1Issue1, project2Branch1Issue2);
// Search for issues of project 1 branch 1 and project 2 branch 1 that are new code on a branch using reference for new code
assertThatSearchReturnsOnly(IssueQuery.builder()
.mainBranch(false)
.newCodeOnReferenceByProjectUuids(Set.of(project1Branch1.uuid(), project2Branch1.uuid())),
project1Branch1Issue2.key(), project2Branch1Issue2.key());
}
@Test
public void filter_by_severities() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setSeverity(Severity.INFO),
newDoc("I2", project.uuid(), file).setSeverity(Severity.MAJOR));
assertThatSearchReturnsOnly(IssueQuery.builder().severities(asList(Severity.INFO, Severity.MAJOR)), "I1", "I2");
assertThatSearchReturnsOnly(IssueQuery.builder().severities(singletonList(Severity.INFO)), "I1");
assertThatSearchReturnsEmpty(IssueQuery.builder().severities(singletonList(Severity.BLOCKER)));
}
@Test
public void filter_by_statuses() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setStatus(Issue.STATUS_CLOSED),
newDoc("I2", project.uuid(), file).setStatus(Issue.STATUS_OPEN));
assertThatSearchReturnsOnly(IssueQuery.builder().statuses(asList(Issue.STATUS_CLOSED, Issue.STATUS_OPEN)), "I1", "I2");
assertThatSearchReturnsOnly(IssueQuery.builder().statuses(singletonList(Issue.STATUS_CLOSED)), "I1");
assertThatSearchReturnsEmpty(IssueQuery.builder().statuses(singletonList(Issue.STATUS_CONFIRMED)));
}
@Test
public void filter_by_resolutions() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setResolution(Issue.RESOLUTION_FALSE_POSITIVE),
newDoc("I2", project.uuid(), file).setResolution(Issue.RESOLUTION_FIXED));
assertThatSearchReturnsOnly(IssueQuery.builder().resolutions(asList(Issue.RESOLUTION_FALSE_POSITIVE, Issue.RESOLUTION_FIXED)), "I1", "I2");
assertThatSearchReturnsOnly(IssueQuery.builder().resolutions(singletonList(Issue.RESOLUTION_FALSE_POSITIVE)), "I1");
assertThatSearchReturnsEmpty(IssueQuery.builder().resolutions(singletonList(Issue.RESOLUTION_REMOVED)));
}
@Test
public void filter_by_resolved() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setStatus(Issue.STATUS_CLOSED).setResolution(Issue.RESOLUTION_FIXED),
newDoc("I2", project.uuid(), file).setStatus(Issue.STATUS_OPEN).setResolution(null),
newDoc("I3", project.uuid(), file).setStatus(Issue.STATUS_OPEN).setResolution(null));
assertThatSearchReturnsOnly(IssueQuery.builder().resolved(true), "I1");
assertThatSearchReturnsOnly(IssueQuery.builder().resolved(false), "I2", "I3");
assertThatSearchReturnsOnly(IssueQuery.builder().resolved(null), "I1", "I2", "I3");
}
@Test
public void filter_by_rules() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
RuleDto ruleDefinitionDto = newRule();
db.rules().insert(ruleDefinitionDto);
indexIssues(newDoc("I1", project.uuid(), file).setRuleUuid(ruleDefinitionDto.getUuid()));
assertThatSearchReturnsOnly(IssueQuery.builder().ruleUuids(singletonList(ruleDefinitionDto.getUuid())), "I1");
assertThatSearchReturnsEmpty(IssueQuery.builder().ruleUuids(singletonList("uuid-abc")));
}
@Test
public void filter_by_languages() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
RuleDto ruleDefinitionDto = newRule();
db.rules().insert(ruleDefinitionDto);
indexIssues(newDoc("I1", project.uuid(), file).setRuleUuid(ruleDefinitionDto.getUuid()).setLanguage("xoo"));
assertThatSearchReturnsOnly(IssueQuery.builder().languages(singletonList("xoo")), "I1");
assertThatSearchReturnsEmpty(IssueQuery.builder().languages(singletonList("unknown")));
}
@Test
public void filter_by_assignees() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setAssigneeUuid("steph-uuid"),
newDoc("I2", project.uuid(), file).setAssigneeUuid("marcel-uuid"),
newDoc("I3", project.uuid(), file).setAssigneeUuid(null));
assertThatSearchReturnsOnly(IssueQuery.builder().assigneeUuids(singletonList("steph-uuid")), "I1");
assertThatSearchReturnsOnly(IssueQuery.builder().assigneeUuids(asList("steph-uuid", "marcel-uuid")), "I1", "I2");
assertThatSearchReturnsEmpty(IssueQuery.builder().assigneeUuids(singletonList("unknown")));
}
@Test
public void filter_by_assigned() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setAssigneeUuid("steph-uuid"),
newDoc("I2", project.uuid(), file).setAssigneeUuid(null),
newDoc("I3", project.uuid(), file).setAssigneeUuid(null));
assertThatSearchReturnsOnly(IssueQuery.builder().assigned(true), "I1");
assertThatSearchReturnsOnly(IssueQuery.builder().assigned(false), "I2", "I3");
assertThatSearchReturnsOnly(IssueQuery.builder().assigned(null), "I1", "I2", "I3");
}
@Test
public void filter_by_authors() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setAuthorLogin("steph"),
newDoc("I2", project.uuid(), file).setAuthorLogin("marcel"),
newDoc("I3", project.uuid(), file).setAssigneeUuid(null));
assertThatSearchReturnsOnly(IssueQuery.builder().authors(singletonList("steph")), "I1");
assertThatSearchReturnsOnly(IssueQuery.builder().authors(asList("steph", "marcel")), "I1", "I2");
assertThatSearchReturnsEmpty(IssueQuery.builder().authors(singletonList("unknown")));
}
@Test
public void filter_by_created_after() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setFuncCreationDate(parseDate("2014-09-20")),
newDoc("I2", project.uuid(), file).setFuncCreationDate(parseDate("2014-09-23")));
assertThatSearchReturnsOnly(IssueQuery.builder().createdAfter(parseDate("2014-09-19")), "I1", "I2");
// Lower bound is included
assertThatSearchReturnsOnly(IssueQuery.builder().createdAfter(parseDate("2014-09-20")), "I1", "I2");
assertThatSearchReturnsOnly(IssueQuery.builder().createdAfter(parseDate("2014-09-21")), "I2");
assertThatSearchReturnsEmpty(IssueQuery.builder().createdAfter(parseDate("2014-09-25")));
}
@Test
public void filter_by_created_before() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setFuncCreationDate(parseDate("2014-09-20")),
newDoc("I2", project.uuid(), file).setFuncCreationDate(parseDate("2014-09-23")));
assertThatSearchReturnsEmpty(IssueQuery.builder().createdBefore(parseDate("2014-09-19")));
// Upper bound is excluded
assertThatSearchReturnsEmpty(IssueQuery.builder().createdBefore(parseDate("2014-09-20")));
assertThatSearchReturnsOnly(IssueQuery.builder().createdBefore(parseDate("2014-09-21")), "I1");
assertThatSearchReturnsOnly(IssueQuery.builder().createdBefore(parseDate("2014-09-25")), "I1", "I2");
}
@Test
public void filter_by_created_after_and_before() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setFuncCreationDate(parseDate("2014-09-20")),
newDoc("I2", project.uuid(), file).setFuncCreationDate(parseDate("2014-09-23")));
// 19 < createdAt < 25
assertThatSearchReturnsOnly(IssueQuery.builder().createdAfter(parseDate("2014-09-19")).createdBefore(parseDate("2014-09-25")),
"I1", "I2");
// 20 < createdAt < 25: excludes first issue
assertThatSearchReturnsOnly(IssueQuery.builder()
.createdAfter(parseDate("2014-09-20")).createdBefore(parseDate("2014-09-25")), "I1", "I2");
// 21 < createdAt < 25
assertThatSearchReturnsOnly(IssueQuery.builder()
.createdAfter(parseDate("2014-09-21")).createdBefore(parseDate("2014-09-25")), "I2");
// 21 < createdAt < 24
assertThatSearchReturnsOnly(IssueQuery.builder()
.createdAfter(parseDate("2014-09-21")).createdBefore(parseDate("2014-09-24")), "I2");
// 21 < createdAt < 23: excludes second issue
assertThatSearchReturnsEmpty(IssueQuery.builder()
.createdAfter(parseDate("2014-09-21")).createdBefore(parseDate("2014-09-23")));
// 19 < createdAt < 21: only first issue
assertThatSearchReturnsOnly(IssueQuery.builder()
.createdAfter(parseDate("2014-09-19")).createdBefore(parseDate("2014-09-21")), "I1");
// 20 < createdAt < 20: exception
assertThatThrownBy(() -> underTest.search(IssueQuery.builder()
.createdAfter(parseDate("2014-09-20")).createdBefore(parseDate("2014-09-20"))
.build(), new SearchOptions()))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void filter_by_created_after_and_before_take_into_account_timezone() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setFuncCreationDate(parseDateTime("2014-09-20T00:00:00+0100")),
newDoc("I2", project.uuid(), file).setFuncCreationDate(parseDateTime("2014-09-23T00:00:00+0100")));
assertThatSearchReturnsOnly(IssueQuery.builder().createdAfter(parseDateTime("2014-09-19T23:00:00+0000")).createdBefore(parseDateTime("2014-09-22T23:00:01+0000")),
"I1", "I2");
assertThatSearchReturnsEmpty(IssueQuery.builder().createdAfter(parseDateTime("2014-09-19T23:00:01+0000")).createdBefore(parseDateTime("2014-09-22T23:00:00+0000")));
}
@Test
public void filter_by_created_before_must_be_lower_than_after() {
try {
underTest.search(IssueQuery.builder().createdAfter(parseDate("2014-09-20")).createdBefore(parseDate("2014-09-19")).build(),
new SearchOptions());
Fail.failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (IllegalArgumentException exception) {
assertThat(exception.getMessage()).isEqualTo("Start bound cannot be larger or equal to end bound");
}
}
@Test
public void fail_if_created_before_equals_created_after() {
assertThatThrownBy(() -> underTest.search(IssueQuery.builder().createdAfter(parseDate("2014-09-20"))
.createdBefore(parseDate("2014-09-20")).build(), new SearchOptions()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Start bound cannot be larger or equal to end bound");
}
@Test
public void filter_by_created_after_must_not_be_in_future() {
try {
underTest.search(IssueQuery.builder().createdAfter(new Date(Long.MAX_VALUE)).build(), new SearchOptions());
Fail.failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (IllegalArgumentException exception) {
assertThat(exception.getMessage()).isEqualTo("Start bound cannot be in the future");
}
}
@Test
public void filter_by_created_at() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(newDoc("I1", project.uuid(), file).setFuncCreationDate(parseDate("2014-09-20")));
assertThatSearchReturnsOnly(IssueQuery.builder().createdAt(parseDate("2014-09-20")), "I1");
assertThatSearchReturnsEmpty(IssueQuery.builder().createdAt(parseDate("2014-09-21")));
}
@Test
public void filter_by_new_code_reference() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(newDoc("I1", project.uuid(), file).setIsNewCodeReference(true),
newDoc("I2", project.uuid(), file).setIsNewCodeReference(false));
assertThatSearchReturnsOnly(IssueQuery.builder().newCodeOnReference(true), "I1");
}
@Test
public void filter_by_cwe() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setCwe(asList("20", "564", "89", "943")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setCwe(singletonList("943")),
newDoc("I3", project.uuid(), file));
assertThatSearchReturnsOnly(IssueQuery.builder().cwe(singletonList("20")), "I1");
}
@Test
public void filter_by_owaspAsvs40_category() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspAsvs40(asList("1.1.1", "1.2.2", "2.2.2")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspAsvs40(asList("1.1.1", "1.2.2")),
newDoc("I3", project.uuid(), file));
assertThatSearchReturnsOnly(IssueQuery.builder().owaspAsvs40(singletonList("1")), "I1", "I2");
assertThatSearchReturnsOnly(IssueQuery.builder().owaspAsvs40(singletonList("2")), "I1");
assertThatSearchReturnsOnly(IssueQuery.builder().owaspAsvs40(singletonList("3")));
}
@Test
public void filter_by_owaspAsvs40_specific_requirement() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspAsvs40(asList("1.1.1", "1.2.2", "2.2.2")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspAsvs40(asList("1.1.1", "1.2.2")),
newDoc("I3", project.uuid(), file));
assertThatSearchReturnsOnly(IssueQuery.builder().owaspAsvs40(singletonList("1.1.1")), "I1", "I2");
assertThatSearchReturnsOnly(IssueQuery.builder().owaspAsvs40(singletonList("2.2.2")), "I1");
assertThatSearchReturnsOnly(IssueQuery.builder().owaspAsvs40(singletonList("3.3.3")));
}
@Test
public void filter_by_owaspAsvs40_level() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspAsvs40(asList("2.1.1", "1.1.1", "1.11.3")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspAsvs40(asList("1.1.1", "1.11.3")),
newDoc("I3", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspAsvs40(singletonList("1.11.3")),
newDoc("IError1", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspAsvs40(asList("5.5.1", "7.2.2", "10.2.6")),
newDoc("IError2", project.uuid(), file));
assertThatSearchReturnsOnly(
IssueQuery.builder().owaspAsvs40(singletonList("1.1.1")).owaspAsvsLevel(1));
assertThatSearchReturnsOnly(
IssueQuery.builder().owaspAsvs40(singletonList("1.1.1")).owaspAsvsLevel(2),
"I1", "I2");
assertThatSearchReturnsOnly(
IssueQuery.builder().owaspAsvs40(singletonList("1.1.1")).owaspAsvsLevel(3),
"I1", "I2");
}
@Test
public void filter_by_owaspTop10() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setOwaspTop10(asList("a1", "a2")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setCwe(singletonList("a3")),
newDoc("I3", project.uuid(), file));
assertThatSearchReturnsOnly(IssueQuery.builder().owaspTop10(singletonList("a1")), "I1");
}
@Test
public void filter_by_sansTop25() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setSansTop25(asList("porous-defenses", "risky-resource", "insecure-interaction")),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setSansTop25(singletonList("porous-defenses")),
newDoc("I3", project.uuid(), file));
assertThatSearchReturnsOnly(IssueQuery.builder().sansTop25(singletonList("risky-resource")), "I1");
}
@Test
public void filter_by_sonarSecurity() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(RuleType.VULNERABILITY).setSonarSourceSecurityCategory(SQCategory.BUFFER_OVERFLOW),
newDoc("I2", project.uuid(), file).setType(RuleType.VULNERABILITY).setSonarSourceSecurityCategory(SQCategory.DOS),
newDoc("I3", project.uuid(), file));
assertThatSearchReturnsOnly(IssueQuery.builder().sonarsourceSecurity(singletonList("buffer-overflow")), "I1");
}
@Test
public void search_whenFilteringByCodeVariants_shouldReturnRelevantIssues() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setCodeVariants(asList("variant1", "variant2")),
newDoc("I2", project.uuid(), file).setCodeVariants(singletonList("variant2")),
newDoc("I3", project.uuid(), file).setCodeVariants(singletonList("variant3")),
newDoc("I4", project.uuid(), file));
assertThatSearchReturnsOnly(IssueQuery.builder().codeVariants(singletonList("variant2")), "I1", "I2");
}
private void indexView(String viewUuid, List<String> projectBranchUuids) {
viewIndexer.index(new ViewDoc().setUuid(viewUuid).setProjectBranchUuids(projectBranchUuids));
}
}
| 44,492 | 50.796275 | 180 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexProjectStatisticsTest.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.issue.index;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.sonar.api.issue.Issue;
import org.sonar.db.component.ComponentDto;
import static java.util.Arrays.asList;
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.sonar.db.component.ComponentTesting.newBranchComponent;
import static org.sonar.db.component.ComponentTesting.newBranchDto;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.server.issue.IssueDocTesting.newDoc;
import static org.sonar.server.issue.IssueDocTesting.newDocForProject;
public class IssueIndexProjectStatisticsTest extends IssueIndexTestCommon {
@Test
public void searchProjectStatistics_returns_empty_list_if_no_input() {
List<ProjectStatistics> result = underTest.searchProjectStatistics(emptyList(), emptyList(), "unknownUser");
assertThat(result).isEmpty();
}
@Test
public void searchProjectStatistics_returns_empty_list_if_the_input_does_not_match_anything() {
List<ProjectStatistics> result = underTest.searchProjectStatistics(singletonList("unknownProjectUuid"), singletonList(1_111_234_567_890L), "unknownUser");
assertThat(result).isEmpty();
}
@Test
public void searchProjectStatistics_returns_something() {
ComponentDto project = newPrivateProjectDto();
String userUuid = randomAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)));
List<ProjectStatistics> result = underTest.searchProjectStatistics(singletonList(project.uuid()), singletonList(from), userUuid);
assertThat(result).extracting(ProjectStatistics::getProjectUuid).containsExactly(project.uuid());
}
@Test
public void searchProjectStatistics_does_not_return_results_if_assignee_does_not_match() {
ComponentDto project = newPrivateProjectDto();
String user1Uuid = randomAlphanumeric(40);
String user2Uuid = randomAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(newDocForProject("issue1", project).setAssigneeUuid(user1Uuid).setFuncCreationDate(new Date(from + 1L)));
List<ProjectStatistics> result = underTest.searchProjectStatistics(singletonList(project.uuid()), singletonList(from), user2Uuid);
assertThat(result).isEmpty();
}
@Test
public void searchProjectStatistics_returns_results_if_assignee_matches() {
ComponentDto project = newPrivateProjectDto();
String user1Uuid = randomAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(newDocForProject("issue1", project).setAssigneeUuid(user1Uuid).setFuncCreationDate(new Date(from + 1L)));
List<ProjectStatistics> result = underTest.searchProjectStatistics(singletonList(project.uuid()), singletonList(from), user1Uuid);
assertThat(result).extracting(ProjectStatistics::getProjectUuid).containsExactly(project.uuid());
}
@Test
public void searchProjectStatistics_returns_results_if_functional_date_is_strictly_after_from_date() {
ComponentDto project = newPrivateProjectDto();
String userUuid = randomAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)));
List<ProjectStatistics> result = underTest.searchProjectStatistics(singletonList(project.uuid()), singletonList(from), userUuid);
assertThat(result).extracting(ProjectStatistics::getProjectUuid).containsExactly(project.uuid());
}
@Test
public void searchProjectStatistics_does_not_return_results_if_functional_date_is_same_as_from_date() {
ComponentDto project = newPrivateProjectDto();
String userUuid = randomAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from)));
List<ProjectStatistics> result = underTest.searchProjectStatistics(singletonList(project.uuid()), singletonList(from), userUuid);
assertThat(result).extracting(ProjectStatistics::getProjectUuid).containsExactly(project.uuid());
}
@Test
public void searchProjectStatistics_does_not_return_resolved_issues() {
ComponentDto project = newPrivateProjectDto();
String userUuid = randomAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(
newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)).setResolution(Issue.RESOLUTION_FALSE_POSITIVE),
newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)).setResolution(Issue.RESOLUTION_FIXED),
newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)).setResolution(Issue.RESOLUTION_REMOVED),
newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)).setResolution(Issue.RESOLUTION_WONT_FIX));
List<ProjectStatistics> result = underTest.searchProjectStatistics(singletonList(project.uuid()), singletonList(from), userUuid);
assertThat(result).isEmpty();
}
@Test
public void searchProjectStatistics_does_not_return_results_if_functional_date_is_before_from_date() {
ComponentDto project = newPrivateProjectDto();
String userUuid = randomAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from - 1000L)));
List<ProjectStatistics> result = underTest.searchProjectStatistics(singletonList(project.uuid()), singletonList(from), userUuid);
assertThat(result).isEmpty();
}
@Test
public void searchProjectStatistics_returns_issue_count() {
ComponentDto project = newPrivateProjectDto();
String userUuid = randomAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(
newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)),
newDocForProject("issue2", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)),
newDocForProject("issue3", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)));
List<ProjectStatistics> result = underTest.searchProjectStatistics(singletonList(project.uuid()), singletonList(from), userUuid);
assertThat(result).extracting(ProjectStatistics::getIssueCount).containsExactly(3L);
}
@Test
public void searchProjectStatistics_returns_issue_count_for_multiple_projects() {
ComponentDto project1 = newPrivateProjectDto();
ComponentDto project2 = newPrivateProjectDto();
ComponentDto project3 = newPrivateProjectDto();
String userUuid = randomAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(
newDocForProject("issue1", project1).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)),
newDocForProject("issue2", project1).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)),
newDocForProject("issue3", project1).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)),
newDocForProject("issue4", project3).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)),
newDocForProject("issue5", project3).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)));
List<ProjectStatistics> result = underTest.searchProjectStatistics(
asList(project1.uuid(), project2.uuid(), project3.uuid()),
asList(from, from, from),
userUuid);
assertThat(result)
.extracting(ProjectStatistics::getProjectUuid, ProjectStatistics::getIssueCount)
.containsExactlyInAnyOrder(
tuple(project1.uuid(), 3L),
tuple(project3.uuid(), 2L));
}
@Test
public void searchProjectStatistics_returns_max_date_for_multiple_projects() {
ComponentDto project1 = newPrivateProjectDto();
ComponentDto project2 = newPrivateProjectDto();
ComponentDto project3 = newPrivateProjectDto();
String userUuid = randomAlphanumeric(40);
long from = 1_111_234_567_000L;
indexIssues(
newDocForProject("issue1", project1).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1_000L)),
newDocForProject("issue2", project1).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 2_000L)),
newDocForProject("issue3", project1).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 3_000L)),
newDocForProject("issue4", project3).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 4_000L)),
newDocForProject("issue5", project3).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 5_000L)));
List<ProjectStatistics> result = underTest.searchProjectStatistics(
asList(project1.uuid(), project2.uuid(), project3.uuid()),
asList(from, from, from),
userUuid);
assertThat(result)
.extracting(ProjectStatistics::getProjectUuid, ProjectStatistics::getLastIssueDate)
.containsExactlyInAnyOrder(
tuple(project1.uuid(), from + 3_000L),
tuple(project3.uuid(), from + 5_000L));
}
@Test
public void searchProjectStatistics_return_branch_issues() {
ComponentDto project = newPrivateProjectDto();
ComponentDto branch = newBranchComponent(project, newBranchDto(project).setKey("branch"));
String userUuid = randomAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(
newDoc("issue1", project.uuid(), branch).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)),
newDoc("issue2", project.uuid(), branch).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 2L)),
newDocForProject("issue3", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)));
List<ProjectStatistics> result = underTest.searchProjectStatistics(singletonList(project.uuid()), singletonList(from), userUuid);
assertThat(result)
.extracting(ProjectStatistics::getIssueCount, ProjectStatistics::getProjectUuid, ProjectStatistics::getLastIssueDate)
.containsExactly(
tuple(2L, branch.uuid(), from + 2L),
tuple(1L, project.uuid(), from + 1L));
}
}
| 11,338 | 47.875 | 158 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSecurityCategoriesTest.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.issue.index;
import java.util.List;
import org.junit.Test;
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.db.component.ComponentDto;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.server.issue.IssueDocTesting.newDocForProject;
public class IssueIndexSecurityCategoriesTest extends IssueIndexTestCommon {
@Test
public void searchSinglePciDss32Category() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("openvul1", project).setPciDss32(asList("1.2.0", "3.4.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN)
.setSeverity(Severity.MAJOR),
newDocForProject("openvul2", project).setPciDss32(asList("3.3.2", "1.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR)
);
assertThatSearchReturnsOnly(queryPciDss32("1"), "openvul1", "openvul2");
assertThatSearchReturnsOnly(queryPciDss32("1.2.0"), "openvul1");
assertThatSearchReturnsEmpty(queryPciDss32("1.2"));
}
@Test
public void searchMultiplePciDss32Categories() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("openvul1", project).setPciDss32(asList("1.2.0", "3.4.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN)
.setSeverity(Severity.MAJOR),
newDocForProject("openvul2", project).setPciDss32(asList("3.3.2", "2.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("openvul3", project).setPciDss32(asList("4.1", "5.4")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR)
);
assertThatSearchReturnsOnly(queryPciDss32("1", "4"), "openvul1", "openvul3");
assertThatSearchReturnsOnly(queryPciDss32("1.2.0", "5.4"), "openvul1", "openvul3");
assertThatSearchReturnsEmpty(queryPciDss32("6", "7", "8", "9", "10", "11", "12"));
}
@Test
public void searchSinglePciDss40Category() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("openvul1", project).setPciDss40(asList("1.2.0", "3.4.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN)
.setSeverity(Severity.MAJOR),
newDocForProject("openvul2", project).setPciDss40(asList("3.3.2", "1.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR)
);
assertThatSearchReturnsOnly(queryPciDss40("1"), "openvul1", "openvul2");
assertThatSearchReturnsOnly(queryPciDss40("1.2.0"), "openvul1");
assertThatSearchReturnsEmpty(queryPciDss40("1.2"));
}
@Test
public void searchMultiplePciDss40Categories() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("openvul1", project).setPciDss40(asList("1.2.0", "3.4.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN)
.setSeverity(Severity.MAJOR),
newDocForProject("openvul2", project).setPciDss40(asList("3.3.2", "2.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("openvul3", project).setPciDss40(asList("4.1", "5.4")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR)
);
assertThatSearchReturnsOnly(queryPciDss40("1", "4"), "openvul1", "openvul3");
assertThatSearchReturnsOnly(queryPciDss40("1.2.0", "5.4"), "openvul1", "openvul3");
assertThatSearchReturnsEmpty(queryPciDss40("6", "7", "8", "9", "10", "11", "12"));
}
@Test
public void searchMixedPciDssCategories() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("openvul1", project).setPciDss40(asList("1.2.0", "3.4.5")).setPciDss32(List.of("2.1")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN)
.setSeverity(Severity.MAJOR),
newDocForProject("openvul2", project).setPciDss40(asList("3.3.2", "2.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("openvul3", project).setPciDss32(asList("4.1", "5.4")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR)
);
assertThatSearchReturnsOnly(queryPciDss40("1", "4"), "openvul1");
assertThatSearchReturnsOnly(queryPciDss40("1.2.0", "5.4"), "openvul1");
assertThatSearchReturnsEmpty(queryPciDss40("6", "7", "8", "9", "10", "11", "12"));
assertThatSearchReturnsOnly(queryPciDss32("3", "2.1"), "openvul1");
assertThatSearchReturnsOnly(queryPciDss32("1", "2"), "openvul1");
assertThatSearchReturnsOnly(queryPciDss32("4", "3"), "openvul3");
assertThatSearchReturnsEmpty(queryPciDss32("1", "3", "6", "7", "8", "9", "10", "11", "12"));
}
private IssueQuery.Builder queryPciDss32(String... values) {
return IssueQuery.builder()
.pciDss32(stream(values).collect(toList()))
.types(List.of("CODE_SMELL", "BUG", "VULNERABILITY"));
}
private IssueQuery.Builder queryPciDss40(String... values) {
return IssueQuery.builder()
.pciDss40(stream(values).collect(toList()))
.types(List.of("CODE_SMELL", "BUG", "VULNERABILITY"));
}
}
| 6,397 | 44.375887 | 170 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSecurityHotspotsTest.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.issue.index;
import java.util.Map;
import org.elasticsearch.action.search.SearchResponse;
import org.junit.Test;
import org.sonar.api.rule.Severity;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.es.Facets;
import org.sonar.server.es.SearchOptions;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.sonar.api.rule.Severity.INFO;
import static org.sonar.api.rule.Severity.MAJOR;
import static org.sonar.api.rules.RuleType.BUG;
import static org.sonar.api.rules.RuleType.CODE_SMELL;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.api.rules.RuleType.VULNERABILITY;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.server.issue.IssueDocTesting.newDoc;
public class IssueIndexSecurityHotspotsTest extends IssueIndexTestCommon {
@Test
public void filter_by_security_hotspots_type() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setType(BUG),
newDoc("I2", project.uuid(), file).setType(CODE_SMELL),
newDoc("I3", project.uuid(), file).setType(VULNERABILITY),
newDoc("I4", project.uuid(), file).setType(VULNERABILITY),
newDoc("I5", project.uuid(), file).setType(SECURITY_HOTSPOT),
newDoc("I6", project.uuid(), file).setType(SECURITY_HOTSPOT));
assertThatSearchReturnsOnly(IssueQuery.builder().types(singletonList(SECURITY_HOTSPOT.name())), "I5", "I6");
assertThatSearchReturnsOnly(IssueQuery.builder().types(asList(SECURITY_HOTSPOT.name(), VULNERABILITY.name())), "I3", "I4", "I5", "I6");
assertThatSearchReturnsOnly(IssueQuery.builder(), "I1", "I2", "I3", "I4", "I5", "I6");
}
@Test
public void filter_by_severities_ignore_hotspots() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setSeverity(Severity.INFO).setType(BUG),
newDoc("I2", project.uuid(), file).setSeverity(Severity.MAJOR).setType(CODE_SMELL),
newDoc("I3", project.uuid(), file).setSeverity(Severity.MAJOR).setType(VULNERABILITY),
newDoc("I4", project.uuid(), file).setSeverity(Severity.CRITICAL).setType(VULNERABILITY),
// This entry should be ignored
newDoc("I5", project.uuid(), file).setSeverity(Severity.MAJOR).setType(SECURITY_HOTSPOT));
assertThatSearchReturnsOnly(IssueQuery.builder().severities(asList(Severity.INFO, Severity.MAJOR)), "I1", "I2", "I3");
assertThatSearchReturnsOnly(IssueQuery.builder().severities(asList(Severity.INFO, Severity.MAJOR)).types(singletonList(VULNERABILITY.name())), "I3");
assertThatSearchReturnsEmpty(IssueQuery.builder().severities(singletonList(Severity.MAJOR)).types(singletonList(SECURITY_HOTSPOT.name())));
}
@Test
public void facet_on_severities_ignore_hotspots() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setSeverity(INFO).setType(BUG),
newDoc("I2", project.uuid(), file).setSeverity(INFO).setType(CODE_SMELL),
newDoc("I3", project.uuid(), file).setSeverity(INFO).setType(VULNERABILITY),
newDoc("I4", project.uuid(), file).setSeverity(MAJOR).setType(VULNERABILITY),
// These 2 entries should be ignored
newDoc("I5", project.uuid(), file).setSeverity(INFO).setType(SECURITY_HOTSPOT),
newDoc("I6", project.uuid(), file).setSeverity(MAJOR).setType(SECURITY_HOTSPOT));
assertThatFacetHasOnly(IssueQuery.builder(), "severities", entry("INFO", 3L), entry("MAJOR", 1L));
assertThatFacetHasOnly(IssueQuery.builder().types(singletonList(VULNERABILITY.name())), "severities", entry("INFO", 1L), entry("MAJOR", 1L));
assertThatFacetHasOnly(IssueQuery.builder().types(asList(BUG.name(), CODE_SMELL.name(), VULNERABILITY.name())), "severities", entry("INFO", 3L), entry("MAJOR", 1L));
assertThatFacetHasOnly(IssueQuery.builder().types(singletonList(SECURITY_HOTSPOT.name())), "severities");
}
@SafeVarargs
private final void assertThatFacetHasOnly(IssueQuery.Builder query, String facet, Map.Entry<String, Long>... expectedEntries) {
SearchResponse result = underTest.search(query.build(), new SearchOptions().addFacets(singletonList(facet)));
Facets facets = new Facets(result, system2.getDefaultTimeZone().toZoneId());
assertThat(facets.getNames()).containsOnly(facet, "effort");
assertThat(facets.get(facet)).containsOnly(expectedEntries);
}
}
| 5,672 | 50.108108 | 169 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSecurityReportsTest.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.issue.index;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.view.index.ViewDoc;
import static java.lang.Integer.parseInt;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.sonar.api.server.rule.RulesDefinition.OwaspAsvsVersion;
import static org.sonar.api.server.rule.RulesDefinition.PciDssVersion;
import static org.sonar.api.server.rule.RulesDefinition.OwaspTop10Version.Y2017;
import static org.sonar.api.server.rule.RulesDefinition.OwaspTop10Version.Y2021;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.server.issue.IssueDocTesting.newDocForProject;
import static org.sonar.server.security.SecurityStandards.UNKNOWN_STANDARD;
public class IssueIndexSecurityReportsTest extends IssueIndexTestCommon {
@Test
public void getOwaspTop10Report_dont_count_vulnerabilities_from_other_projects() {
ComponentDto project = newPrivateProjectDto();
ComponentDto another = newPrivateProjectDto();
IssueDoc openVulDoc = newDocForProject("openvul1", project).setOwaspTop10(singletonList("a1")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN).setSeverity(Severity.MAJOR);
openVulDoc.setOwaspTop10For2021(singletonList("a2")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN).setSeverity(Severity.MAJOR);
IssueDoc otherProjectDoc = newDocForProject("anotherProject", another).setOwaspTop10(singletonList("a1")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN).setSeverity(Severity.CRITICAL);
otherProjectDoc.setOwaspTop10For2021(singletonList("a2")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN).setSeverity(Severity.CRITICAL);
indexIssues(openVulDoc, otherProjectDoc);
List<SecurityStandardCategoryStatistics> owaspTop10Report = underTest.getOwaspTop10Report(project.uuid(), false, false, Y2017);
assertThat(owaspTop10Report)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating)
.contains(
tuple("a1", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */));
List<SecurityStandardCategoryStatistics> owaspTop10For2021Report = underTest.getOwaspTop10Report(project.uuid(), false, false, Y2021);
assertThat(owaspTop10For2021Report)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating)
.contains(
tuple("a2", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */));
}
@Test
public void getOwaspTop10Report_dont_count_closed_vulnerabilities() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("openvul1", project).setOwaspTop10(List.of("a1")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN).setSeverity(Severity.MAJOR),
newDocForProject("openvul12021", project).setOwaspTop10For2021(List.of("a2")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN).setSeverity(Severity.MAJOR),
newDocForProject("notopenvul", project).setOwaspTop10(List.of("a1")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_CLOSED).setResolution(Issue.RESOLUTION_FIXED)
.setSeverity(Severity.BLOCKER),
newDocForProject("notopenvul2021", project).setOwaspTop10For2021(List.of("a2")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_CLOSED).setResolution(Issue.RESOLUTION_FIXED)
.setSeverity(Severity.BLOCKER));
List<SecurityStandardCategoryStatistics> owaspTop10Report = underTest.getOwaspTop10Report(project.uuid(), false, false, Y2017);
assertThat(owaspTop10Report)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating)
.contains(
tuple("a1", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */));
List<SecurityStandardCategoryStatistics> owaspTop10For2021Report = underTest.getOwaspTop10Report(project.uuid(), false, false, Y2021);
assertThat(owaspTop10For2021Report)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating)
.contains(
tuple("a2", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */));
}
@Test
public void getOwaspTop10Report_dont_count_old_vulnerabilities() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
// Previous vulnerabilities in projects that are not reanalyzed will have no owasp nor cwe attributes (not even 'unknown')
newDocForProject("openvulNotReindexed", project).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN).setSeverity(Severity.MAJOR));
List<SecurityStandardCategoryStatistics> owaspTop10Report = underTest.getOwaspTop10Report(project.uuid(), false, false, Y2017);
assertThat(owaspTop10Report)
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating)
.containsOnly(
tuple(0L, OptionalInt.empty()));
List<SecurityStandardCategoryStatistics> owaspTop10For2021Report = underTest.getOwaspTop10Report(project.uuid(), false, false, Y2021);
assertThat(owaspTop10For2021Report)
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating)
.containsOnly(
tuple(0L, OptionalInt.empty()));
}
@Test
public void getOwaspTop10Report_dont_count_hotspots_from_other_projects() {
ComponentDto project = newPrivateProjectDto();
ComponentDto another = newPrivateProjectDto();
indexIssues(
newDocForProject("openhotspot1", project).setOwaspTop10(List.of("a1")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("openhotspot2021", project).setOwaspTop10For2021(List.of("a2")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("anotherProject", another).setOwaspTop10(List.of("a1")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("anotherProject2021", another).setOwaspTop10For2021(List.of("a2")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW));
List<SecurityStandardCategoryStatistics> owaspTop10Report = underTest.getOwaspTop10Report(project.uuid(), false, false, Y2017);
assertThat(owaspTop10Report)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots)
.contains(
tuple("a1", 1L /* openhotspot1 */));
List<SecurityStandardCategoryStatistics> owaspTop10For2021Report = underTest.getOwaspTop10Report(project.uuid(), false, false, Y2021);
assertThat(owaspTop10For2021Report)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots)
.contains(
tuple("a2", 1L /* openhotspot1 */));
}
@Test
public void getOwaspTop10Report_dont_count_closed_hotspots() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("openhotspot1", project).setOwaspTop10(List.of("a1")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("openhotspot2021", project).setOwaspTop10For2021(List.of("a2")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("closedHotspot", project).setOwaspTop10(List.of("a1")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_CLOSED)
.setResolution(Issue.RESOLUTION_FIXED),
newDocForProject("closedHotspot2021", project).setOwaspTop10For2021(List.of("a2")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_CLOSED)
.setResolution(Issue.RESOLUTION_FIXED));
List<SecurityStandardCategoryStatistics> owaspTop10Report = underTest.getOwaspTop10Report(project.uuid(), false, false, Y2017);
assertThat(owaspTop10Report)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots)
.contains(
tuple("a1", 1L /* openhotspot1 */));
List<SecurityStandardCategoryStatistics> owaspTop10For2021Report = underTest.getOwaspTop10Report(project.uuid(), false, false, Y2021);
assertThat(owaspTop10For2021Report)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots)
.contains(
tuple("a2", 1L /* openhotspot1 */));
}
@Test
public void getOwaspTop10Report_aggregation_no_cwe() {
List<SecurityStandardCategoryStatistics> owaspTop10Report = indexIssuesAndAssertOwaspReport(false);
assertThat(owaspTop10Report)
.isNotEmpty()
.allMatch(category -> category.getChildren().isEmpty());
}
@Test
public void getPciDss32Report_aggregation() {
List<SecurityStandardCategoryStatistics> pciDss32Report = indexIssuesAndAssertPciDss32Report();
assertThat(pciDss32Report)
.isNotEmpty();
assertThat(pciDss32Report.get(0).getChildren()).hasSize(2);
assertThat(pciDss32Report.get(1).getChildren()).isEmpty();
assertThat(pciDss32Report.get(2).getChildren()).hasSize(4);
assertThat(pciDss32Report.get(3).getChildren()).isEmpty();
assertThat(pciDss32Report.get(4).getChildren()).isEmpty();
assertThat(pciDss32Report.get(5).getChildren()).hasSize(2);
assertThat(pciDss32Report.get(6).getChildren()).isEmpty();
assertThat(pciDss32Report.get(7).getChildren()).hasSize(1);
assertThat(pciDss32Report.get(8).getChildren()).isEmpty();
assertThat(pciDss32Report.get(9).getChildren()).hasSize(1);
assertThat(pciDss32Report.get(10).getChildren()).isEmpty();
assertThat(pciDss32Report.get(11).getChildren()).isEmpty();
}
@Test
public void getOwaspAsvs40Report_aggregation() {
List<SecurityStandardCategoryStatistics> owaspAsvsReport = indexIssuesAndAssertOwaspAsvsReport();
assertThat(owaspAsvsReport)
.isNotEmpty();
assertThat(owaspAsvsReport.get(0).getChildren()).isEmpty();
assertThat(owaspAsvsReport.get(1).getChildren()).hasSize(2);
assertThat(owaspAsvsReport.get(2).getChildren()).hasSize(4);
assertThat(owaspAsvsReport.get(3).getChildren()).isEmpty();
assertThat(owaspAsvsReport.get(4).getChildren()).isEmpty();
assertThat(owaspAsvsReport.get(5).getChildren()).hasSize(2);
assertThat(owaspAsvsReport.get(6).getChildren()).hasSize(1);
assertThat(owaspAsvsReport.get(7).getChildren()).hasSize(1);
assertThat(owaspAsvsReport.get(8).getChildren()).isEmpty();
assertThat(owaspAsvsReport.get(9).getChildren()).hasSize(1);
assertThat(owaspAsvsReport.get(10).getChildren()).isEmpty();
assertThat(owaspAsvsReport.get(11).getChildren()).isEmpty();
assertThat(owaspAsvsReport.get(12).getChildren()).isEmpty();
assertThat(owaspAsvsReport.get(13).getChildren()).isEmpty();
}
@Test
public void getOwaspAsvs40ReportGroupedByLevel_aggregation() {
List<SecurityStandardCategoryStatistics> owaspAsvsReportGroupedByLevel = indexIssuesAndAssertOwaspAsvsReportGroupedByLevel();
assertThat(owaspAsvsReportGroupedByLevel)
.isNotEmpty();
assertThat(owaspAsvsReportGroupedByLevel.get(0).getChildren()).hasSize(3);
assertThat(owaspAsvsReportGroupedByLevel.get(1).getChildren()).hasSize(7);
assertThat(owaspAsvsReportGroupedByLevel.get(2).getChildren()).hasSize(11);
}
@Test
public void getOwaspTop10Report_aggregation_with_cwe() {
List<SecurityStandardCategoryStatistics> owaspTop10Report = indexIssuesAndAssertOwaspReport(true);
Map<String, List<SecurityStandardCategoryStatistics>> cweByOwasp = owaspTop10Report.stream()
.collect(Collectors.toMap(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getChildren));
assertThat(cweByOwasp.get("a1")).extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots, SecurityStandardCategoryStatistics::getSecurityReviewRating)
.containsExactlyInAnyOrder(
tuple("123", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 0L, 0L, 1),
tuple("456", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 0L, 0L, 1),
tuple("unknown", 0L, OptionalInt.empty(), 1L /* openhotspot1 */, 0L, 5));
assertThat(cweByOwasp.get("a3")).extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots, SecurityStandardCategoryStatistics::getSecurityReviewRating)
.containsExactlyInAnyOrder(
tuple("123", 2L /* openvul1, openvul2 */, OptionalInt.of(3)/* MAJOR = C */, 0L, 0L, 1),
tuple("456", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 0L, 0L, 1),
tuple("unknown", 0L, OptionalInt.empty(), 1L /* openhotspot1 */, 0L, 5));
}
@Test
public void getOwaspTop10For2021Report_aggregation_with_cwe() {
List<SecurityStandardCategoryStatistics> owaspTop10Report = indexIssuesAndAssertOwasp2021Report(true);
Map<String, List<SecurityStandardCategoryStatistics>> cweByOwasp = owaspTop10Report.stream()
.collect(Collectors.toMap(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getChildren));
assertThat(cweByOwasp.get("a1")).extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots, SecurityStandardCategoryStatistics::getSecurityReviewRating)
.containsExactlyInAnyOrder(
tuple("123", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 0L, 0L, 1),
tuple("456", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 0L, 0L, 1),
tuple("unknown", 0L, OptionalInt.empty(), 1L /* openhotspot1 */, 0L, 5));
assertThat(cweByOwasp.get("a3")).extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots, SecurityStandardCategoryStatistics::getSecurityReviewRating)
.containsExactlyInAnyOrder(
tuple("123", 2L /* openvul1, openvul2 */, OptionalInt.of(3)/* MAJOR = C */, 0L, 0L, 1),
tuple("456", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 0L, 0L, 1),
tuple("unknown", 0L, OptionalInt.empty(), 1L /* openhotspot1 */, 0L, 5));
}
private List<SecurityStandardCategoryStatistics> indexIssuesAndAssertOwaspReport(boolean includeCwe) {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("openvul1", project).setOwaspTop10(asList("a1", "a3")).setCwe(asList("123", "456")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN)
.setSeverity(Severity.MAJOR),
newDocForProject("openvul2", project).setOwaspTop10(asList("a3", "a6")).setCwe(List.of("123")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("notowaspvul", project).setOwaspTop10(singletonList(UNKNOWN_STANDARD)).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN).setSeverity(Severity.CRITICAL),
newDocForProject("toreviewhotspot1", project).setOwaspTop10(asList("a1", "a3")).setCwe(singletonList(UNKNOWN_STANDARD)).setType(RuleType.SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("toreviewhotspot2", project).setOwaspTop10(asList("a3", "a6")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("reviewedHotspot", project).setOwaspTop10(asList("a3", "a8")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED)
.setResolution(Issue.RESOLUTION_FIXED),
newDocForProject("notowasphotspot", project).setOwaspTop10(singletonList(UNKNOWN_STANDARD)).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW));
List<SecurityStandardCategoryStatistics> owaspTop10Report = underTest.getOwaspTop10Report(project.uuid(), false, includeCwe, Y2017);
assertThat(owaspTop10Report)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots, SecurityStandardCategoryStatistics::getSecurityReviewRating)
.containsExactlyInAnyOrder(
tuple("a1", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 1L /* toreviewhotspot1 */, 0L, 5),
tuple("a2", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("a3", 2L /* openvul1,openvul2 */, OptionalInt.of(3)/* MAJOR = C */, 2L/* toreviewhotspot1,toreviewhotspot2 */, 1L /* reviewedHotspot */, 4),
tuple("a4", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("a5", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("a6", 1L /* openvul2 */, OptionalInt.of(2) /* MINOR = B */, 1L /* toreviewhotspot2 */, 0L, 5),
tuple("a7", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("a8", 0L, OptionalInt.empty(), 0L, 1L /* reviewedHotspot */, 1),
tuple("a9", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("a10", 0L, OptionalInt.empty(), 0L, 0L, 1));
return owaspTop10Report;
}
private List<SecurityStandardCategoryStatistics> indexIssuesAndAssertPciDss32Report() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("openvul1", project).setPciDss32(asList("1.2.0", "3.4.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN)
.setSeverity(Severity.MAJOR),
newDocForProject("openvul2", project).setPciDss32(asList("3.3.2", "6.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("openvul3", project).setPciDss32(asList("10.1.2", "6.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("notpcidssvul", project).setPciDss32(singletonList(UNKNOWN_STANDARD)).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN).setSeverity(Severity.CRITICAL),
newDocForProject("toreviewhotspot1", project).setPciDss32(asList("1.3.0", "3.3.2")).setType(RuleType.SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("toreviewhotspot2", project).setPciDss32(asList("3.5.6", "6.4.5")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("reviewedHotspot", project).setPciDss32(asList("3.1.1", "8.6")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED)
.setResolution(Issue.RESOLUTION_FIXED),
newDocForProject("notpcidsshotspot", project).setPciDss32(singletonList(UNKNOWN_STANDARD)).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW));
List<SecurityStandardCategoryStatistics> pciDssReport = underTest.getPciDssReport(project.uuid(), false, PciDssVersion.V3_2).stream()
.sorted(comparing(s -> parseInt(s.getCategory())))
.collect(toList());
assertThat(pciDssReport)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots, SecurityStandardCategoryStatistics::getSecurityReviewRating)
.containsExactlyInAnyOrder(
tuple("1", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 1L /* toreviewhotspot1 */, 0L, 5),
tuple("2", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("3", 2L /* openvul1,openvul2 */, OptionalInt.of(3)/* MAJOR = C */, 2L/* toreviewhotspot1,toreviewhotspot2 */, 1L /* reviewedHotspot */, 4),
tuple("4", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("5", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("6", 2L /* openvul2 */, OptionalInt.of(2) /* MINOR = B */, 1L /* toreviewhotspot2 */, 0L, 5),
tuple("7", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("8", 0L, OptionalInt.empty(), 0L, 1L /* reviewedHotspot */, 1),
tuple("9", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("10", 1L, OptionalInt.of(2), 0L, 0L, 1),
tuple("11", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("12", 0L, OptionalInt.empty(), 0L, 0L, 1));
return pciDssReport;
}
private List<SecurityStandardCategoryStatistics> indexIssuesAndAssertOwaspAsvsReport() {
ComponentDto project = getProjectWithOwaspAsvsIssuesIndexed();
List<SecurityStandardCategoryStatistics> owaspAsvsReport = underTest.getOwaspAsvsReport(project.uuid(), false, OwaspAsvsVersion.V4_0, 3).stream()
.sorted(comparing(s -> parseInt(s.getCategory())))
.collect(toList());
assertThat(owaspAsvsReport)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots, SecurityStandardCategoryStatistics::getSecurityReviewRating)
.containsExactlyInAnyOrder(
tuple("1", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("2", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 1L /* toreviewhotspot1 */, 0L, 5),
tuple("3", 2L /* openvul1,openvul2 */, OptionalInt.of(3)/* MAJOR = C */, 2L/* toreviewhotspot1,toreviewhotspot2 */, 1L /* reviewedHotspot */, 4),
tuple("4", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("5", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("6", 2L /* openvul2 */, OptionalInt.of(2) /* MINOR = B */, 0L, 0L, 1),
tuple("7", 0L /* openvul2 */, OptionalInt.empty() /* MINOR = B */, 1L /* toreviewhotspot2 */, 0L, 5),
tuple("8", 0L, OptionalInt.empty(), 0L, 1L /* reviewedHotspot */, 1),
tuple("9", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("10", 1L, OptionalInt.of(2), 0L, 0L, 1),
tuple("11", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("12", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("13", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("14", 0L, OptionalInt.empty(), 0L, 0L, 1));
return owaspAsvsReport;
}
private List<SecurityStandardCategoryStatistics> indexIssuesAndAssertOwaspAsvsReportGroupedByLevel() {
ComponentDto project = getProjectWithOwaspAsvsIssuesIndexed();
List<SecurityStandardCategoryStatistics> owaspAsvsReportGroupedByLevel = new ArrayList<>();
owaspAsvsReportGroupedByLevel.addAll(underTest.getOwaspAsvsReportGroupedByLevel(project.uuid(), false, OwaspAsvsVersion.V4_0, 1).stream()
.sorted(comparing(s -> parseInt(s.getCategory())))
.toList());
owaspAsvsReportGroupedByLevel.addAll(underTest.getOwaspAsvsReportGroupedByLevel(project.uuid(), false, OwaspAsvsVersion.V4_0, 2).stream()
.sorted(comparing(s -> parseInt(s.getCategory())))
.toList());
owaspAsvsReportGroupedByLevel.addAll(underTest.getOwaspAsvsReportGroupedByLevel(project.uuid(), false, OwaspAsvsVersion.V4_0, 3).stream()
.sorted(comparing(s -> parseInt(s.getCategory())))
.toList());
assertThat(owaspAsvsReportGroupedByLevel)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots, SecurityStandardCategoryStatistics::getSecurityReviewRating)
.containsExactlyInAnyOrder(
tuple("l1", 1L /* openvul2 */, OptionalInt.of(2), 1L /* toreviewhotspot2 */, 0L, 5),
tuple("l2", 2L /* openvul1, openvul2 */, OptionalInt.of(3)/* MAJOR = C */, 2L /* toreviewhotspot1, toreviewhotspot2 */, 1L /* reviewedHotspot */, 4),
tuple("l3", 3L /* openvul1,openvul2,openvul3 */, OptionalInt.of(3)/* MAJOR = C */, 2L/* toreviewhotspot1,toreviewhotspot2 */, 1L /* reviewedHotspot */, 4));
return owaspAsvsReportGroupedByLevel;
}
@NotNull
private ComponentDto getProjectWithOwaspAsvsIssuesIndexed() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("openvul1", project).setOwaspAsvs40(asList("2.4.1", "3.2.4")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN)
.setSeverity(Severity.MAJOR),
newDocForProject("openvul2", project).setOwaspAsvs40(asList("3.4.5", "6.2.1")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("openvul3", project).setOwaspAsvs40(asList("10.2.4", "6.2.8")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("notowaspasvsvul", project).setOwaspAsvs40(singletonList(UNKNOWN_STANDARD)).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN).setSeverity(Severity.CRITICAL),
newDocForProject("toreviewhotspot1", project).setOwaspAsvs40(asList("2.2.5", "3.2.4")).setType(RuleType.SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("toreviewhotspot2", project).setOwaspAsvs40(asList("3.6.1", "7.1.1")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("reviewedHotspot", project).setOwaspAsvs40(asList("3.3.3", "8.3.7")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED)
.setResolution(Issue.RESOLUTION_FIXED),
newDocForProject("notowaspasvshotspot", project).setOwaspAsvs40(singletonList(UNKNOWN_STANDARD)).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW));
return project;
}
private List<SecurityStandardCategoryStatistics> indexIssuesAndAssertOwasp2021Report(boolean includeCwe) {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("openvul1", project).setOwaspTop10For2021(asList("a1", "a3")).setCwe(asList("123", "456")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN)
.setSeverity(Severity.MAJOR),
newDocForProject("openvul2", project).setOwaspTop10For2021(asList("a3", "a6")).setCwe(List.of("123")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("notowaspvul", project).setOwaspTop10For2021(singletonList(UNKNOWN_STANDARD)).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN).setSeverity(Severity.CRITICAL),
newDocForProject("toreviewhotspot1", project).setOwaspTop10For2021(asList("a1", "a3")).setCwe(singletonList(UNKNOWN_STANDARD)).setType(RuleType.SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("toreviewhotspot2", project).setOwaspTop10For2021(asList("a3", "a6")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("reviewedHotspot", project).setOwaspTop10For2021(asList("a3", "a8")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED)
.setResolution(Issue.RESOLUTION_FIXED),
newDocForProject("notowasphotspot", project).setOwaspTop10For2021(singletonList(UNKNOWN_STANDARD)).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW));
List<SecurityStandardCategoryStatistics> owaspTop10Report = underTest.getOwaspTop10Report(project.uuid(), false, includeCwe, Y2021);
assertThat(owaspTop10Report)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots, SecurityStandardCategoryStatistics::getSecurityReviewRating)
.containsExactlyInAnyOrder(
tuple("a1", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 1L /* toreviewhotspot1 */, 0L, 5),
tuple("a2", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("a3", 2L /* openvul1,openvul2 */, OptionalInt.of(3)/* MAJOR = C */, 2L/* toreviewhotspot1,toreviewhotspot2 */, 1L /* reviewedHotspot */, 4),
tuple("a4", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("a5", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("a6", 1L /* openvul2 */, OptionalInt.of(2) /* MINOR = B */, 1L /* toreviewhotspot2 */, 0L, 5),
tuple("a7", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("a8", 0L, OptionalInt.empty(), 0L, 1L /* reviewedHotspot */, 1),
tuple("a9", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("a10", 0L, OptionalInt.empty(), 0L, 0L, 1));
return owaspTop10Report;
}
@Test
public void getPciDssReport_aggregation_on_portfolio() {
ComponentDto portfolio1 = db.components().insertPrivateApplication().getMainBranchComponent();
ComponentDto portfolio2 = db.components().insertPrivateApplication().getMainBranchComponent();
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
indexIssues(
newDocForProject("openvul1", project1).setPciDss32(asList("1.2.0", "3.4.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN)
.setSeverity(Severity.MAJOR),
newDocForProject("openvul2", project2).setPciDss32(asList("3.3.2", "6.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("openvul3", project1).setPciDss32(asList("10.1.2", "6.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("notpcidssvul", project1).setPciDss32(singletonList(UNKNOWN_STANDARD)).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN).setSeverity(Severity.CRITICAL),
newDocForProject("toreviewhotspot1", project2).setPciDss32(asList("1.3.0", "3.3.2")).setType(RuleType.SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("toreviewhotspot2", project1).setPciDss32(asList("3.5.6", "6.4.5")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("reviewedHotspot", project2).setPciDss32(asList("3.1.1", "8.6")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED)
.setResolution(Issue.RESOLUTION_FIXED),
newDocForProject("notpcidsshotspot", project1).setPciDss32(singletonList(UNKNOWN_STANDARD)).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW));
indexView(portfolio1.uuid(), singletonList(project1.uuid()));
indexView(portfolio2.uuid(), singletonList(project2.uuid()));
List<SecurityStandardCategoryStatistics> pciDssReport = underTest.getPciDssReport(portfolio1.uuid(), true, PciDssVersion.V3_2).stream()
.sorted(comparing(s -> parseInt(s.getCategory())))
.collect(toList());
assertThat(pciDssReport)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots, SecurityStandardCategoryStatistics::getSecurityReviewRating)
.containsExactlyInAnyOrder(
tuple("1", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 0L, 0L, 1),
tuple("2", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("3", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 1L/* toreviewhotspot2 */, 0L, 5),
tuple("4", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("5", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("6", 1L /* openvul3 */, OptionalInt.of(2) /* MINOR = B */, 1L /* toreviewhotspot2 */, 0L, 5),
tuple("7", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("8", 0L, OptionalInt.empty(), 0L, 0L /* reviewedHotspot */, 1),
tuple("9", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("10", 1L /* openvul3 */, OptionalInt.of(2), 0L, 0L, 1),
tuple("11", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("12", 0L, OptionalInt.empty(), 0L, 0L, 1));
}
@Test
public void getOwaspAsvsReport_aggregation_on_portfolio() {
ComponentDto portfolio1 = db.components().insertPrivateApplication().getMainBranchComponent();
ComponentDto portfolio2 = db.components().insertPrivateApplication().getMainBranchComponent();
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
indexIssues(
newDocForProject("openvul1", project1).setOwaspAsvs40(asList("2.1.1", "3.4.5")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN)
.setSeverity(Severity.MAJOR),
newDocForProject("openvul2", project2).setOwaspAsvs40(asList("3.3.2", "6.2.1")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("openvul3", project1).setOwaspAsvs40(asList("10.3.2", "6.2.1")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("notowaspasvsvul", project1).setOwaspAsvs40(singletonList(UNKNOWN_STANDARD)).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN).setSeverity(Severity.CRITICAL),
newDocForProject("toreviewhotspot1", project2).setOwaspAsvs40(asList("2.1.3", "3.3.2")).setType(RuleType.SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("toreviewhotspot2", project1).setOwaspAsvs40(asList("3.4.4", "6.2.1")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("reviewedHotspot", project2).setOwaspAsvs40(asList("3.1.1", "8.3.1")).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED)
.setResolution(Issue.RESOLUTION_FIXED),
newDocForProject("notowaspasvshotspot", project1).setOwaspAsvs40(singletonList(UNKNOWN_STANDARD)).setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW));
indexView(portfolio1.uuid(), singletonList(project1.uuid()));
indexView(portfolio2.uuid(), singletonList(project2.uuid()));
List<SecurityStandardCategoryStatistics> owaspAsvsReport = underTest.getOwaspAsvsReport(portfolio1.uuid(), true, OwaspAsvsVersion.V4_0, 1).stream()
.sorted(comparing(s -> parseInt(s.getCategory())))
.collect(toList());
assertThat(owaspAsvsReport)
.extracting(SecurityStandardCategoryStatistics::getCategory, SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getVulnerabilityRating, SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots, SecurityStandardCategoryStatistics::getSecurityReviewRating)
.containsExactlyInAnyOrder(
tuple("1", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("2", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 0L, 0L, 1),
tuple("3", 1L /* openvul1 */, OptionalInt.of(3)/* MAJOR = C */, 1L/* toreviewhotspot2 */, 0L, 5),
tuple("4", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("5", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("6", 1L /* openvul3 */, OptionalInt.of(2) /* MINOR = B */, 1L /* toreviewhotspot2 */, 0L, 5),
tuple("7", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("8", 0L, OptionalInt.empty(), 0L, 0L /* reviewedHotspot */, 1),
tuple("9", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("10", 1L /* openvul3 */, OptionalInt.of(2), 0L, 0L, 1),
tuple("11", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("12", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("13", 0L, OptionalInt.empty(), 0L, 0L, 1),
tuple("14", 0L, OptionalInt.empty(), 0L, 0L, 1));
}
@Test
public void getCWETop25Report_aggregation() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("openvul", project).setCwe(List.of("119")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN)
.setSeverity(Severity.MAJOR),
newDocForProject("notopenvul", project).setCwe(List.of("119")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_CLOSED)
.setResolution(Issue.RESOLUTION_FIXED)
.setSeverity(Severity.BLOCKER),
newDocForProject("toreviewhotspot", project).setCwe(List.of("89")).setType(RuleType.SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("only2020", project).setCwe(List.of("862")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("unknown", project).setCwe(List.of("999")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR));
List<SecurityStandardCategoryStatistics> cweTop25Reports = underTest.getCweTop25Reports(project.uuid(), false);
List<String> listOfYears = cweTop25Reports.stream()
.map(SecurityStandardCategoryStatistics::getCategory)
.collect(toList());
assertThat(listOfYears).contains("2020", "2021", "2022");
SecurityStandardCategoryStatistics cwe2020 = cweTop25Reports.stream()
.filter(s -> s.getCategory().equals("2020"))
.findAny().get();
assertThat(cwe2020.getChildren()).hasSize(25);
assertThat(findRuleInCweByYear(cwe2020, "119")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(1L, 0L, 0L);
assertThat(findRuleInCweByYear(cwe2020, "89")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(0L, 1L, 0L);
assertThat(findRuleInCweByYear(cwe2020, "862")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(1L, 0L, 0L);
assertThat(findRuleInCweByYear(cwe2020, "999")).isNull();
SecurityStandardCategoryStatistics cwe2021 = cweTop25Reports.stream()
.filter(s -> s.getCategory().equals("2021"))
.findAny().get();
assertThat(cwe2021.getChildren()).hasSize(25);
assertThat(findRuleInCweByYear(cwe2021, "119")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(1L, 0L, 0L);
assertThat(findRuleInCweByYear(cwe2021, "89")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(0L, 1L, 0L);
assertThat(findRuleInCweByYear(cwe2021, "295")).isNull();
assertThat(findRuleInCweByYear(cwe2021, "999")).isNull();
SecurityStandardCategoryStatistics cwe2022 = cweTop25Reports.stream()
.filter(s -> s.getCategory().equals("2022"))
.findAny().get();
assertThat(cwe2022.getChildren()).hasSize(25);
assertThat(findRuleInCweByYear(cwe2022, "119")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(1L, 0L, 0L);
assertThat(findRuleInCweByYear(cwe2022, "89")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(0L, 1L, 0L);
assertThat(findRuleInCweByYear(cwe2022, "950")).isNull();
assertThat(findRuleInCweByYear(cwe2022, "999")).isNull();
}
@Test
public void getCWETop25Report_aggregation_on_portfolio() {
ComponentDto application = db.components().insertPrivateApplication().getMainBranchComponent();
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
indexIssues(
newDocForProject("openvul1", project1).setCwe(List.of("119")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_OPEN)
.setSeverity(Severity.MAJOR),
newDocForProject("openvul2", project2).setCwe(List.of("119")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("toreviewhotspot", project1).setCwe(List.of("89")).setType(RuleType.SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW),
newDocForProject("only2020", project2).setCwe(List.of("862")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR),
newDocForProject("unknown", project2).setCwe(List.of("999")).setType(RuleType.VULNERABILITY).setStatus(Issue.STATUS_REOPENED)
.setSeverity(Severity.MINOR));
indexView(application.uuid(), asList(project1.uuid(), project2.uuid()));
List<SecurityStandardCategoryStatistics> cweTop25Reports = underTest.getCweTop25Reports(application.uuid(), true);
List<String> listOfYears = cweTop25Reports.stream()
.map(SecurityStandardCategoryStatistics::getCategory)
.collect(toList());
assertThat(listOfYears).contains("2020", "2021", "2022");
SecurityStandardCategoryStatistics cwe2020 = cweTop25Reports.stream()
.filter(s -> s.getCategory().equals("2020"))
.findAny().get();
assertThat(cwe2020.getChildren()).hasSize(25);
assertThat(findRuleInCweByYear(cwe2020, "119")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(2L, 0L, 0L);
assertThat(findRuleInCweByYear(cwe2020, "89")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(0L, 1L, 0L);
assertThat(findRuleInCweByYear(cwe2020, "862")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(1L, 0L, 0L);
assertThat(findRuleInCweByYear(cwe2020, "999")).isNull();
SecurityStandardCategoryStatistics cwe2021 = cweTop25Reports.stream()
.filter(s -> s.getCategory().equals("2021"))
.findAny().get();
assertThat(cwe2021.getChildren()).hasSize(25);
assertThat(findRuleInCweByYear(cwe2021, "119")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(2L, 0L, 0L);
assertThat(findRuleInCweByYear(cwe2021, "89")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(0L, 1L, 0L);
assertThat(findRuleInCweByYear(cwe2021, "295")).isNull();
assertThat(findRuleInCweByYear(cwe2021, "999")).isNull();
SecurityStandardCategoryStatistics cwe2022 = cweTop25Reports.stream()
.filter(s -> s.getCategory().equals("2022"))
.findAny().get();
assertThat(cwe2022.getChildren()).hasSize(25);
assertThat(findRuleInCweByYear(cwe2022, "119")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(2L, 0L, 0L);
assertThat(findRuleInCweByYear(cwe2022, "89")).isNotNull()
.extracting(SecurityStandardCategoryStatistics::getVulnerabilities,
SecurityStandardCategoryStatistics::getToReviewSecurityHotspots,
SecurityStandardCategoryStatistics::getReviewedSecurityHotspots)
.containsExactlyInAnyOrder(0L, 1L, 0L);
assertThat(findRuleInCweByYear(cwe2022, "295")).isNull();
assertThat(findRuleInCweByYear(cwe2022, "999")).isNull();
}
private SecurityStandardCategoryStatistics findRuleInCweByYear(SecurityStandardCategoryStatistics statistics, String cweId) {
return statistics.getChildren().stream().filter(stat -> stat.getCategory().equals(cweId)).findAny().orElse(null);
}
private void indexView(String viewUuid, List<String> projectBranchUuids) {
viewIndexer.index(new ViewDoc().setUuid(viewUuid).setProjectBranchUuids(projectBranchUuids));
}
}
| 48,467 | 64.320755 | 202 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSortTest.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.issue.index;
import org.elasticsearch.action.search.SearchResponse;
import org.junit.Test;
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.Severity;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.es.SearchOptions;
import static org.sonar.api.utils.DateUtils.parseDateTime;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.server.issue.IssueDocTesting.newDoc;
public class IssueIndexSortTest extends IssueIndexTestCommon {
@Test
public void sort_by_status() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setStatus(Issue.STATUS_OPEN),
newDoc("I2", project.uuid(), file).setStatus(Issue.STATUS_CLOSED),
newDoc("I3", project.uuid(), file).setStatus(Issue.STATUS_REOPENED));
IssueQuery.Builder query = IssueQuery.builder().sort(IssueQuery.SORT_BY_STATUS).asc(true);
assertThatSearchReturnsOnly(query, "I2", "I1", "I3");
query = IssueQuery.builder().sort(IssueQuery.SORT_BY_STATUS).asc(false);
assertThatSearchReturnsOnly(query, "I3", "I1", "I2");
}
@Test
public void sort_by_severity() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setSeverity(Severity.BLOCKER),
newDoc("I2", project.uuid(), file).setSeverity(Severity.INFO),
newDoc("I3", project.uuid(), file).setSeverity(Severity.MINOR),
newDoc("I4", project.uuid(), file).setSeverity(Severity.CRITICAL),
newDoc("I5", project.uuid(), file).setSeverity(Severity.MAJOR));
IssueQuery.Builder query = IssueQuery.builder().sort(IssueQuery.SORT_BY_SEVERITY).asc(true);
assertThatSearchReturnsOnly(query, "I2", "I3", "I5", "I4", "I1");
query = IssueQuery.builder().sort(IssueQuery.SORT_BY_SEVERITY).asc(false);
assertThatSearchReturnsOnly(query, "I1", "I4", "I5", "I3", "I2");
}
@Test
public void sort_by_creation_date() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setFuncCreationDate(parseDateTime("2014-09-23T00:00:00+0100")),
newDoc("I2", project.uuid(), file).setFuncCreationDate(parseDateTime("2014-09-24T00:00:00+0100")));
IssueQuery.Builder query = IssueQuery.builder().sort(IssueQuery.SORT_BY_CREATION_DATE).asc(true);
SearchResponse result = underTest.search(query.build(), new SearchOptions());
assertThatSearchReturnsOnly(query, "I1", "I2");
query = IssueQuery.builder().sort(IssueQuery.SORT_BY_CREATION_DATE).asc(false);
assertThatSearchReturnsOnly(query, "I2", "I1");
}
@Test
public void sort_by_update_date() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setFuncUpdateDate(parseDateTime("2014-09-23T00:00:00+0100")),
newDoc("I2", project.uuid(), file).setFuncUpdateDate(parseDateTime("2014-09-24T00:00:00+0100")));
IssueQuery.Builder query = IssueQuery.builder().sort(IssueQuery.SORT_BY_UPDATE_DATE).asc(true);
SearchResponse result = underTest.search(query.build(), new SearchOptions());
assertThatSearchReturnsOnly(query, "I1", "I2");
query = IssueQuery.builder().sort(IssueQuery.SORT_BY_UPDATE_DATE).asc(false);
assertThatSearchReturnsOnly(query, "I2", "I1");
}
@Test
public void sort_by_close_date() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I1", project.uuid(), file).setFuncCloseDate(parseDateTime("2014-09-23T00:00:00+0100")),
newDoc("I2", project.uuid(), file).setFuncCloseDate(parseDateTime("2014-09-24T00:00:00+0100")),
newDoc("I3", project.uuid(), file).setFuncCloseDate(null));
IssueQuery.Builder query = IssueQuery.builder().sort(IssueQuery.SORT_BY_CLOSE_DATE).asc(true);
SearchResponse result = underTest.search(query.build(), new SearchOptions());
assertThatSearchReturnsOnly(query, "I3", "I1", "I2");
query = IssueQuery.builder().sort(IssueQuery.SORT_BY_CLOSE_DATE).asc(false);
assertThatSearchReturnsOnly(query, "I2", "I1", "I3");
}
@Test
public void sort_by_file_and_line() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file1 = newFileDto(project, null, "F1").setPath("src/main/xoo/org/sonar/samples/File.xoo");
ComponentDto file2 = newFileDto(project, null, "F2").setPath("src/main/xoo/org/sonar/samples/File2.xoo");
indexIssues(
// file F1
newDoc("F1_2", project.uuid(), file1).setLine(20),
newDoc("F1_1", project.uuid(), file1).setLine(null),
newDoc("F1_3", project.uuid(), file1).setLine(25),
// file F2
newDoc("F2_1", project.uuid(), file2).setLine(9),
newDoc("F2_2", project.uuid(), file2).setLine(109),
// two issues on the same line -> sort by key
newDoc("F2_3", project.uuid(), file2).setLine(109));
// ascending sort -> F1 then F2. Line "0" first.
IssueQuery.Builder query = IssueQuery.builder().sort(IssueQuery.SORT_BY_FILE_LINE).asc(true);
assertThatSearchReturnsOnly(query, "F1_1", "F1_2", "F1_3", "F2_1", "F2_2", "F2_3");
// descending sort -> F2 then F1
query = IssueQuery.builder().sort(IssueQuery.SORT_BY_FILE_LINE).asc(false);
assertThatSearchReturnsOnly(query, "F2_3", "F2_2", "F2_1", "F1_3", "F1_2", "F1_1");
}
@Test
public void default_sort_is_by_creation_date_then_project_then_file_then_line_then_issue_key() {
ComponentDto project1 = newPrivateProjectDto("P1");
ComponentDto file1 = newFileDto(project1, null, "F1").setPath("src/main/xoo/org/sonar/samples/File.xoo");
ComponentDto file2 = newFileDto(project1, null, "F2").setPath("src/main/xoo/org/sonar/samples/File2.xoo");
ComponentDto project2 = newPrivateProjectDto("P2");
ComponentDto file3 = newFileDto(project2, null, "F3").setPath("src/main/xoo/org/sonar/samples/File3.xoo");
indexIssues(
// file F1 from project P1
newDoc("F1_1", project1.uuid(), file1).setLine(20).setFuncCreationDate(parseDateTime("2014-09-23T00:00:00+0100")),
newDoc("F1_2", project1.uuid(), file1).setLine(null).setFuncCreationDate(parseDateTime("2014-09-23T00:00:00+0100")),
newDoc("F1_3", project1.uuid(), file1).setLine(25).setFuncCreationDate(parseDateTime("2014-09-23T00:00:00+0100")),
// file F2 from project P1
newDoc("F2_1", project1.uuid(), file2).setLine(9).setFuncCreationDate(parseDateTime("2014-09-23T00:00:00+0100")),
newDoc("F2_2", project1.uuid(), file2).setLine(109).setFuncCreationDate(parseDateTime("2014-09-23T00:00:00+0100")),
// two issues on the same line -> sort by key
newDoc("F2_3", project1.uuid(), file2).setLine(109).setFuncCreationDate(parseDateTime("2014-09-23T00:00:00+0100")),
// file F3 from project P2
newDoc("F3_1", project2.uuid(), file3).setLine(20).setFuncCreationDate(parseDateTime("2014-09-24T00:00:00+0100")),
newDoc("F3_2", project2.uuid(), file3).setLine(20).setFuncCreationDate(parseDateTime("2014-09-23T00:00:00+0100")));
assertThatSearchReturnsOnly(IssueQuery.builder(), "F3_1", "F1_2", "F1_1", "F1_3", "F2_1", "F2_2", "F2_3", "F3_2");
}
}
| 8,299 | 45.111111 | 122 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSyncProgressCheckerTest.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.issue.index;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.ce.CeActivityDto;
import org.sonar.db.ce.CeQueueDto;
import org.sonar.db.ce.CeQueueDto.Status;
import org.sonar.db.ce.CeTaskTypes;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ProjectData;
import org.sonar.server.es.EsIndexSyncInProgressException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.ce.CeActivityDto.Status.FAILED;
import static org.sonar.db.ce.CeActivityDto.Status.SUCCESS;
@RunWith(DataProviderRunner.class)
public class IssueIndexSyncProgressCheckerTest {
private final System2 system2 = new System2();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private final IssueIndexSyncProgressChecker underTest = new IssueIndexSyncProgressChecker(db.getDbClient());
@Test
public void return_100_if_there_is_no_tasks_left() {
IssueSyncProgress issueSyncProgress = underTest.getIssueSyncProgress(db.getSession());
assertThat(issueSyncProgress.getCompleted()).isZero();
assertThat(issueSyncProgress.getTotal()).isZero();
assertThat(issueSyncProgress.toPercentCompleted()).isEqualTo(100);
assertThat(issueSyncProgress.isCompleted()).isTrue();
assertThat(issueSyncProgress.hasFailures()).isFalse();
}
@Test
public void return_100_if_all_branches_have_need_issue_sync_set_FALSE() {
IntStream.range(0, 13).forEach(value -> insertProjectWithBranches(false, 2));
IntStream.range(0, 14).forEach(value -> insertProjectWithBranches(false, 4));
IntStream.range(0, 4).forEach(value -> insertProjectWithBranches(false, 10));
IssueSyncProgress result = underTest.getIssueSyncProgress(db.getSession());
assertThat(result.getCompleted()).isEqualTo(153);
assertThat(result.getTotal()).isEqualTo(153);
assertThat(result.toPercentCompleted()).isEqualTo(100);
assertThat(result.isCompleted()).isTrue();
}
@Test
public void return_has_failure_true_if_exists_task() {
assertThat(underTest.getIssueSyncProgress(db.getSession()).hasFailures()).isFalse();
ProjectData projectData1 = insertProjectWithBranches(false, 0);
insertCeActivity("TASK_1", projectData1, SUCCESS);
ProjectData projectData2 = insertProjectWithBranches(false, 0);
insertCeActivity("TASK_2", projectData2, SUCCESS);
assertThat(underTest.getIssueSyncProgress(db.getSession()).hasFailures()).isFalse();
ProjectData projectData3 = insertProjectWithBranches(true, 0);
insertCeActivity("TASK_3", projectData3, FAILED);
assertThat(underTest.getIssueSyncProgress(db.getSession()).hasFailures()).isTrue();
}
@Test
@UseDataProvider("various_task_numbers")
public void return_correct_percent_value_for_branches_to_sync(int toSync, int synced, int expectedPercent) {
IntStream.range(0, toSync).forEach(value -> insertProjectWithBranches(true, 0));
IntStream.range(0, synced).forEach(value -> insertProjectWithBranches(false, 0));
IssueSyncProgress result = underTest.getIssueSyncProgress(db.getSession());
assertThat(result.getCompleted()).isEqualTo(synced);
assertThat(result.getTotal()).isEqualTo(toSync + synced);
assertThat(result.toPercentCompleted()).isEqualTo(expectedPercent);
}
@DataProvider
public static Object[][] various_task_numbers() {
return new Object[][] {
// toSync, synced, expected result
{0, 0, 100},
{0, 9, 100},
{10, 0, 0},
{99, 1, 1},
{2, 1, 33},
{6, 4, 40},
{7, 7, 50},
{1, 2, 66},
{4, 10, 71},
{1, 99, 99},
};
}
@Test
public void return_0_if_all_branches_have_need_issue_sync_set_true() {
// only project
IntStream.range(0, 10).forEach(value -> insertProjectWithBranches(true, 0));
// project + additional branch
IntStream.range(0, 10).forEach(value -> insertProjectWithBranches(true, 1));
IssueSyncProgress result = underTest.getIssueSyncProgress(db.getSession());
assertThat(result.getCompleted()).isZero();
assertThat(result.getTotal()).isEqualTo(30);
assertThat(result.toPercentCompleted()).isZero();
}
@Test
public void return_is_completed_true_if_no_pending_or_in_progress_tasks() {
// only project
IntStream.range(0, 10).forEach(value -> insertProjectWithBranches(false, 0));
// project + additional branch
IntStream.range(0, 10).forEach(value -> insertProjectWithBranches(false, 1));
IssueSyncProgress result = underTest.getIssueSyncProgress(db.getSession());
assertThat(result.isCompleted()).isTrue();
}
@Test
public void return_is_completed_true_if_pending_task_exist_but_all_branches_have_been_synced() {
insertCeQueue("TASK_1", Status.PENDING);
// only project
IntStream.range(0, 10).forEach(value -> insertProjectWithBranches(false, 0));
// project + additional branch
IntStream.range(0, 10).forEach(value -> insertProjectWithBranches(false, 1));
IssueSyncProgress result = underTest.getIssueSyncProgress(db.getSession());
assertThat(result.isCompleted()).isTrue();
}
@Test
public void return_is_completed_true_if_in_progress_task_exist_but_all_branches_have_been_synced() {
insertCeQueue("TASK_1", Status.IN_PROGRESS);
// only project
IntStream.range(0, 10).forEach(value -> insertProjectWithBranches(false, 0));
// project + additional branch
IntStream.range(0, 10).forEach(value -> insertProjectWithBranches(false, 1));
IssueSyncProgress result = underTest.getIssueSyncProgress(db.getSession());
assertThat(result.isCompleted()).isTrue();
}
@Test
public void return_is_completed_false_if_pending_task_exist_and_branches_need_issue_sync() {
insertCeQueue("TASK_1", Status.PENDING);
// only project
IntStream.range(0, 10).forEach(value -> insertProjectWithBranches(true, 0));
// project + additional branch
IntStream.range(0, 10).forEach(value -> insertProjectWithBranches(false, 1));
IssueSyncProgress result = underTest.getIssueSyncProgress(db.getSession());
assertThat(result.isCompleted()).isFalse();
}
@Test
public void return_is_completed_false_if_in_progress_task_exist_and_branches_need_issue_sync() {
insertCeQueue("TASK_1", Status.IN_PROGRESS);
// only project
IntStream.range(0, 10).forEach(value -> insertProjectWithBranches(true, 0));
// project + additional branch
IntStream.range(0, 10).forEach(value -> insertProjectWithBranches(false, 1));
IssueSyncProgress result = underTest.getIssueSyncProgress(db.getSession());
assertThat(result.isCompleted()).isFalse();
}
@Test
public void checkIfAnyComponentsNeedIssueSync_throws_exception_if_all_components_have_need_issue_sync_TRUE() {
ProjectData projectData1 = insertProjectWithBranches(true, 0);
ProjectData projectData2 = insertProjectWithBranches(true, 0);
DbSession session = db.getSession();
List<String> projectKeys = Arrays.asList(projectData1.getProjectDto().getKey(), projectData2.getProjectDto().getKey());
assertThatThrownBy(() -> underTest.checkIfAnyComponentsNeedIssueSync(session, projectKeys))
.isInstanceOf(EsIndexSyncInProgressException.class)
.hasFieldOrPropertyWithValue("httpCode", 503)
.hasMessage("Results are temporarily unavailable. Indexing of issues is in progress.");
}
@Test
public void checkIfAnyComponentsNeedIssueSync_does_not_throw_exception_if_all_components_have_need_issue_sync_FALSE() {
underTest.checkIfAnyComponentsNeedIssueSync(db.getSession(), Collections.emptyList());
ProjectData projectData1 = insertProjectWithBranches(false, 0);
ProjectData projectData2 = insertProjectWithBranches(false, 0);
underTest.checkIfAnyComponentsNeedIssueSync(db.getSession(), Arrays.asList(projectData1.getProjectDto().getKey(), projectData2.getProjectDto().getKey()));
}
@Test
public void checkIfAnyComponentsNeedIssueSync_throws_exception_if_at_least_one_component_has_need_issue_sync_TRUE() {
ProjectData projectData1 = insertProjectWithBranches(false, 0);
ProjectData projectData2 = insertProjectWithBranches(true, 0);
DbSession session = db.getSession();
List<String> projectKeys = Arrays.asList(projectData1.getProjectDto().getKey(), projectData2.getProjectDto().getKey());
assertThatThrownBy(() -> underTest.checkIfAnyComponentsNeedIssueSync(session, projectKeys))
.isInstanceOf(EsIndexSyncInProgressException.class)
.hasFieldOrPropertyWithValue("httpCode", 503)
.hasMessage("Results are temporarily unavailable. Indexing of issues is in progress.");
}
@Test
public void checkIfComponentNeedIssueSync_single_component() {
ProjectData projectData1 = insertProjectWithBranches(true, 0);
ProjectData projectData2 = insertProjectWithBranches(false, 0);
DbSession session = db.getSession();
// do nothing when need issue sync false
underTest.checkIfComponentNeedIssueSync(session, projectData2.getProjectDto().getKey());
// throws if flag set to TRUE
String key = projectData1.getProjectDto().getKey();
assertThatThrownBy(() -> underTest.checkIfComponentNeedIssueSync(session, key))
.isInstanceOf(EsIndexSyncInProgressException.class)
.hasFieldOrPropertyWithValue("httpCode", 503)
.hasMessage("Results are temporarily unavailable. Indexing of issues is in progress.");
}
@Test
public void checkIfAnyComponentsNeedIssueSync_single_view_subview_or_app() {
ProjectData projectData1 = insertProjectWithBranches(true, 0);
ComponentDto app = db.components().insertPublicApplication().getMainBranchComponent();
ComponentDto view = db.components().insertPrivatePortfolio();
ComponentDto subview = db.components().insertSubView(view);
DbSession session = db.getSession();
List<String> appViewOrSubviewKeys = Arrays.asList(projectData1.getProjectDto().getKey(), app.getKey(), view.getKey(), subview.getKey());
// throws if flag set to TRUE
assertThatThrownBy(() -> underTest.checkIfAnyComponentsNeedIssueSync(session,
appViewOrSubviewKeys))
.isInstanceOf(EsIndexSyncInProgressException.class)
.hasFieldOrPropertyWithValue("httpCode", 503)
.hasMessage("Results are temporarily unavailable. Indexing of issues is in progress.");
}
@Test
public void checkIfIssueSyncInProgress_throws_exception_if_at_least_one_component_has_need_issue_sync_TRUE() {
insertProjectWithBranches(false, 0);
underTest.checkIfIssueSyncInProgress(db.getSession());
insertProjectWithBranches(true, 0);
DbSession session = db.getSession();
assertThatThrownBy(() -> underTest.checkIfIssueSyncInProgress(session))
.isInstanceOf(EsIndexSyncInProgressException.class)
.hasFieldOrPropertyWithValue("httpCode", 503)
.hasMessage("Results are temporarily unavailable. Indexing of issues is in progress.");
}
@Test
public void doProjectNeedIssueSync() {
ProjectData projectData1 = insertProjectWithBranches(false, 0);
assertThat(underTest.doProjectNeedIssueSync(db.getSession(), projectData1.getProjectDto().getUuid())).isFalse();
ProjectData projectData2 = insertProjectWithBranches(true, 0);
assertThat(underTest.doProjectNeedIssueSync(db.getSession(), projectData2.getProjectDto().getUuid())).isTrue();
}
@Test
public void findProjectUuidsWithIssuesSyncNeed() {
ProjectData projectData1 = insertProjectWithBranches(false, 0);
ProjectData projectData2 = insertProjectWithBranches(false, 0);
ProjectData projectData3 = insertProjectWithBranches(true, 0);
ProjectData projectData4 = insertProjectWithBranches(true, 0);
assertThat(underTest.findProjectUuidsWithIssuesSyncNeed(db.getSession(),
Arrays.asList(projectData1.getProjectDto().getUuid(), projectData2.getProjectDto().getUuid(), projectData3.getProjectDto().getUuid(), projectData4.getProjectDto().getUuid())))
.containsOnly(projectData3.getProjectDto().getUuid(), projectData4.getProjectDto().getUuid());
}
private ProjectData insertProjectWithBranches(boolean needIssueSync, int numberOfBranches) {
ProjectData projectData = db.components()
.insertPrivateProject(branchDto -> branchDto.setNeedIssueSync(needIssueSync), c -> {
}, p -> {
});
IntStream.range(0, numberOfBranches).forEach(
i -> db.components().insertProjectBranch(projectData.getProjectDto(), branchDto -> branchDto.setNeedIssueSync(needIssueSync)));
return projectData;
}
private CeQueueDto insertCeQueue(String uuid, CeQueueDto.Status status) {
CeQueueDto queueDto = new CeQueueDto();
queueDto.setUuid(uuid);
queueDto.setStatus(status);
queueDto.setTaskType(CeTaskTypes.BRANCH_ISSUE_SYNC);
db.getDbClient().ceQueueDao().insert(db.getSession(), queueDto);
return queueDto;
}
private CeActivityDto insertCeActivity(String uuid, ProjectData projectData, CeActivityDto.Status status) {
CeQueueDto queueDto = new CeQueueDto();
queueDto.setUuid(uuid);
queueDto.setTaskType(CeTaskTypes.BRANCH_ISSUE_SYNC);
CeActivityDto dto = new CeActivityDto(queueDto);
dto.setComponentUuid(projectData.getMainBranchComponent().uuid());
dto.setEntityUuid(projectData.projectUuid());
dto.setStatus(status);
dto.setTaskType(CeTaskTypes.BRANCH_ISSUE_SYNC);
dto.setAnalysisUuid(uuid + "_AA");
dto.setCreatedAt(system2.now());
db.getDbClient().ceActivityDao().insert(db.getSession(), dto);
return dto;
}
}
| 14,791 | 42.125364 | 181 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexTest.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.issue.index;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.TotalHits.Relation;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.junit.Test;
import org.sonar.api.issue.Issue;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.SearchOptions;
import static com.google.common.collect.ImmutableSortedSet.of;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.db.user.GroupTesting.newGroupDto;
import static org.sonar.db.user.UserTesting.newUserDto;
import static org.sonar.server.issue.IssueDocTesting.newDoc;
import static org.sonar.server.issue.IssueDocTesting.newDocForProject;
public class IssueIndexTest extends IssueIndexTestCommon {
@Test
public void paging() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
for (int i = 0; i < 12; i++) {
indexIssues(newDoc("I" + i, project.uuid(), file));
}
IssueQuery.Builder query = IssueQuery.builder();
// There are 12 issues in total, with 10 issues per page, the page 2 should only contain 2 elements
SearchResponse result = underTest.search(query.build(), new SearchOptions().setPage(2, 10));
assertThat(result.getHits().getHits()).hasSize(2);
assertThat(result.getHits().getTotalHits()).isEqualTo(new TotalHits(12, TotalHits.Relation.EQUAL_TO));
result = underTest.search(IssueQuery.builder().build(), new SearchOptions().setOffset(0).setLimit(5));
assertThat(result.getHits().getHits()).hasSize(5);
assertThat(result.getHits().getTotalHits()).isEqualTo(new TotalHits(12, TotalHits.Relation.EQUAL_TO));
result = underTest.search(IssueQuery.builder().build(), new SearchOptions().setOffset(2).setLimit(10));
assertThat(result.getHits().getHits()).hasSize(10);
assertThat(result.getHits().getTotalHits()).isEqualTo(new TotalHits(12, TotalHits.Relation.EQUAL_TO));
}
@Test
public void search_with_max_limit() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
List<IssueDoc> issues = new ArrayList<>();
for (int i = 0; i < 500; i++) {
String key = "I" + i;
issues.add(newDoc(key, project.uuid(), file));
}
indexIssues(issues.toArray(new IssueDoc[]{}));
IssueQuery.Builder query = IssueQuery.builder();
SearchResponse result = underTest.search(query.build(), new SearchOptions().setLimit(500));
assertThat(result.getHits().getHits()).hasSize(SearchOptions.MAX_PAGE_SIZE);
}
// SONAR-14224
@Test
public void search_exceeding_default_index_max_window() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
List<IssueDoc> issues = new ArrayList<>();
for (int i = 0; i < 11_000; i++) {
String key = "I" + i;
issues.add(newDoc(key, project.uuid(), file));
}
indexIssues(issues.toArray(new IssueDoc[]{}));
IssueQuery.Builder query = IssueQuery.builder();
SearchResponse result = underTest.search(query.build(), new SearchOptions().setLimit(500));
assertThat(result.getHits().getHits()).hasSize(SearchOptions.MAX_PAGE_SIZE);
assertThat(result.getHits().getTotalHits().value).isEqualTo(11_000L);
assertThat(result.getHits().getTotalHits().relation).isEqualTo(Relation.EQUAL_TO);
}
@Test
public void search_nine_issues_with_same_creation_date_sorted_by_creation_date_order_is_sorted_also_by_key() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
List<IssueDoc> issues = new ArrayList<>();
// we are adding issues in reverse order to see if the sort is actually doing anything
for (int i = 9; i >= 1; i--) {
String key = "I" + i;
issues.add(newDoc(key, project.uuid(), file));
}
indexIssues(issues.toArray(new IssueDoc[]{}));
IssueQuery.Builder query = IssueQuery.builder().asc(true);
SearchResponse result = underTest.search(query.sort(IssueQuery.SORT_BY_CREATION_DATE).build(), new SearchOptions());
SearchHit[] hits = result.getHits().getHits();
for (int i = 1; i <= 9; i++) {
assertThat(hits[i - 1].getId()).isEqualTo("I" + i);
}
}
@Test
public void search_nine_issues_5_times_with_same_creation_date_sorted_by_creation_date_returned_issues_same_order() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
List<IssueDoc> issues = new ArrayList<>();
// we are adding issues in reverse order to see if the sort is actually doing anything
for (int i = 9; i >= 1; i--) {
String key = "I" + i;
issues.add(newDoc(key, project.uuid(), file));
}
indexIssues(issues.toArray(new IssueDoc[]{}));
IssueQuery.Builder query = IssueQuery.builder().asc(true);
SearchResponse result = underTest.search(query.sort(IssueQuery.SORT_BY_CREATION_DATE).build(), new SearchOptions());
SearchHit[] originalHits = result.getHits().getHits();
for (int i = 0; i < 4; i++) {
result = underTest.search(query.sort(IssueQuery.SORT_BY_CREATION_DATE).build(), new SearchOptions());
for (int j = 0; j < originalHits.length; j++) {
SearchHit[] hits = result.getHits().getHits();
assertThat(originalHits[j].getId()).isEqualTo(hits[j].getId());
}
}
}
@Test
public void authorized_issues_on_groups() {
ComponentDto project1 = newPrivateProjectDto();
ComponentDto project2 = newPrivateProjectDto();
ComponentDto project3 = newPrivateProjectDto();
ComponentDto file1 = newFileDto(project1);
ComponentDto file2 = newFileDto(project2);
ComponentDto file3 = newFileDto(project3);
GroupDto group1 = newGroupDto();
GroupDto group2 = newGroupDto();
// project1 can be seen by group1
indexIssue(newDoc("I1", project1.uuid(), file1));
authorizationIndexer.allowOnlyGroup(project1, group1);
// project2 can be seen by group2
indexIssue(newDoc("I2", project2.uuid(), file2));
authorizationIndexer.allowOnlyGroup(project2, group2);
// project3 can be seen by nobody but root
indexIssue(newDoc("I3", project3.uuid(), file3));
userSessionRule.logIn().setGroups(group1);
assertThatSearchReturnsOnly(IssueQuery.builder(), "I1");
userSessionRule.logIn().setGroups(group2);
assertThatSearchReturnsOnly(IssueQuery.builder(), "I2");
userSessionRule.logIn().setGroups(group1, group2);
assertThatSearchReturnsOnly(IssueQuery.builder(), "I1", "I2");
GroupDto otherGroup = newGroupDto();
userSessionRule.logIn().setGroups(otherGroup);
assertThatSearchReturnsEmpty(IssueQuery.builder());
userSessionRule.logIn().setGroups(group1, group2);
assertThatSearchReturnsEmpty(IssueQuery.builder().projectUuids(singletonList(project3.uuid())));
}
@Test
public void authorized_issues_on_user() {
ComponentDto project1 = newPrivateProjectDto();
ComponentDto project2 = newPrivateProjectDto();
ComponentDto project3 = newPrivateProjectDto();
ComponentDto file1 = newFileDto(project1);
ComponentDto file2 = newFileDto(project2);
ComponentDto file3 = newFileDto(project3);
UserDto user1 = newUserDto();
UserDto user2 = newUserDto();
// project1 can be seen by john, project2 by max, project3 cannot be seen by anyone
indexIssue(newDoc("I1", project1.uuid(), file1));
authorizationIndexer.allowOnlyUser(project1, user1);
indexIssue(newDoc("I2", project2.uuid(), file2));
authorizationIndexer.allowOnlyUser(project2, user2);
indexIssue(newDoc("I3", project3.uuid(), file3));
userSessionRule.logIn(user1);
assertThatSearchReturnsOnly(IssueQuery.builder(), "I1");
assertThatSearchReturnsEmpty(IssueQuery.builder().projectUuids(singletonList(project3.getKey())));
userSessionRule.logIn(user2);
assertThatSearchReturnsOnly(IssueQuery.builder(), "I2");
// another user
userSessionRule.logIn(newUserDto());
assertThatSearchReturnsEmpty(IssueQuery.builder());
}
@Test
public void list_tags() {
RuleDto r1 = db.rules().insert();
RuleDto r2 = db.rules().insert();
ruleIndexer.commitAndIndex(db.getSession(), asList(r1.getUuid(), r2.getUuid()));
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
indexIssues(
newDoc("I42", project.uuid(), file).setRuleUuid(r1.getUuid()).setTags(of("another")),
newDoc("I1", project.uuid(), file).setRuleUuid(r1.getUuid()).setTags(of("convention", "java8", "bug")),
newDoc("I2", project.uuid(), file).setRuleUuid(r1.getUuid()).setTags(of("convention", "bug")),
newDoc("I3", project.uuid(), file).setRuleUuid(r2.getUuid()),
newDoc("I4", project.uuid(), file).setRuleUuid(r1.getUuid()).setTags(of("convention")));
assertThat(underTest.searchTags(IssueQuery.builder().build(), null, 100)).containsExactlyInAnyOrder("convention", "java8", "bug", "another");
assertThat(underTest.searchTags(IssueQuery.builder().build(), null, 2)).containsOnly("another", "bug");
assertThat(underTest.searchTags(IssueQuery.builder().build(), "vent", 100)).containsOnly("convention");
assertThat(underTest.searchTags(IssueQuery.builder().build(), null, 1)).containsOnly("another");
assertThat(underTest.searchTags(IssueQuery.builder().build(), "invalidRegexp[", 100)).isEmpty();
}
@Test
public void list_authors() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("issue1", project).setAuthorLogin("luke.skywalker"),
newDocForProject("issue2", project).setAuthorLogin("luke@skywalker.name"),
newDocForProject("issue3", project).setAuthorLogin(null),
newDocForProject("issue4", project).setAuthorLogin("anakin@skywalker.name"));
IssueQuery query = IssueQuery.builder().build();
assertThat(underTest.searchAuthors(query, null, 5)).containsExactly("anakin@skywalker.name", "luke.skywalker", "luke@skywalker.name");
assertThat(underTest.searchAuthors(query, null, 2)).containsExactly("anakin@skywalker.name", "luke.skywalker");
assertThat(underTest.searchAuthors(query, "uke", 5)).containsExactly("luke.skywalker", "luke@skywalker.name");
assertThat(underTest.searchAuthors(query, null, 1)).containsExactly("anakin@skywalker.name");
assertThat(underTest.searchAuthors(query, null, Integer.MAX_VALUE)).containsExactly("anakin@skywalker.name", "luke.skywalker", "luke@skywalker.name");
}
@Test
public void list_authors_escapes_regexp_special_characters() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("issue1", project).setAuthorLogin("name++"));
IssueQuery query = IssueQuery.builder().build();
assertThat(underTest.searchAuthors(query, "invalidRegexp[", 5)).isEmpty();
assertThat(underTest.searchAuthors(query, "nam+", 5)).isEmpty();
assertThat(underTest.searchAuthors(query, "name+", 5)).containsExactly("name++");
assertThat(underTest.searchAuthors(query, ".*", 5)).isEmpty();
}
@Test
public void countTags() {
ComponentDto project = newPrivateProjectDto();
indexIssues(
newDocForProject("issue1", project).setTags(ImmutableSet.of("convention", "java8", "bug")),
newDocForProject("issue2", project).setTags(ImmutableSet.of("convention", "bug")),
newDocForProject("issue3", project).setTags(emptyList()),
newDocForProject("issue4", project).setTags(ImmutableSet.of("convention", "java8", "bug")).setResolution(Issue.RESOLUTION_FIXED),
newDocForProject("issue5", project).setTags(ImmutableSet.of("convention")));
assertThat(underTest.countTags(projectQuery(project.uuid()), 5)).containsOnly(entry("convention", 3L), entry("bug", 2L), entry("java8", 1L));
assertThat(underTest.countTags(projectQuery(project.uuid()), 2)).contains(entry("convention", 3L), entry("bug", 2L)).doesNotContainEntry("java8", 1L);
assertThat(underTest.countTags(projectQuery("other"), 10)).isEmpty();
}
private IssueQuery projectQuery(String projectUuid) {
return IssueQuery.builder().projectUuids(singletonList(projectUuid)).resolved(false).build();
}
private void indexIssue(IssueDoc issue) {
issueIndexer.index(Iterators.singletonIterator(issue));
}
}
| 13,726 | 44.909699 | 154 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexTestCommon.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.issue.index;
import java.util.Arrays;
import java.util.List;
import org.elasticsearch.search.SearchHit;
import org.junit.Rule;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.permission.index.IndexPermissions;
import org.sonar.server.permission.index.PermissionIndexerTester;
import org.sonar.server.permission.index.WebAuthorizationTypeSupport;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.view.index.ViewIndexer;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static java.util.TimeZone.getTimeZone;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.sonar.api.resources.Qualifiers.PROJECT;
public class IssueIndexTestCommon {
@Rule
public EsTester es = EsTester.create();
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
protected final System2 system2 = new TestSystem2().setNow(1_500_000_000_000L).setDefaultTimeZone(getTimeZone("GMT-01:00"));
@Rule
public DbTester db = DbTester.create(system2);
private final AsyncIssueIndexing asyncIssueIndexing = mock(AsyncIssueIndexing.class);
protected final IssueIndexer issueIndexer = new IssueIndexer(es.client(), db.getDbClient(), new IssueIteratorFactory(db.getDbClient()), asyncIssueIndexing);
protected final RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient());
protected final PermissionIndexerTester authorizationIndexer = new PermissionIndexerTester(es, issueIndexer);
protected final ViewIndexer viewIndexer = new ViewIndexer(db.getDbClient(), es.client());
protected final IssueIndex underTest = new IssueIndex(es.client(), system2, userSessionRule, new WebAuthorizationTypeSupport(userSessionRule));
/**
* Execute the search request and return the document ids of results.
*/
protected List<String> searchAndReturnKeys(IssueQuery.Builder query) {
return Arrays.stream(underTest.search(query.build(), new SearchOptions()).getHits().getHits())
.map(SearchHit::getId)
.toList();
}
protected void assertThatSearchReturnsOnly(IssueQuery.Builder query, String... expectedIssueKeys) {
List<String> keys = searchAndReturnKeys(query);
assertThat(keys).containsExactlyInAnyOrder(expectedIssueKeys);
}
protected void assertThatSearchReturnsEmpty(IssueQuery.Builder query) {
List<String> keys = searchAndReturnKeys(query);
assertThat(keys).isEmpty();
}
protected void indexIssues(IssueDoc... issues) {
issueIndexer.index(asList(issues).iterator());
authorizationIndexer.allow(stream(issues).map(issue -> new IndexPermissions(issue.projectUuid(), PROJECT).allowAnyone()).collect(toList()));
}
}
| 3,851 | 42.280899 | 158 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueQueryFactoryTest.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.issue.index;
import java.time.Clock;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ProjectData;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.rule.RuleDbTester;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.SearchRequest;
import org.sonar.server.tester.UserSessionRule;
import static java.util.Arrays.asList;
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.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.measures.CoreMetrics.ANALYSIS_FROM_SONARQUBE_9_4_KEY;
import static org.sonar.api.resources.Qualifiers.APP;
import static org.sonar.api.utils.DateUtils.addDays;
import static org.sonar.api.utils.DateUtils.parseDateTime;
import static org.sonar.api.web.UserRole.USER;
import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
import static org.sonar.db.component.ComponentTesting.newDirectory;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.component.ComponentTesting.newProjectCopy;
import static org.sonar.db.component.ComponentTesting.newSubPortfolio;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH;
import static org.sonar.db.rule.RuleTesting.newRule;
public class IssueQueryFactoryTest {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
@Rule
public LogTester logTester = new LogTester();
private final RuleDbTester ruleDbTester = new RuleDbTester(db);
private final Clock clock = mock(Clock.class);
private final IssueQueryFactory underTest = new IssueQueryFactory(db.getDbClient(), clock, userSession);
@Test
public void create_from_parameters() {
String ruleAdHocName = "New Name";
UserDto user = db.users().insertUser(u -> u.setLogin("joanna"));
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto project = projectData.getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
RuleDto rule1 = ruleDbTester.insert(r -> r.setAdHocName(ruleAdHocName));
RuleDto rule2 = ruleDbTester.insert(r -> r.setAdHocName(ruleAdHocName));
newRule(RuleKey.of("findbugs", "NullReference"));
SearchRequest request = new SearchRequest()
.setIssues(asList("anIssueKey"))
.setSeverities(asList("MAJOR", "MINOR"))
.setStatuses(asList("CLOSED"))
.setResolutions(asList("FALSE-POSITIVE"))
.setResolved(true)
.setProjectKeys(asList(project.getKey()))
.setDirectories(asList("aDirPath"))
.setFiles(asList(file.uuid()))
.setAssigneesUuid(asList(user.getUuid()))
.setScopes(asList("MAIN", "TEST"))
.setLanguages(asList("xoo"))
.setTags(asList("tag1", "tag2"))
.setAssigned(true)
.setCreatedAfter("2013-04-16T09:08:24+0200")
.setCreatedBefore("2013-04-17T09:08:24+0200")
.setRules(asList(rule1.getKey().toString(), rule2.getKey().toString()))
.setSort("CREATION_DATE")
.setAsc(true)
.setCodeVariants(asList("variant1", "variant2"));
IssueQuery query = underTest.create(request);
assertThat(query.issueKeys()).containsOnly("anIssueKey");
assertThat(query.severities()).containsOnly("MAJOR", "MINOR");
assertThat(query.statuses()).containsOnly("CLOSED");
assertThat(query.resolutions()).containsOnly("FALSE-POSITIVE");
assertThat(query.resolved()).isTrue();
assertThat(query.projectUuids()).containsOnly(projectData.projectUuid());
assertThat(query.files()).containsOnly(file.uuid());
assertThat(query.assignees()).containsOnly(user.getUuid());
assertThat(query.scopes()).containsOnly("TEST", "MAIN");
assertThat(query.languages()).containsOnly("xoo");
assertThat(query.tags()).containsOnly("tag1", "tag2");
assertThat(query.onComponentOnly()).isFalse();
assertThat(query.assigned()).isTrue();
assertThat(query.rules()).hasSize(2);
assertThat(query.ruleUuids()).hasSize(2);
assertThat(query.directories()).containsOnly("aDirPath");
assertThat(query.createdAfter().date()).isEqualTo(parseDateTime("2013-04-16T09:08:24+0200"));
assertThat(query.createdAfter().inclusive()).isTrue();
assertThat(query.createdBefore()).isEqualTo(parseDateTime("2013-04-17T09:08:24+0200"));
assertThat(query.sort()).isEqualTo(IssueQuery.SORT_BY_CREATION_DATE);
assertThat(query.asc()).isTrue();
assertThat(query.codeVariants()).containsOnly("variant1", "variant2");
}
@Test
public void create_with_rule_key_that_does_not_exist_in_the_db() {
db.users().insertUser(u -> u.setLogin("joanna"));
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
db.components().insertComponent(newFileDto(project));
newRule(RuleKey.of("findbugs", "NullReference"));
SearchRequest request = new SearchRequest()
.setRules(asList("unknown:key1", "unknown:key2"));
IssueQuery query = underTest.create(request);
assertThat(query.rules()).isEmpty();
assertThat(query.ruleUuids()).containsExactly("non-existing-uuid");
}
@Test
public void in_new_code_period_start_date_is_exclusive() {
long newCodePeriodStart = addDays(new Date(), -14).getTime();
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
SnapshotDto analysis = db.components().insertSnapshot(project, s -> s.setPeriodDate(newCodePeriodStart));
SearchRequest request = new SearchRequest()
.setComponentUuids(Collections.singletonList(file.uuid()))
.setOnComponentOnly(true)
.setInNewCodePeriod(true);
IssueQuery query = underTest.create(request);
assertThat(query.componentUuids()).containsOnly(file.uuid());
assertThat(query.createdAfter().date()).isEqualTo(new Date(newCodePeriodStart));
assertThat(query.createdAfter().inclusive()).isFalse();
assertThat(query.newCodeOnReference()).isNull();
}
@Test
public void new_code_period_does_not_rely_on_date_for_reference_branch_with_analysis_after_sonarqube_94() {
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
db.components().insertSnapshot(project, s -> s.setPeriodMode(REFERENCE_BRANCH.name())
.setPeriodParam("master"));
MetricDto analysisMetric = db.measures().insertMetric(m -> m.setKey(ANALYSIS_FROM_SONARQUBE_9_4_KEY));
db.measures().insertLiveMeasure(project, analysisMetric, measure -> measure.setData("true"));
SearchRequest request = new SearchRequest()
.setComponentUuids(Collections.singletonList(file.uuid()))
.setOnComponentOnly(true)
.setInNewCodePeriod(true);
IssueQuery query = underTest.create(request);
assertThat(query.componentUuids()).containsOnly(file.uuid());
assertThat(query.newCodeOnReference()).isTrue();
assertThat(query.createdAfter()).isNull();
}
@Test
public void dates_are_inclusive() {
when(clock.getZone()).thenReturn(ZoneId.of("Europe/Paris"));
SearchRequest request = new SearchRequest()
.setCreatedAfter("2013-04-16")
.setCreatedBefore("2013-04-17");
IssueQuery query = underTest.create(request);
assertThat(query.createdAfter().date()).isEqualTo(parseDateTime("2013-04-16T00:00:00+0200"));
assertThat(query.createdAfter().inclusive()).isTrue();
assertThat(query.createdBefore()).isEqualTo(parseDateTime("2013-04-18T00:00:00+0200"));
}
@Test
public void creation_date_support_localdate() {
when(clock.getZone()).thenReturn(ZoneId.of("Europe/Paris"));
SearchRequest request = new SearchRequest()
.setCreatedAt("2013-04-16");
IssueQuery query = underTest.create(request);
assertThat(query.createdAt()).isEqualTo(parseDateTime("2013-04-16T00:00:00+0200"));
}
@Test
public void use_provided_timezone_to_parse_createdAfter() {
SearchRequest request = new SearchRequest()
.setCreatedAfter("2020-04-16")
.setTimeZone("Australia/Sydney");
IssueQuery query = underTest.create(request);
assertThat(query.createdAfter().date()).isEqualTo(parseDateTime("2020-04-16T00:00:00+1000"));
}
@Test
public void use_provided_timezone_to_parse_createdBefore() {
SearchRequest request = new SearchRequest()
.setCreatedBefore("2020-04-16")
.setTimeZone("Europe/Moscow");
IssueQuery query = underTest.create(request);
assertThat(query.createdBefore()).isEqualTo(parseDateTime("2020-04-17T00:00:00+0300"));
}
@Test
public void creation_date_support_zoneddatetime() {
SearchRequest request = new SearchRequest()
.setCreatedAt("2013-04-16T09:08:24+0200");
IssueQuery query = underTest.create(request);
assertThat(query.createdAt()).isEqualTo(parseDateTime("2013-04-16T09:08:24+0200"));
}
@Test
public void add_unknown_when_no_component_found() {
SearchRequest request = new SearchRequest()
.setComponentKeys(asList("does_not_exist"));
IssueQuery query = underTest.create(request);
assertThat(query.componentUuids()).containsOnly("<UNKNOWN>");
}
@Test
public void query_without_any_parameter() {
SearchRequest request = new SearchRequest();
IssueQuery query = underTest.create(request);
assertThat(query.componentUuids()).isEmpty();
assertThat(query.projectUuids()).isEmpty();
assertThat(query.directories()).isEmpty();
assertThat(query.files()).isEmpty();
assertThat(query.viewUuids()).isEmpty();
assertThat(query.branchUuid()).isNull();
}
@Test
public void fail_if_components_and_components_uuid_params_are_set_at_the_same_time() {
SearchRequest request = new SearchRequest()
.setComponentKeys(singletonList("foo"))
.setComponentUuids(singletonList("bar"));
assertThatThrownBy(() -> underTest.create(request))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("At most one of the following parameters can be provided: componentKeys and componentUuids");
}
@Test
public void timeZone_ifZoneFromQueryIsUnknown_fallbacksToClockZone() {
SearchRequest request = new SearchRequest().setTimeZone("Poitou-Charentes");
when(clock.getZone()).thenReturn(ZoneId.systemDefault());
IssueQuery issueQuery = underTest.create(request);
assertThat(issueQuery.timeZone()).isEqualTo(clock.getZone());
assertThat(logTester.logs()).containsOnly("TimeZone 'Poitou-Charentes' cannot be parsed as a valid zone ID");
}
@Test
public void param_componentUuids_enables_search_in_view_tree_if_user_has_permission_on_view() {
ComponentDto view = db.components().insertPublicPortfolio();
SearchRequest request = new SearchRequest()
.setComponentUuids(singletonList(view.uuid()));
userSession.registerPortfolios(view);
IssueQuery query = underTest.create(request);
assertThat(query.viewUuids()).containsOnly(view.uuid());
assertThat(query.onComponentOnly()).isFalse();
}
@Test
public void application_search_project_issues() {
ProjectData projectData1 = db.components().insertPublicProject();
ComponentDto project1 = projectData1.getMainBranchComponent();
ProjectData projectData2 = db.components().insertPublicProject();
ComponentDto project2 = projectData2.getMainBranchComponent();
ProjectData applicationData = db.components().insertPublicApplication();
ComponentDto applicationMainBranch = applicationData.getMainBranchComponent();
db.components().insertComponents(newProjectCopy("PC1", project1, applicationMainBranch));
db.components().insertComponents(newProjectCopy("PC2", project2, applicationMainBranch));
userSession.registerApplication(applicationData.getProjectDto())
.registerProjects(projectData1.getProjectDto(), projectData2.getProjectDto())
.registerBranches(applicationData.getMainBranchDto());
IssueQuery result = underTest.create(new SearchRequest().setComponentUuids(singletonList(applicationMainBranch.uuid())));
assertThat(result.viewUuids()).containsExactlyInAnyOrder(applicationMainBranch.uuid());
}
@Test
public void application_search_project_issues_returns_empty_if_user_cannot_access_child_projects() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto application = db.components().insertPublicApplication().getMainBranchComponent();
db.components().insertComponents(newProjectCopy("PC1", project1, application));
db.components().insertComponents(newProjectCopy("PC2", project2, application));
IssueQuery result = underTest.create(new SearchRequest().setComponentUuids(singletonList(application.uuid())));
assertThat(result.viewUuids()).containsOnly("<UNKNOWN>");
}
@Test
public void application_search_project_issues_in_new_code_with_and_without_analysis_after_sonarqube_94() {
Date now = new Date();
when(clock.millis()).thenReturn(now.getTime());
ProjectData projectData1 = db.components().insertPublicProject();
ComponentDto project1 = projectData1.getMainBranchComponent();
SnapshotDto analysis1 = db.components().insertSnapshot(project1, s -> s.setPeriodDate(addDays(now, -14).getTime()));
ProjectData projectData2 = db.components().insertPublicProject();
ComponentDto project2 = projectData2.getMainBranchComponent();
db.components().insertSnapshot(project2, s -> s.setPeriodDate(null));
ProjectData projectData3 = db.components().insertPublicProject();
ComponentDto project3 = projectData3.getMainBranchComponent();
ProjectData projectData4 = db.components().insertPublicProject();
ComponentDto project4 = projectData4.getMainBranchComponent();
SnapshotDto analysis2 = db.components().insertSnapshot(project4,
s -> s.setPeriodMode(REFERENCE_BRANCH.name()).setPeriodParam("master"));
ProjectData applicationData = db.components().insertPublicApplication();
ComponentDto application = applicationData.getMainBranchComponent();
MetricDto analysisMetric = db.measures().insertMetric(m -> m.setKey(ANALYSIS_FROM_SONARQUBE_9_4_KEY));
db.measures().insertLiveMeasure(project4, analysisMetric, measure -> measure.setData("true"));
db.components().insertComponents(newProjectCopy("PC1", project1, application));
db.components().insertComponents(newProjectCopy("PC2", project2, application));
db.components().insertComponents(newProjectCopy("PC3", project3, application));
db.components().insertComponents(newProjectCopy("PC4", project4, application));
userSession.registerApplication(applicationData.getProjectDto())
.registerBranches(applicationData.getMainBranchDto());
userSession.registerProjects(projectData1.getProjectDto(), projectData2.getProjectDto(), projectData3.getProjectDto(), projectData4.getProjectDto());
IssueQuery result = underTest.create(new SearchRequest()
.setComponentUuids(singletonList(application.uuid()))
.setInNewCodePeriod(true));
assertThat(result.createdAfterByProjectUuids()).hasSize(1);
assertThat(result.createdAfterByProjectUuids().entrySet()).extracting(Map.Entry::getKey, e -> e.getValue().date(), e -> e.getValue().inclusive()).containsOnly(
tuple(project1.uuid(), new Date(analysis1.getPeriodDate()), false));
assertThat(result.newCodeOnReferenceByProjectUuids()).hasSize(1);
assertThat(result.newCodeOnReferenceByProjectUuids()).containsOnly(project4.uuid());
assertThat(result.viewUuids()).containsExactlyInAnyOrder(application.uuid());
}
@Test
public void return_empty_results_if_not_allowed_to_search_for_subview() {
ComponentDto view = db.components().insertPrivatePortfolio();
ComponentDto subView = db.components().insertComponent(newSubPortfolio(view));
SearchRequest request = new SearchRequest()
.setComponentUuids(singletonList(subView.uuid()));
IssueQuery query = underTest.create(request);
assertThat(query.viewUuids()).containsOnly("<UNKNOWN>");
}
@Test
public void param_componentUuids_enables_search_on_project_tree_by_default() {
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
SearchRequest request = new SearchRequest()
.setComponentUuids(asList(mainBranch.uuid()));
IssueQuery query = underTest.create(request);
assertThat(query.projectUuids()).containsExactly(projectData.projectUuid());
assertThat(query.onComponentOnly()).isFalse();
}
@Test
public void onComponentOnly_restricts_search_to_specified_componentKeys() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
SearchRequest request = new SearchRequest()
.setComponentKeys(asList(project.getKey()))
.setOnComponentOnly(true);
IssueQuery query = underTest.create(request);
assertThat(query.projectUuids()).isEmpty();
assertThat(query.componentUuids()).containsExactly(project.uuid());
assertThat(query.onComponentOnly()).isTrue();
}
@Test
public void param_componentUuids_enables_search_in_directory_tree() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto dir = db.components().insertComponent(newDirectory(project, "src/main/java/foo"));
SearchRequest request = new SearchRequest()
.setComponentUuids(asList(dir.uuid()));
IssueQuery query = underTest.create(request);
assertThat(query.directories()).containsOnly(dir.path());
assertThat(query.onComponentOnly()).isFalse();
}
@Test
public void param_componentUuids_enables_search_by_file() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
SearchRequest request = new SearchRequest()
.setComponentUuids(asList(file.uuid()));
IssueQuery query = underTest.create(request);
assertThat(query.componentUuids()).containsExactly(file.uuid());
}
@Test
public void param_componentUuids_enables_search_by_test_file() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project).setQualifier(Qualifiers.UNIT_TEST_FILE));
SearchRequest request = new SearchRequest()
.setComponentUuids(asList(file.uuid()));
IssueQuery query = underTest.create(request);
assertThat(query.componentUuids()).containsExactly(file.uuid());
}
@Test
public void search_issue_from_branch() {
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
String branchName = randomAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName));
assertThat(underTest.create(new SearchRequest()
.setProjectKeys(singletonList(branch.getKey()))
.setBranch(branchName)))
.extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch)
.containsOnly(branch.uuid(), singletonList(projectData.projectUuid()), false);
assertThat(underTest.create(new SearchRequest()
.setComponentKeys(singletonList(branch.getKey()))
.setBranch(branchName)))
.extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch)
.containsOnly(branch.uuid(), singletonList(projectData.projectUuid()), false);
}
@Test
public void search_file_issue_from_branch() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
String branchName = randomAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
assertThat(underTest.create(new SearchRequest()
.setComponentKeys(singletonList(file.getKey()))
.setBranch(branchName)))
.extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.componentUuids()), IssueQuery::isMainBranch)
.containsOnly(branch.uuid(), singletonList(file.uuid()), false);
assertThat(underTest.create(new SearchRequest()
.setComponentKeys(singletonList(branch.getKey()))
.setFiles(singletonList(file.path()))
.setBranch(branchName)))
.extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.files()), IssueQuery::isMainBranch)
.containsOnly(branch.uuid(), singletonList(file.path()), false);
assertThat(underTest.create(new SearchRequest()
.setProjectKeys(singletonList(branch.getKey()))
.setFiles(singletonList(file.path()))
.setBranch(branchName)))
.extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.files()), IssueQuery::isMainBranch)
.containsOnly(branch.uuid(), singletonList(file.path()), false);
}
@Test
public void search_issue_on_component_only_from_branch() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
String branchName = randomAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
assertThat(underTest.create(new SearchRequest()
.setComponentKeys(singletonList(file.getKey()))
.setBranch(branchName)
.setOnComponentOnly(true)))
.extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.componentUuids()), IssueQuery::isMainBranch)
.containsOnly(branch.uuid(), singletonList(file.uuid()), false);
}
@Test
public void search_issues_from_main_branch() {
ProjectData projectData = db.components().insertPublicProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
db.components().insertProjectBranch(mainBranch);
assertThat(underTest.create(new SearchRequest()
.setProjectKeys(singletonList(projectData.projectKey()))
.setBranch(DEFAULT_MAIN_BRANCH_NAME)))
.extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch)
.containsOnly(mainBranch.uuid(), singletonList(projectData.projectUuid()), true);
assertThat(underTest.create(new SearchRequest()
.setComponentKeys(singletonList(mainBranch.getKey()))
.setBranch(DEFAULT_MAIN_BRANCH_NAME)))
.extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch)
.containsOnly(mainBranch.uuid(), singletonList(projectData.projectUuid()), true);
}
@Test
public void search_by_application_key() {
ProjectData applicationData = db.components().insertPrivateApplication();
ComponentDto application = applicationData.getMainBranchComponent();
ProjectData projectData1 = db.components().insertPrivateProject();
ComponentDto project1 = projectData1.getMainBranchComponent();
ProjectData projectData2 = db.components().insertPrivateProject();
ComponentDto project2 = projectData2.getMainBranchComponent();
db.components().insertComponents(newProjectCopy(project1, application));
db.components().insertComponents(newProjectCopy(project2, application));
userSession.registerApplication(applicationData.getProjectDto())
.registerProjects(projectData1.getProjectDto(), projectData2.getProjectDto())
.addProjectPermission(USER, applicationData.getProjectDto())
.addProjectPermission(USER, projectData1.getProjectDto())
.addProjectPermission(USER, projectData2.getProjectDto())
.registerBranches(applicationData.getMainBranchDto());
assertThat(underTest.create(new SearchRequest()
.setComponentKeys(singletonList(application.getKey())))
.viewUuids()).containsExactly(applicationData.getMainBranchComponent().uuid());
}
@Test
public void search_by_application_key_and_branch() {
ComponentDto application = db.components().insertPublicProject(c -> c.setQualifier(APP).setKey("app")).getMainBranchComponent();
String branchName1 = "app-branch1";
String branchName2 = "app-branch2";
ComponentDto applicationBranch1 = db.components().insertProjectBranch(application, a -> a.setKey(branchName1));
ComponentDto applicationBranch2 = db.components().insertProjectBranch(application, a -> a.setKey(branchName2));
ProjectData projectData1 = db.components().insertPrivateProject(p -> p.setKey("prj1"));
ComponentDto mainBranch1 = projectData1.getMainBranchComponent();
ComponentDto project1Branch1 = db.components().insertProjectBranch(mainBranch1);
db.components().insertComponent(newFileDto(project1Branch1, mainBranch1.uuid()));
ComponentDto project1Branch2 = db.components().insertProjectBranch(mainBranch1);
ComponentDto project2 = db.components().insertPrivateProject(p -> p.setKey("prj2")).getMainBranchComponent();
db.components().insertComponents(newProjectCopy(project1Branch1, applicationBranch1));
db.components().insertComponents(newProjectCopy(project2, applicationBranch1));
db.components().insertComponents(newProjectCopy(project1Branch2, applicationBranch2));
// Search on applicationBranch1
assertThat(underTest.create(new SearchRequest()
.setComponentKeys(singletonList(applicationBranch1.getKey()))
.setBranch(branchName1)))
.extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch)
.containsOnly(applicationBranch1.uuid(), Collections.emptyList(), false);
// Search on project1Branch1
assertThat(underTest.create(new SearchRequest()
.setComponentKeys(singletonList(applicationBranch1.getKey()))
.setProjectKeys(singletonList(mainBranch1.getKey()))
.setBranch(branchName1)))
.extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch)
.containsOnly(applicationBranch1.uuid(), singletonList(projectData1.projectUuid()), false);
}
@Test
public void fail_if_created_after_and_created_since_are_both_set() {
SearchRequest request = new SearchRequest()
.setCreatedAfter("2013-07-25T07:35:00+0100")
.setCreatedInLast("palap");
try {
underTest.create(request);
fail();
} catch (Exception e) {
assertThat(e).isInstanceOf(IllegalArgumentException.class).hasMessage("Parameters createdAfter and createdInLast cannot be set simultaneously");
}
}
@Test
public void set_created_after_from_created_since() {
Date now = parseDateTime("2013-07-25T07:35:00+0100");
when(clock.instant()).thenReturn(now.toInstant());
when(clock.getZone()).thenReturn(ZoneOffset.UTC);
SearchRequest request = new SearchRequest()
.setCreatedInLast("1y2m3w4d");
assertThat(underTest.create(request).createdAfter().date()).isEqualTo(parseDateTime("2012-04-30T07:35:00+0100"));
assertThat(underTest.create(request).createdAfter().inclusive()).isTrue();
}
@Test
public void fail_if_in_new_code_period_and_created_after_set_at_the_same_time() {
SearchRequest searchRequest = new SearchRequest()
.setInNewCodePeriod(true)
.setCreatedAfter("2013-07-25T07:35:00+0100");
assertThatThrownBy(() -> underTest.create(searchRequest))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Parameters 'createdAfter' and 'inNewCodePeriod' cannot be set simultaneously");
}
@Test
public void fail_if_in_new_code_period_and_created_in_last_set_at_the_same_time() {
SearchRequest searchRequest = new SearchRequest()
.setInNewCodePeriod(true)
.setCreatedInLast("1y2m3w4d");
assertThatThrownBy(() -> underTest.create(searchRequest))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Parameters 'createdInLast' and 'inNewCodePeriod' cannot be set simultaneously");
}
@Test
public void fail_if_no_component_provided_with_since_leak_period() {
assertThatThrownBy(() -> underTest.create(new SearchRequest().setInNewCodePeriod(true)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("One and only one component must be provided when searching in new code period");
}
@Test
public void fail_if_no_component_provided_with_in_new_code_period() {
SearchRequest searchRequest = new SearchRequest().setInNewCodePeriod(true);
assertThatThrownBy(() -> underTest.create(searchRequest))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("One and only one component must be provided when searching in new code period");
}
@Test
public void fail_if_several_components_provided_with_in_new_code_period() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
SearchRequest searchRequest = new SearchRequest()
.setInNewCodePeriod(true)
.setComponentKeys(asList(project1.getKey(), project2.getKey()));
assertThatThrownBy(() -> underTest.create(searchRequest))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("One and only one component must be provided when searching in new code period");
}
@Test
public void fail_if_date_is_not_formatted_correctly() {
assertThatThrownBy(() -> underTest.create(new SearchRequest()
.setCreatedAfter("unknown-date")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("'unknown-date' cannot be parsed as either a date or date+time");
}
}
| 31,602 | 45.270864 | 163 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueQueryTest.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.issue.index;
import com.google.common.collect.ImmutableMap;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.Severity;
import org.sonar.core.util.Uuids;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.issue.index.IssueQuery.PeriodStart;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
public class IssueQueryTest {
@Test
public void build_query() {
RuleDto rule = new RuleDto().setUuid(Uuids.createFast());
PeriodStart filterDate = new IssueQuery.PeriodStart(new Date(10_000_000_000L), false);
IssueQuery query = IssueQuery.builder()
.issueKeys(List.of("ABCDE"))
.severities(List.of(Severity.BLOCKER))
.statuses(List.of(Issue.STATUS_RESOLVED))
.resolutions(List.of(Issue.RESOLUTION_FALSE_POSITIVE))
.projectUuids(List.of("PROJECT"))
.componentUuids(List.of("org/struts/Action.java"))
.rules(List.of(rule))
.assigneeUuids(List.of("gargantua"))
.languages(List.of("xoo"))
.tags(List.of("tag1", "tag2"))
.types(List.of("RELIABILITY", "SECURITY"))
.sansTop25(List.of("insecure-interaction", "porous-defenses"))
.cwe(List.of("12", "125"))
.branchUuid("my_branch")
.createdAfterByProjectUuids(ImmutableMap.of("PROJECT", filterDate))
.assigned(true)
.createdAfter(new Date())
.createdBefore(new Date())
.createdAt(new Date())
.resolved(true)
.newCodeOnReference(true)
.newCodeOnReferenceByProjectUuids(List.of("PROJECT"))
.sort(IssueQuery.SORT_BY_CREATION_DATE)
.asc(true)
.codeVariants(List.of("codeVariant1", "codeVariant2"))
.build();
assertThat(query.issueKeys()).containsOnly("ABCDE");
assertThat(query.severities()).containsOnly(Severity.BLOCKER);
assertThat(query.statuses()).containsOnly(Issue.STATUS_RESOLVED);
assertThat(query.resolutions()).containsOnly(Issue.RESOLUTION_FALSE_POSITIVE);
assertThat(query.projectUuids()).containsOnly("PROJECT");
assertThat(query.componentUuids()).containsOnly("org/struts/Action.java");
assertThat(query.assignees()).containsOnly("gargantua");
assertThat(query.languages()).containsOnly("xoo");
assertThat(query.tags()).containsOnly("tag1", "tag2");
assertThat(query.types()).containsOnly("RELIABILITY", "SECURITY");
assertThat(query.sansTop25()).containsOnly("insecure-interaction", "porous-defenses");
assertThat(query.cwe()).containsOnly("12", "125");
assertThat(query.branchUuid()).isEqualTo("my_branch");
assertThat(query.createdAfterByProjectUuids()).containsOnly(entry("PROJECT", filterDate));
assertThat(query.assigned()).isTrue();
assertThat(query.rules()).containsOnly(rule);
assertThat(query.createdAfter()).isNotNull();
assertThat(query.createdBefore()).isNotNull();
assertThat(query.createdAt()).isNotNull();
assertThat(query.resolved()).isTrue();
assertThat(query.newCodeOnReference()).isTrue();
assertThat(query.newCodeOnReferenceByProjectUuids()).containsOnly("PROJECT");
assertThat(query.sort()).isEqualTo(IssueQuery.SORT_BY_CREATION_DATE);
assertThat(query.asc()).isTrue();
assertThat(query.codeVariants()).containsOnly("codeVariant1", "codeVariant2");
}
@Test
public void build_pci_dss_query() {
IssueQuery query = IssueQuery.builder()
.pciDss32(List.of("1.2.3", "3.2.1"))
.pciDss40(List.of("3.4.5", "5.6"))
.build();
assertThat(query.pciDss32()).containsOnly("1.2.3", "3.2.1");
assertThat(query.pciDss40()).containsOnly("3.4.5", "5.6");
}
@Test
public void build_owasp_asvs_query() {
IssueQuery query = IssueQuery.builder()
.owaspAsvs40(List.of("1.2.3", "3.2.1"))
.owaspAsvsLevel(2)
.build();
assertThat(query.owaspAsvs40()).containsOnly("1.2.3", "3.2.1");
assertThat(query.getOwaspAsvsLevel()).isPresent().hasValue(2);
}
@Test
public void build_owasp_query() {
IssueQuery query = IssueQuery.builder()
.owaspTop10(List.of("a1", "a2"))
.owaspTop10For2021(List.of("a3", "a4"))
.build();
assertThat(query.owaspTop10()).containsOnly("a1", "a2");
assertThat(query.owaspTop10For2021()).containsOnly("a3", "a4");
}
@Test
public void build_query_without_dates() {
IssueQuery query = IssueQuery.builder()
.issueKeys(List.of("ABCDE"))
.createdAfter(null)
.createdBefore(null)
.createdAt(null)
.build();
assertThat(query.issueKeys()).containsOnly("ABCDE");
assertThat(query.createdAfter()).isNull();
assertThat(query.createdBefore()).isNull();
assertThat(query.createdAt()).isNull();
}
@Test
public void throw_exception_if_sort_is_not_valid() {
try {
IssueQuery.builder()
.sort("UNKNOWN")
.build();
} catch (Exception e) {
assertThat(e).isInstanceOf(IllegalArgumentException.class).hasMessage("Bad sort field: UNKNOWN");
}
}
@Test
public void collection_params_should_not_be_null_but_empty() {
IssueQuery query = IssueQuery.builder()
.issueKeys(null)
.projectUuids(null)
.componentUuids(null)
.statuses(null)
.assigneeUuids(null)
.resolutions(null)
.rules(null)
.severities(null)
.languages(null)
.tags(null)
.types(null)
.owaspTop10(null)
.sansTop25(null)
.cwe(null)
.createdAfterByProjectUuids(null)
.build();
assertThat(query.issueKeys()).isEmpty();
assertThat(query.projectUuids()).isEmpty();
assertThat(query.componentUuids()).isEmpty();
assertThat(query.statuses()).isEmpty();
assertThat(query.assignees()).isEmpty();
assertThat(query.resolutions()).isEmpty();
assertThat(query.rules()).isEmpty();
assertThat(query.severities()).isEmpty();
assertThat(query.languages()).isEmpty();
assertThat(query.tags()).isEmpty();
assertThat(query.types()).isEmpty();
assertThat(query.owaspTop10()).isEmpty();
assertThat(query.sansTop25()).isEmpty();
assertThat(query.cwe()).isEmpty();
assertThat(query.createdAfterByProjectUuids()).isEmpty();
}
@Test
public void test_default_query() {
IssueQuery query = IssueQuery.builder().build();
assertThat(query.issueKeys()).isEmpty();
assertThat(query.projectUuids()).isEmpty();
assertThat(query.componentUuids()).isEmpty();
assertThat(query.statuses()).isEmpty();
assertThat(query.assignees()).isEmpty();
assertThat(query.resolutions()).isEmpty();
assertThat(query.rules()).isEmpty();
assertThat(query.severities()).isEmpty();
assertThat(query.languages()).isEmpty();
assertThat(query.tags()).isEmpty();
assertThat(query.types()).isEmpty();
assertThat(query.branchUuid()).isNull();
assertThat(query.assigned()).isNull();
assertThat(query.createdAfter()).isNull();
assertThat(query.createdBefore()).isNull();
assertThat(query.resolved()).isNull();
assertThat(query.sort()).isNull();
assertThat(query.createdAfterByProjectUuids()).isEmpty();
}
@Test
public void should_accept_null_sort() {
IssueQuery query = IssueQuery.builder().sort(null).build();
assertThat(query.sort()).isNull();
}
}
| 8,153 | 36.063636 | 103 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.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.measure.index;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.utils.System2;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.Facets;
import org.sonar.server.es.SearchIdResult;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion;
import org.sonar.server.permission.index.IndexPermissions;
import org.sonar.server.permission.index.PermissionIndexerTester;
import org.sonar.server.permission.index.WebAuthorizationTypeSupport;
import org.sonar.server.tester.UserSessionRule;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY;
import static org.sonar.api.measures.Metric.Level.ERROR;
import static org.sonar.api.measures.Metric.Level.OK;
import static org.sonar.api.measures.Metric.Level.WARN;
import static org.sonar.api.resources.Qualifiers.APP;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.db.user.GroupTesting.newGroupDto;
import static org.sonar.db.user.UserTesting.newUserDto;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_TAGS;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.TYPE_PROJECT_MEASURES;
import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.FILTER_QUALIFIER;
@RunWith(DataProviderRunner.class)
public class ProjectMeasuresIndexTest {
private static final String MAINTAINABILITY_RATING = "sqale_rating";
private static final String NEW_MAINTAINABILITY_RATING_KEY = "new_maintainability_rating";
private static final String RELIABILITY_RATING = "reliability_rating";
private static final String NEW_RELIABILITY_RATING = "new_reliability_rating";
private static final String SECURITY_RATING = "security_rating";
private static final String NEW_SECURITY_RATING = "new_security_rating";
private static final String SECURITY_REVIEW_RATING = "security_review_rating";
private static final String NEW_SECURITY_REVIEW_RATING = "new_security_review_rating";
private static final String SECURITY_HOTSPOTS_REVIEWED = "security_hotspots_reviewed";
private static final String NEW_SECURITY_HOTSPOTS_REVIEWED = "new_security_hotspots_reviewed";
private static final String COVERAGE = "coverage";
private static final String NEW_COVERAGE = "new_coverage";
private static final String DUPLICATION = "duplicated_lines_density";
private static final String NEW_DUPLICATION = "new_duplicated_lines_density";
private static final String NCLOC = "ncloc";
private static final String NEW_LINES = "new_lines";
private static final String LANGUAGES = "languages";
private static final ComponentDto PROJECT1 = ComponentTesting.newPrivateProjectDto().setUuid("Project-1").setName("Project 1").setKey("key-1");
private static final ComponentDto PROJECT2 = ComponentTesting.newPrivateProjectDto().setUuid("Project-2").setName("Project 2").setKey("key-2");
private static final ComponentDto PROJECT3 = ComponentTesting.newPrivateProjectDto().setUuid("Project-3").setName("Project 3").setKey("key-3");
private static final ComponentDto APP1 = ComponentTesting.newApplication().setUuid("App-1").setName("App 1").setKey("app-key-1");
private static final ComponentDto APP2 = ComponentTesting.newApplication().setUuid("App-2").setName("App 2").setKey("app-key-2");
private static final ComponentDto APP3 = ComponentTesting.newApplication().setUuid("App-3").setName("App 3").setKey("app-key-3");
private static final UserDto USER1 = newUserDto();
private static final UserDto USER2 = newUserDto();
private static final GroupDto GROUP1 = newGroupDto();
private static final GroupDto GROUP2 = newGroupDto();
@Rule
public EsTester es = EsTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@DataProvider
public static Object[][] rating_metric_keys() {
return new Object[][] {{MAINTAINABILITY_RATING}, {NEW_MAINTAINABILITY_RATING_KEY}, {RELIABILITY_RATING}, {NEW_RELIABILITY_RATING}, {SECURITY_RATING}, {NEW_SECURITY_RATING},
{SECURITY_REVIEW_RATING}, {NEW_SECURITY_REVIEW_RATING}};
}
private ProjectMeasuresIndexer projectMeasureIndexer = new ProjectMeasuresIndexer(null, es.client());
private PermissionIndexerTester authorizationIndexer = new PermissionIndexerTester(es, projectMeasureIndexer);
private ProjectMeasuresIndex underTest = new ProjectMeasuresIndex(es.client(), new WebAuthorizationTypeSupport(userSession), System2.INSTANCE);
@Test
public void return_empty_if_no_projects() {
assertNoResults(new ProjectMeasuresQuery());
}
@Test
public void default_sort_is_by_ascending_case_insensitive_name_then_by_key() {
ComponentDto windows = ComponentTesting.newPrivateProjectDto().setUuid("windows").setName("Windows").setKey("project1");
ComponentDto apachee = ComponentTesting.newPrivateProjectDto().setUuid("apachee").setName("apachee").setKey("project2");
ComponentDto apache1 = ComponentTesting.newPrivateProjectDto().setUuid("apache-1").setName("Apache").setKey("project3");
ComponentDto apache2 = ComponentTesting.newPrivateProjectDto().setUuid("apache-2").setName("Apache").setKey("project4");
index(newDoc(windows), newDoc(apachee), newDoc(apache1), newDoc(apache2));
assertResults(new ProjectMeasuresQuery(), apache1, apache2, apachee, windows);
}
@Test
public void sort_by_insensitive_name() {
ComponentDto windows = ComponentTesting.newPrivateProjectDto().setUuid("windows").setName("Windows");
ComponentDto apachee = ComponentTesting.newPrivateProjectDto().setUuid("apachee").setName("apachee");
ComponentDto apache = ComponentTesting.newPrivateProjectDto().setUuid("apache").setName("Apache");
index(newDoc(windows), newDoc(apachee), newDoc(apache));
assertResults(new ProjectMeasuresQuery().setSort("name").setAsc(true), apache, apachee, windows);
assertResults(new ProjectMeasuresQuery().setSort("name").setAsc(false), windows, apachee, apache);
}
@Test
public void sort_by_ncloc() {
index(
newDoc(PROJECT1, NCLOC, 15_000d),
newDoc(PROJECT2, NCLOC, 30_000d),
newDoc(PROJECT3, NCLOC, 1_000d));
assertResults(new ProjectMeasuresQuery().setSort("ncloc").setAsc(true), PROJECT3, PROJECT1, PROJECT2);
assertResults(new ProjectMeasuresQuery().setSort("ncloc").setAsc(false), PROJECT2, PROJECT1, PROJECT3);
}
@Test
public void sort_by_a_metric_then_by_name_then_by_key() {
ComponentDto windows = ComponentTesting.newPrivateProjectDto().setUuid("windows").setName("Windows").setKey("project1");
ComponentDto apachee = ComponentTesting.newPrivateProjectDto().setUuid("apachee").setName("apachee").setKey("project2");
ComponentDto apache1 = ComponentTesting.newPrivateProjectDto().setUuid("apache-1").setName("Apache").setKey("project3");
ComponentDto apache2 = ComponentTesting.newPrivateProjectDto().setUuid("apache-2").setName("Apache").setKey("project4");
index(
newDoc(windows, NCLOC, 10_000d),
newDoc(apachee, NCLOC, 5_000d),
newDoc(apache1, NCLOC, 5_000d),
newDoc(apache2, NCLOC, 5_000d));
assertResults(new ProjectMeasuresQuery().setSort("ncloc").setAsc(true), apache1, apache2, apachee, windows);
assertResults(new ProjectMeasuresQuery().setSort("ncloc").setAsc(false), windows, apache1, apache2, apachee);
}
@Test
public void sort_by_quality_gate_status() {
ComponentDto project4 = ComponentTesting.newPrivateProjectDto().setUuid("Project-4").setName("Project 4").setKey("key-4");
index(
newDoc(PROJECT1).setQualityGateStatus(OK.name()),
newDoc(PROJECT2).setQualityGateStatus(ERROR.name()),
newDoc(project4).setQualityGateStatus(OK.name()));
assertResults(new ProjectMeasuresQuery().setSort("alert_status").setAsc(true), PROJECT1, project4, PROJECT2);
assertResults(new ProjectMeasuresQuery().setSort("alert_status").setAsc(false), PROJECT2, PROJECT1, project4);
}
@Test
public void sort_by_quality_gate_status_then_by_name_then_by_key() {
ComponentDto windows = ComponentTesting.newPrivateProjectDto().setUuid("windows").setName("Windows").setKey("project1");
ComponentDto apachee = ComponentTesting.newPrivateProjectDto().setUuid("apachee").setName("apachee").setKey("project2");
ComponentDto apache1 = ComponentTesting.newPrivateProjectDto().setUuid("apache-1").setName("Apache").setKey("project3");
ComponentDto apache2 = ComponentTesting.newPrivateProjectDto().setUuid("apache-2").setName("Apache").setKey("project4");
index(
newDoc(windows).setQualityGateStatus(ERROR.name()),
newDoc(apachee).setQualityGateStatus(OK.name()),
newDoc(apache1).setQualityGateStatus(OK.name()),
newDoc(apache2).setQualityGateStatus(OK.name()));
assertResults(new ProjectMeasuresQuery().setSort("alert_status").setAsc(true), apache1, apache2, apachee, windows);
assertResults(new ProjectMeasuresQuery().setSort("alert_status").setAsc(false), windows, apache1, apache2, apachee);
}
@Test
public void paginate_results() {
IntStream.rangeClosed(1, 9)
.forEach(i -> index(newDoc(newPrivateProjectDto("P" + i))));
SearchIdResult<String> result = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().setPage(2, 3));
assertThat(result.getUuids()).containsExactly("P4", "P5", "P6");
assertThat(result.getTotal()).isEqualTo(9);
}
@Test
public void filter_with_lower_than() {
index(
newDoc(PROJECT1, COVERAGE, 79d, NCLOC, 10_000d),
newDoc(PROJECT2, COVERAGE, 80d, NCLOC, 10_000d),
newDoc(PROJECT3, COVERAGE, 81d, NCLOC, 10_000d));
ProjectMeasuresQuery query = new ProjectMeasuresQuery()
.addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 80d));
assertResults(query, PROJECT1);
}
@Test
public void filter_with_lower_than_or_equals() {
index(
newDoc(PROJECT1, COVERAGE, 79d, NCLOC, 10_000d),
newDoc(PROJECT2, COVERAGE, 80d, NCLOC, 10_000d),
newDoc(PROJECT3, COVERAGE, 81d, NCLOC, 10_000d));
ProjectMeasuresQuery query = new ProjectMeasuresQuery()
.addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LTE, 80d));
assertResults(query, PROJECT1, PROJECT2);
}
@Test
public void filter_with_greater_than() {
index(
newDoc(PROJECT1, COVERAGE, 80d, NCLOC, 30_000d),
newDoc(PROJECT2, COVERAGE, 80d, NCLOC, 30_001d),
newDoc(PROJECT3, COVERAGE, 80d, NCLOC, 30_001d));
ProjectMeasuresQuery query = new ProjectMeasuresQuery().addMetricCriterion(MetricCriterion.create(NCLOC, Operator.GT, 30_000d));
assertResults(query, PROJECT2, PROJECT3);
query = new ProjectMeasuresQuery().addMetricCriterion(MetricCriterion.create(NCLOC, Operator.GT, 100_000d));
assertNoResults(query);
}
@Test
public void filter_with_greater_than_or_equals() {
index(
newDoc(PROJECT1, COVERAGE, 80d, NCLOC, 30_000d),
newDoc(PROJECT2, COVERAGE, 80d, NCLOC, 30_001d),
newDoc(PROJECT3, COVERAGE, 80d, NCLOC, 30_001d));
ProjectMeasuresQuery query = new ProjectMeasuresQuery().addMetricCriterion(MetricCriterion.create(NCLOC, Operator.GTE, 30_001d));
assertResults(query, PROJECT2, PROJECT3);
query = new ProjectMeasuresQuery().addMetricCriterion(MetricCriterion.create(NCLOC, Operator.GTE, 100_000d));
assertNoResults(query);
}
@Test
public void filter_with_equals() {
index(
newDoc(PROJECT1, COVERAGE, 79d, NCLOC, 10_000d),
newDoc(PROJECT2, COVERAGE, 80d, NCLOC, 10_000d),
newDoc(PROJECT3, COVERAGE, 81d, NCLOC, 10_000d));
ProjectMeasuresQuery query = new ProjectMeasuresQuery()
.addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.EQ, 80d));
assertResults(query, PROJECT2);
}
@Test
public void filter_on_no_data_with_several_projects() {
index(
newDoc(PROJECT1, NCLOC, 1d),
newDoc(PROJECT2, DUPLICATION, 80d));
ProjectMeasuresQuery query = new ProjectMeasuresQuery()
.addMetricCriterion(MetricCriterion.createNoData(DUPLICATION));
assertResults(query, PROJECT1);
}
@Test
public void filter_on_no_data_should_not_return_projects_with_data_and_other_measures() {
ComponentDto project = ComponentTesting.newPrivateProjectDto();
index(newDoc(project, DUPLICATION, 80d, NCLOC, 1d));
ProjectMeasuresQuery query = new ProjectMeasuresQuery().addMetricCriterion(MetricCriterion.createNoData(DUPLICATION));
assertNoResults(query);
}
@Test
public void filter_on_no_data_should_not_return_projects_with_data() {
ComponentDto project = ComponentTesting.newPrivateProjectDto();
index(newDoc(project, DUPLICATION, 80d));
ProjectMeasuresQuery query = new ProjectMeasuresQuery().addMetricCriterion(MetricCriterion.createNoData(DUPLICATION));
assertNoResults(query);
}
@Test
public void filter_on_no_data_should_return_projects_with_no_data() {
ComponentDto project = ComponentTesting.newPrivateProjectDto();
index(newDoc(project, NCLOC, 1d));
ProjectMeasuresQuery query = new ProjectMeasuresQuery().addMetricCriterion(MetricCriterion.createNoData(DUPLICATION));
assertResults(query, project);
}
@Test
public void filter_on_several_metrics() {
index(
newDoc(PROJECT1, COVERAGE, 81d, NCLOC, 10_001d),
newDoc(PROJECT2, COVERAGE, 80d, NCLOC, 10_001d),
newDoc(PROJECT3, COVERAGE, 79d, NCLOC, 10_000d));
ProjectMeasuresQuery esQuery = new ProjectMeasuresQuery()
.addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LTE, 80d))
.addMetricCriterion(MetricCriterion.create(NCLOC, Operator.GT, 10_000d))
.addMetricCriterion(MetricCriterion.create(NCLOC, Operator.LT, 11_000d));
assertResults(esQuery, PROJECT2);
}
@Test
public void facet_security_hotspots_reviewed() {
index(
// 2 docs with no measure
newDocWithNoMeasure(),
newDocWithNoMeasure(),
// 3 docs < 30%
newDoc(SECURITY_HOTSPOTS_REVIEWED, 29),
newDoc(SECURITY_HOTSPOTS_REVIEWED, 28),
newDoc(SECURITY_HOTSPOTS_REVIEWED, 0),
// 2 docs with >=30% and <50%
newDoc(SECURITY_HOTSPOTS_REVIEWED, 30),
newDoc(SECURITY_HOTSPOTS_REVIEWED, 49),
// 4 docs with >=50% and <70%
newDoc(SECURITY_HOTSPOTS_REVIEWED, 50),
newDoc(SECURITY_HOTSPOTS_REVIEWED, 60),
newDoc(SECURITY_HOTSPOTS_REVIEWED, 61),
newDoc(SECURITY_HOTSPOTS_REVIEWED, 69),
// 2 docs with >=70% and <80%
newDoc(SECURITY_HOTSPOTS_REVIEWED, 70),
newDoc(SECURITY_HOTSPOTS_REVIEWED, 79),
// 5 docs with >= 80%
newDoc(SECURITY_HOTSPOTS_REVIEWED, 80),
newDoc(SECURITY_HOTSPOTS_REVIEWED, 90),
newDoc(SECURITY_HOTSPOTS_REVIEWED, 93),
newDoc(SECURITY_HOTSPOTS_REVIEWED, 99),
newDoc(SECURITY_HOTSPOTS_REVIEWED, 100));
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(SECURITY_HOTSPOTS_REVIEWED)).getFacets();
assertThat(facets.get(SECURITY_HOTSPOTS_REVIEWED)).containsExactly(
entry("*-30.0", 3L),
entry("30.0-50.0", 2L),
entry("50.0-70.0", 4L),
entry("70.0-80.0", 2L),
entry("80.0-*", 5L));
}
@Test
public void facet_new_security_hotspots_reviewed() {
index(
// 2 docs with no measure
newDocWithNoMeasure(),
newDocWithNoMeasure(),
// 3 docs < 30%
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 29),
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 28),
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 0),
// 2 docs with >=30% and <50%
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 30),
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 49),
// 4 docs with >=50% and <70%
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 50),
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 60),
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 61),
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 69),
// 2 docs with >=70% and <80%
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 70),
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 79),
// 5 docs with >= 80%
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 80),
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 90),
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 93),
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 99),
newDoc(NEW_SECURITY_HOTSPOTS_REVIEWED, 100));
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(NEW_SECURITY_HOTSPOTS_REVIEWED)).getFacets();
assertThat(facets.get(NEW_SECURITY_HOTSPOTS_REVIEWED)).containsExactly(
entry("*-30.0", 3L),
entry("30.0-50.0", 2L),
entry("50.0-70.0", 4L),
entry("70.0-80.0", 2L),
entry("80.0-*", 5L));
}
@Test
public void filter_on_quality_gate_status() {
index(
newDoc(PROJECT1).setQualityGateStatus(OK.name()),
newDoc(PROJECT2).setQualityGateStatus(OK.name()),
newDoc(PROJECT3).setQualityGateStatus(ERROR.name()));
ProjectMeasuresQuery query = new ProjectMeasuresQuery().setQualityGateStatus(OK);
assertResults(query, PROJECT1, PROJECT2);
}
@Test
public void filter_on_languages() {
ComponentDto project4 = ComponentTesting.newPrivateProjectDto().setUuid("Project-4").setName("Project 4").setKey("key-4");
index(
newDoc(PROJECT1).setLanguages(singletonList("java")),
newDoc(PROJECT2).setLanguages(singletonList("xoo")),
newDoc(PROJECT3).setLanguages(singletonList("xoo")),
newDoc(project4).setLanguages(asList("<null>", "java", "xoo")));
assertResults(new ProjectMeasuresQuery().setLanguages(newHashSet("java", "xoo")), PROJECT1, PROJECT2, PROJECT3, project4);
assertResults(new ProjectMeasuresQuery().setLanguages(newHashSet("java")), PROJECT1, project4);
assertResults(new ProjectMeasuresQuery().setLanguages(newHashSet("unknown")));
}
@Test
public void filter_on_query_text() {
ComponentDto windows = ComponentTesting.newPrivateProjectDto().setUuid("windows").setName("Windows").setKey("project1");
ComponentDto apachee = ComponentTesting.newPrivateProjectDto().setUuid("apachee").setName("apachee").setKey("project2");
ComponentDto apache1 = ComponentTesting.newPrivateProjectDto().setUuid("apache-1").setName("Apache").setKey("project3");
ComponentDto apache2 = ComponentTesting.newPrivateProjectDto().setUuid("apache-2").setName("Apache").setKey("project4");
index(newDoc(windows), newDoc(apachee), newDoc(apache1), newDoc(apache2));
assertResults(new ProjectMeasuresQuery().setQueryText("windows"), windows);
assertResults(new ProjectMeasuresQuery().setQueryText("project2"), apachee);
assertResults(new ProjectMeasuresQuery().setQueryText("pAch"), apache1, apache2, apachee);
}
@Test
public void filter_on_ids() {
index(
newDoc(PROJECT1),
newDoc(PROJECT2),
newDoc(PROJECT3));
ProjectMeasuresQuery query = new ProjectMeasuresQuery().setProjectUuids(newHashSet(PROJECT1.uuid(), PROJECT3.uuid()));
assertResults(query, PROJECT1, PROJECT3);
}
@Test
public void filter_on_tags() {
index(
newDoc(PROJECT1).setTags(newArrayList("finance", "platform")),
newDoc(PROJECT2).setTags(newArrayList("marketing", "platform")),
newDoc(PROJECT3).setTags(newArrayList("finance", "language")));
assertResults(new ProjectMeasuresQuery().setTags(newHashSet("finance")), PROJECT1, PROJECT3);
assertResults(new ProjectMeasuresQuery().setTags(newHashSet("finance", "language")), PROJECT1, PROJECT3);
assertResults(new ProjectMeasuresQuery().setTags(newHashSet("finance", "marketing")), PROJECT1, PROJECT2, PROJECT3);
assertResults(new ProjectMeasuresQuery().setTags(newHashSet("marketing")), PROJECT2);
assertNoResults(new ProjectMeasuresQuery().setTags(newHashSet("tag 42")));
}
@Test
public void filter_on_qualifier() {
index(newDoc(PROJECT1), newDoc(PROJECT2), newDoc(PROJECT3),
newDoc(APP1), newDoc(APP2), newDoc(APP3));
assertResults(new ProjectMeasuresQuery(),
APP1, APP2, APP3, PROJECT1, PROJECT2, PROJECT3);
assertResults(new ProjectMeasuresQuery().setQualifiers(Sets.newHashSet(PROJECT, APP)),
APP1, APP2, APP3, PROJECT1, PROJECT2, PROJECT3);
assertResults(new ProjectMeasuresQuery().setQualifiers(Sets.newHashSet(PROJECT)),
PROJECT1, PROJECT2, PROJECT3);
assertResults(new ProjectMeasuresQuery().setQualifiers(Sets.newHashSet(APP)),
APP1, APP2, APP3);
}
@Test
public void return_correct_number_of_total_if_exceeds_index_max_results() {
index(IntStream.range(0, 12_000)
.mapToObj(operand -> newDoc(ComponentTesting.newPrivateProjectDto()))
.toArray(ProjectMeasuresDoc[]::new));
ProjectMeasuresQuery query = new ProjectMeasuresQuery();
SearchIdResult<String> result = underTest.search(query, new SearchOptions());
assertThat(result.getTotal()).isEqualTo(12_000);
}
@Test
public void return_only_projects_and_applications_authorized_for_user() {
indexForUser(USER1, newDoc(PROJECT1), newDoc(PROJECT2),
newDoc(APP1), newDoc(APP2));
indexForUser(USER2, newDoc(PROJECT3), newDoc(APP3));
userSession.logIn(USER1);
assertResults(new ProjectMeasuresQuery(), APP1, APP2, PROJECT1, PROJECT2);
}
@Test
public void return_only_projects_and_applications_authorized_for_user_groups() {
indexForGroup(GROUP1, newDoc(PROJECT1), newDoc(PROJECT2),
newDoc(APP1), newDoc(APP2));
indexForGroup(GROUP2, newDoc(PROJECT3));
userSession.logIn().setGroups(GROUP1);
assertResults(new ProjectMeasuresQuery(), APP1, APP2, PROJECT1, PROJECT2);
}
@Test
public void return_only_projects_and_applications_authorized_for_user_and_groups() {
indexForUser(USER1, newDoc(PROJECT1), newDoc(PROJECT2),
newDoc(APP1), newDoc(APP2));
indexForGroup(GROUP1, newDoc(PROJECT3));
userSession.logIn(USER1).setGroups(GROUP1);
assertResults(new ProjectMeasuresQuery(), APP1, APP2, PROJECT1, PROJECT2, PROJECT3);
}
@Test
public void anonymous_user_can_only_access_projects_and_applications_authorized_for_anyone() {
index(newDoc(PROJECT1), newDoc(APP1));
indexForUser(USER1, newDoc(PROJECT2), newDoc(APP2));
userSession.anonymous();
assertResults(new ProjectMeasuresQuery(), APP1, PROJECT1);
}
@Test
public void return_all_projects_and_applications_when_setIgnoreAuthorization_is_true() {
indexForUser(USER1, newDoc(PROJECT1), newDoc(PROJECT2), newDoc(APP1), newDoc(APP2));
indexForUser(USER2, newDoc(PROJECT3), newDoc(APP3));
userSession.logIn(USER1);
assertResults(new ProjectMeasuresQuery().setIgnoreAuthorization(false), APP1, APP2, PROJECT1, PROJECT2);
assertResults(new ProjectMeasuresQuery().setIgnoreAuthorization(true), APP1, APP2, APP3, PROJECT1, PROJECT2, PROJECT3);
}
@Test
public void does_not_return_facet_when_no_facets_in_options() {
index(
newDoc(PROJECT1, NCLOC, 10d, COVERAGE_KEY, 30d, MAINTAINABILITY_RATING, 3d)
.setQualityGateStatus(OK.name()));
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions()).getFacets();
assertThat(facets.getAll()).isEmpty();
}
@Test
public void facet_ncloc() {
index(
// 3 docs with ncloc<1K
newDoc(NCLOC, 0d),
newDoc(NCLOC, 0d),
newDoc(NCLOC, 999d),
// 2 docs with ncloc>=1K and ncloc<10K
newDoc(NCLOC, 1_000d),
newDoc(NCLOC, 9_999d),
// 4 docs with ncloc>=10K and ncloc<100K
newDoc(NCLOC, 10_000d),
newDoc(NCLOC, 10_000d),
newDoc(NCLOC, 11_000d),
newDoc(NCLOC, 99_000d),
// 2 docs with ncloc>=100K and ncloc<500K
newDoc(NCLOC, 100_000d),
newDoc(NCLOC, 499_000d),
// 5 docs with ncloc>= 500K
newDoc(NCLOC, 500_000d),
newDoc(NCLOC, 100_000_000d),
newDoc(NCLOC, 500_000d),
newDoc(NCLOC, 1_000_000d),
newDoc(NCLOC, 100_000_000_000d));
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(NCLOC)).getFacets();
assertThat(facets.get(NCLOC)).containsExactly(
entry("*-1000.0", 3L),
entry("1000.0-10000.0", 2L),
entry("10000.0-100000.0", 4L),
entry("100000.0-500000.0", 2L),
entry("500000.0-*", 5L));
}
@Test
public void facet_ncloc_is_sticky() {
index(
// 1 docs with ncloc<1K
newDoc(NCLOC, 999d, COVERAGE, 0d, DUPLICATION, 0d),
// 2 docs with ncloc>=1K and ncloc<10K
newDoc(NCLOC, 1_000d, COVERAGE, 10d, DUPLICATION, 0d),
newDoc(NCLOC, 9_999d, COVERAGE, 20d, DUPLICATION, 0d),
// 3 docs with ncloc>=10K and ncloc<100K
newDoc(NCLOC, 10_000d, COVERAGE, 31d, DUPLICATION, 0d),
newDoc(NCLOC, 11_000d, COVERAGE, 40d, DUPLICATION, 0d),
newDoc(NCLOC, 99_000d, COVERAGE, 50d, DUPLICATION, 0d),
// 2 docs with ncloc>=100K and ncloc<500K
newDoc(NCLOC, 100_000d, COVERAGE, 71d, DUPLICATION, 0d),
newDoc(NCLOC, 499_000d, COVERAGE, 80d, DUPLICATION, 0d),
// 1 docs with ncloc>= 500K
newDoc(NCLOC, 501_000d, COVERAGE, 81d, DUPLICATION, 20d));
Facets facets = underTest.search(new ProjectMeasuresQuery()
.addMetricCriterion(MetricCriterion.create(NCLOC, Operator.LT, 10_000d))
.addMetricCriterion(MetricCriterion.create(DUPLICATION, Operator.LT, 10d)),
new SearchOptions().addFacets(NCLOC, COVERAGE)).getFacets();
// Sticky facet on ncloc does not take into account ncloc filter
assertThat(facets.get(NCLOC)).containsExactly(
entry("*-1000.0", 1L),
entry("1000.0-10000.0", 2L),
entry("10000.0-100000.0", 3L),
entry("100000.0-500000.0", 2L),
entry("500000.0-*", 0L));
// But facet on coverage does well take into into filters
assertThat(facets.get(COVERAGE)).containsOnly(
entry("NO_DATA", 0L),
entry("*-30.0", 3L),
entry("30.0-50.0", 0L),
entry("50.0-70.0", 0L),
entry("70.0-80.0", 0L),
entry("80.0-*", 0L));
}
@Test
public void facet_ncloc_contains_only_projects_authorized_for_user() {
// User can see these projects
indexForUser(USER1,
// docs with ncloc<1K
newDoc(NCLOC, 0d),
newDoc(NCLOC, 100d),
newDoc(NCLOC, 999d),
// docs with ncloc>=1K and ncloc<10K
newDoc(NCLOC, 1_000d),
newDoc(NCLOC, 9_999d));
// User cannot see these projects
indexForUser(USER2,
// doc with ncloc>=10K and ncloc<100K
newDoc(NCLOC, 11_000d),
// doc with ncloc>=100K and ncloc<500K
newDoc(NCLOC, 499_000d),
// doc with ncloc>= 500K
newDoc(NCLOC, 501_000d));
userSession.logIn(USER1);
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(NCLOC)).getFacets();
assertThat(facets.get(NCLOC)).containsExactly(
entry("*-1000.0", 3L),
entry("1000.0-10000.0", 2L),
entry("10000.0-100000.0", 0L),
entry("100000.0-500000.0", 0L),
entry("500000.0-*", 0L));
}
@Test
public void facet_new_lines() {
index(
// 3 docs with ncloc<1K
newDoc(NEW_LINES, 0d),
newDoc(NEW_LINES, 0d),
newDoc(NEW_LINES, 999d),
// 2 docs with ncloc>=1K and ncloc<10K
newDoc(NEW_LINES, 1_000d),
newDoc(NEW_LINES, 9_999d),
// 4 docs with ncloc>=10K and ncloc<100K
newDoc(NEW_LINES, 10_000d),
newDoc(NEW_LINES, 10_000d),
newDoc(NEW_LINES, 11_000d),
newDoc(NEW_LINES, 99_000d),
// 2 docs with ncloc>=100K and ncloc<500K
newDoc(NEW_LINES, 100_000d),
newDoc(NEW_LINES, 499_000d),
// 5 docs with ncloc>= 500K
newDoc(NEW_LINES, 500_000d),
newDoc(NEW_LINES, 100_000_000d),
newDoc(NEW_LINES, 500_000d),
newDoc(NEW_LINES, 1_000_000d),
newDoc(NEW_LINES, 100_000_000_000d));
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(NEW_LINES)).getFacets();
assertThat(facets.get(NEW_LINES)).containsExactly(
entry("*-1000.0", 3L),
entry("1000.0-10000.0", 2L),
entry("10000.0-100000.0", 4L),
entry("100000.0-500000.0", 2L),
entry("500000.0-*", 5L));
}
@Test
public void facet_coverage() {
index(
// 1 doc with no coverage
newDocWithNoMeasure(),
// 3 docs with coverage<30%
newDoc(COVERAGE, 0d),
newDoc(COVERAGE, 0d),
newDoc(COVERAGE, 29d),
// 2 docs with coverage>=30% and coverage<50%
newDoc(COVERAGE, 30d),
newDoc(COVERAGE, 49d),
// 4 docs with coverage>=50% and coverage<70%
newDoc(COVERAGE, 50d),
newDoc(COVERAGE, 60d),
newDoc(COVERAGE, 60d),
newDoc(COVERAGE, 69d),
// 2 docs with coverage>=70% and coverage<80%
newDoc(COVERAGE, 70d),
newDoc(COVERAGE, 79d),
// 5 docs with coverage>= 80%
newDoc(COVERAGE, 80d),
newDoc(COVERAGE, 80d),
newDoc(COVERAGE, 90d),
newDoc(COVERAGE, 90.5d),
newDoc(COVERAGE, 100d));
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(COVERAGE)).getFacets();
assertThat(facets.get(COVERAGE)).containsOnly(
entry("NO_DATA", 1L),
entry("*-30.0", 3L),
entry("30.0-50.0", 2L),
entry("50.0-70.0", 4L),
entry("70.0-80.0", 2L),
entry("80.0-*", 5L));
}
@Test
public void facet_coverage_is_sticky() {
index(
// docs with no coverage
newDoc(NCLOC, 999d, DUPLICATION, 0d),
newDoc(NCLOC, 999d, DUPLICATION, 1d),
newDoc(NCLOC, 999d, DUPLICATION, 20d),
// docs with coverage<30%
newDoc(NCLOC, 999d, COVERAGE, 0d, DUPLICATION, 0d),
newDoc(NCLOC, 1_000d, COVERAGE, 10d, DUPLICATION, 0d),
newDoc(NCLOC, 9_999d, COVERAGE, 20d, DUPLICATION, 0d),
// docs with coverage>=30% and coverage<50%
newDoc(NCLOC, 10_000d, COVERAGE, 31d, DUPLICATION, 0d),
newDoc(NCLOC, 11_000d, COVERAGE, 40d, DUPLICATION, 0d),
// docs with coverage>=50% and coverage<70%
newDoc(NCLOC, 99_000d, COVERAGE, 50d, DUPLICATION, 0d),
// docs with coverage>=70% and coverage<80%
newDoc(NCLOC, 100_000d, COVERAGE, 71d, DUPLICATION, 0d),
// docs with coverage>= 80%
newDoc(NCLOC, 499_000d, COVERAGE, 80d, DUPLICATION, 15d),
newDoc(NCLOC, 501_000d, COVERAGE, 810d, DUPLICATION, 20d));
Facets facets = underTest.search(new ProjectMeasuresQuery()
.addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 30d))
.addMetricCriterion(MetricCriterion.create(DUPLICATION, Operator.LT, 10d)),
new SearchOptions().addFacets(COVERAGE, NCLOC)).getFacets();
// Sticky facet on coverage does not take into account coverage filter
assertThat(facets.get(COVERAGE)).containsExactly(
entry("NO_DATA", 2L),
entry("*-30.0", 3L),
entry("30.0-50.0", 2L),
entry("50.0-70.0", 1L),
entry("70.0-80.0", 1L),
entry("80.0-*", 0L));
// But facet on ncloc does well take into into filters
assertThat(facets.get(NCLOC)).containsExactly(
entry("*-1000.0", 1L),
entry("1000.0-10000.0", 2L),
entry("10000.0-100000.0", 0L),
entry("100000.0-500000.0", 0L),
entry("500000.0-*", 0L));
}
@Test
public void facet_coverage_contains_only_projects_authorized_for_user() {
// User can see these projects
indexForUser(USER1,
// 1 doc with no coverage
newDocWithNoMeasure(),
// docs with coverage<30%
newDoc(COVERAGE, 0d),
newDoc(COVERAGE, 0d),
newDoc(COVERAGE, 29d),
// docs with coverage>=30% and coverage<50%
newDoc(COVERAGE, 30d),
newDoc(COVERAGE, 49d));
// User cannot see these projects
indexForUser(USER2,
// 2 docs with no coverage
newDocWithNoMeasure(),
newDocWithNoMeasure(),
// docs with coverage>=50% and coverage<70%
newDoc(COVERAGE, 50d),
// docs with coverage>=70% and coverage<80%
newDoc(COVERAGE, 70d),
// docs with coverage>= 80%
newDoc(COVERAGE, 80d));
userSession.logIn(USER1);
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(COVERAGE)).getFacets();
assertThat(facets.get(COVERAGE)).containsExactly(
entry("NO_DATA", 1L),
entry("*-30.0", 3L),
entry("30.0-50.0", 2L),
entry("50.0-70.0", 0L),
entry("70.0-80.0", 0L),
entry("80.0-*", 0L));
}
@Test
public void facet_new_coverage() {
index(
// 1 doc with no coverage
newDocWithNoMeasure(),
// 3 docs with coverage<30%
newDoc(NEW_COVERAGE, 0d),
newDoc(NEW_COVERAGE, 0d),
newDoc(NEW_COVERAGE, 29d),
// 2 docs with coverage>=30% and coverage<50%
newDoc(NEW_COVERAGE, 30d),
newDoc(NEW_COVERAGE, 49d),
// 4 docs with coverage>=50% and coverage<70%
newDoc(NEW_COVERAGE, 50d),
newDoc(NEW_COVERAGE, 60d),
newDoc(NEW_COVERAGE, 60d),
newDoc(NEW_COVERAGE, 69d),
// 2 docs with coverage>=70% and coverage<80%
newDoc(NEW_COVERAGE, 70d),
newDoc(NEW_COVERAGE, 79d),
// 5 docs with coverage>= 80%
newDoc(NEW_COVERAGE, 80d),
newDoc(NEW_COVERAGE, 80d),
newDoc(NEW_COVERAGE, 90d),
newDoc(NEW_COVERAGE, 90.5d),
newDoc(NEW_COVERAGE, 100d));
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(NEW_COVERAGE)).getFacets();
assertThat(facets.get(NEW_COVERAGE)).containsOnly(
entry("NO_DATA", 1L),
entry("*-30.0", 3L),
entry("30.0-50.0", 2L),
entry("50.0-70.0", 4L),
entry("70.0-80.0", 2L),
entry("80.0-*", 5L));
}
@Test
public void facet_duplicated_lines_density() {
index(
// 1 doc with no duplication
newDocWithNoMeasure(),
// 3 docs with duplication<3%
newDoc(DUPLICATION, 0d),
newDoc(DUPLICATION, 0d),
newDoc(DUPLICATION, 2.9d),
// 2 docs with duplication>=3% and duplication<5%
newDoc(DUPLICATION, 3d),
newDoc(DUPLICATION, 4.9d),
// 4 docs with duplication>=5% and duplication<10%
newDoc(DUPLICATION, 5d),
newDoc(DUPLICATION, 6d),
newDoc(DUPLICATION, 6d),
newDoc(DUPLICATION, 9.9d),
// 2 docs with duplication>=10% and duplication<20%
newDoc(DUPLICATION, 10d),
newDoc(DUPLICATION, 19.9d),
// 5 docs with duplication>= 20%
newDoc(DUPLICATION, 20d),
newDoc(DUPLICATION, 20d),
newDoc(DUPLICATION, 50d),
newDoc(DUPLICATION, 80d),
newDoc(DUPLICATION, 100d));
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(DUPLICATION)).getFacets();
assertThat(facets.get(DUPLICATION)).containsOnly(
entry("NO_DATA", 1L),
entry("*-3.0", 3L),
entry("3.0-5.0", 2L),
entry("5.0-10.0", 4L),
entry("10.0-20.0", 2L),
entry("20.0-*", 5L));
}
@Test
public void facet_duplicated_lines_density_is_sticky() {
index(
// docs with no duplication
newDoc(NCLOC, 50_001d, COVERAGE, 29d),
// docs with duplication<3%
newDoc(DUPLICATION, 0d, NCLOC, 999d, COVERAGE, 0d),
// docs with duplication>=3% and duplication<5%
newDoc(DUPLICATION, 3d, NCLOC, 5000d, COVERAGE, 0d),
newDoc(DUPLICATION, 4.9d, NCLOC, 6000d, COVERAGE, 0d),
// docs with duplication>=5% and duplication<10%
newDoc(DUPLICATION, 5d, NCLOC, 11000d, COVERAGE, 0d),
// docs with duplication>=10% and duplication<20%
newDoc(DUPLICATION, 10d, NCLOC, 120000d, COVERAGE, 10d),
newDoc(DUPLICATION, 19.9d, NCLOC, 130000d, COVERAGE, 20d),
// docs with duplication>= 20%
newDoc(DUPLICATION, 20d, NCLOC, 1000000d, COVERAGE, 40d));
Facets facets = underTest.search(new ProjectMeasuresQuery()
.addMetricCriterion(MetricCriterion.create(DUPLICATION, Operator.LT, 10d))
.addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 30d)),
new SearchOptions().addFacets(DUPLICATION, NCLOC)).getFacets();
// Sticky facet on duplication does not take into account duplication filter
assertThat(facets.get(DUPLICATION)).containsOnly(
entry("NO_DATA", 1L),
entry("*-3.0", 1L),
entry("3.0-5.0", 2L),
entry("5.0-10.0", 1L),
entry("10.0-20.0", 2L),
entry("20.0-*", 0L));
// But facet on ncloc does well take into into filters
assertThat(facets.get(NCLOC)).containsOnly(
entry("*-1000.0", 1L),
entry("1000.0-10000.0", 2L),
entry("10000.0-100000.0", 1L),
entry("100000.0-500000.0", 0L),
entry("500000.0-*", 0L));
}
@Test
public void facet_duplicated_lines_density_contains_only_projects_authorized_for_user() {
// User can see these projects
indexForUser(USER1,
// docs with no duplication
newDocWithNoMeasure(),
// docs with duplication<3%
newDoc(DUPLICATION, 0d),
newDoc(DUPLICATION, 0d),
newDoc(DUPLICATION, 2.9d),
// docs with duplication>=3% and duplication<5%
newDoc(DUPLICATION, 3d),
newDoc(DUPLICATION, 4.9d));
// User cannot see these projects
indexForUser(USER2,
// docs with no duplication
newDocWithNoMeasure(),
newDocWithNoMeasure(),
// docs with duplication>=5% and duplication<10%
newDoc(DUPLICATION, 5d),
// docs with duplication>=10% and duplication<20%
newDoc(DUPLICATION, 10d),
// docs with duplication>= 20%
newDoc(DUPLICATION, 20d));
userSession.logIn(USER1);
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(DUPLICATION)).getFacets();
assertThat(facets.get(DUPLICATION)).containsOnly(
entry("NO_DATA", 1L),
entry("*-3.0", 3L),
entry("3.0-5.0", 2L),
entry("5.0-10.0", 0L),
entry("10.0-20.0", 0L),
entry("20.0-*", 0L));
}
@Test
public void facet_new_duplicated_lines_density() {
index(
// 2 docs with no measure
newDocWithNoMeasure(),
newDocWithNoMeasure(),
// 3 docs with duplication<3%
newDoc(NEW_DUPLICATION, 0d),
newDoc(NEW_DUPLICATION, 0d),
newDoc(NEW_DUPLICATION, 2.9d),
// 2 docs with duplication>=3% and duplication<5%
newDoc(NEW_DUPLICATION, 3d),
newDoc(NEW_DUPLICATION, 4.9d),
// 4 docs with duplication>=5% and duplication<10%
newDoc(NEW_DUPLICATION, 5d),
newDoc(NEW_DUPLICATION, 6d),
newDoc(NEW_DUPLICATION, 6d),
newDoc(NEW_DUPLICATION, 9.9d),
// 2 docs with duplication>=10% and duplication<20%
newDoc(NEW_DUPLICATION, 10d),
newDoc(NEW_DUPLICATION, 19.9d),
// 5 docs with duplication>= 20%
newDoc(NEW_DUPLICATION, 20d),
newDoc(NEW_DUPLICATION, 20d),
newDoc(NEW_DUPLICATION, 50d),
newDoc(NEW_DUPLICATION, 80d),
newDoc(NEW_DUPLICATION, 100d));
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(NEW_DUPLICATION)).getFacets();
assertThat(facets.get(NEW_DUPLICATION)).containsExactly(
entry("NO_DATA", 2L),
entry("*-3.0", 3L),
entry("3.0-5.0", 2L),
entry("5.0-10.0", 4L),
entry("10.0-20.0", 2L),
entry("20.0-*", 5L));
}
@Test
@UseDataProvider("rating_metric_keys")
public void facet_on_rating(String metricKey) {
index(
// 3 docs with rating A
newDoc(metricKey, 1d),
newDoc(metricKey, 1d),
newDoc(metricKey, 1d),
// 2 docs with rating B
newDoc(metricKey, 2d),
newDoc(metricKey, 2d),
// 4 docs with rating C
newDoc(metricKey, 3d),
newDoc(metricKey, 3d),
newDoc(metricKey, 3d),
newDoc(metricKey, 3d),
// 2 docs with rating D
newDoc(metricKey, 4d),
newDoc(metricKey, 4d),
// 5 docs with rating E
newDoc(metricKey, 5d),
newDoc(metricKey, 5d),
newDoc(metricKey, 5d),
newDoc(metricKey, 5d),
newDoc(metricKey, 5d));
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(metricKey)).getFacets();
assertThat(facets.get(metricKey)).containsExactly(
entry("1", 3L),
entry("2", 2L),
entry("3", 4L),
entry("4", 2L),
entry("5", 5L));
}
@Test
@UseDataProvider("rating_metric_keys")
public void facet_on_rating_is_sticky(String metricKey) {
index(
// docs with rating A
newDoc(metricKey, 1d, NCLOC, 100d, COVERAGE, 0d),
newDoc(metricKey, 1d, NCLOC, 200d, COVERAGE, 0d),
newDoc(metricKey, 1d, NCLOC, 999d, COVERAGE, 0d),
// docs with rating B
newDoc(metricKey, 2d, NCLOC, 2000d, COVERAGE, 0d),
newDoc(metricKey, 2d, NCLOC, 5000d, COVERAGE, 0d),
// docs with rating C
newDoc(metricKey, 3d, NCLOC, 20000d, COVERAGE, 0d),
newDoc(metricKey, 3d, NCLOC, 30000d, COVERAGE, 0d),
newDoc(metricKey, 3d, NCLOC, 40000d, COVERAGE, 0d),
newDoc(metricKey, 3d, NCLOC, 50000d, COVERAGE, 0d),
// docs with rating D
newDoc(metricKey, 4d, NCLOC, 120000d, COVERAGE, 0d),
// docs with rating E
newDoc(metricKey, 5d, NCLOC, 600000d, COVERAGE, 40d),
newDoc(metricKey, 5d, NCLOC, 700000d, COVERAGE, 50d),
newDoc(metricKey, 5d, NCLOC, 800000d, COVERAGE, 60d));
Facets facets = underTest.search(new ProjectMeasuresQuery()
.addMetricCriterion(MetricCriterion.create(metricKey, Operator.LT, 3d))
.addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 30d)),
new SearchOptions().addFacets(metricKey, NCLOC)).getFacets();
// Sticky facet on maintainability rating does not take into account maintainability rating filter
assertThat(facets.get(metricKey)).containsExactly(
entry("1", 3L),
entry("2", 2L),
entry("3", 4L),
entry("4", 1L),
entry("5", 0L));
// But facet on ncloc does well take into into filters
assertThat(facets.get(NCLOC)).containsExactly(
entry("*-1000.0", 3L),
entry("1000.0-10000.0", 2L),
entry("10000.0-100000.0", 0L),
entry("100000.0-500000.0", 0L),
entry("500000.0-*", 0L));
}
@Test
@UseDataProvider("rating_metric_keys")
public void facet_on_rating_contains_only_projects_authorized_for_user(String metricKey) {
// User can see these projects
indexForUser(USER1,
// 3 docs with rating A
newDoc(metricKey, 1d),
newDoc(metricKey, 1d),
newDoc(metricKey, 1d),
// 2 docs with rating B
newDoc(metricKey, 2d),
newDoc(metricKey, 2d));
// User cannot see these projects
indexForUser(USER2,
// docs with rating C
newDoc(metricKey, 3d),
// docs with rating D
newDoc(metricKey, 4d),
// docs with rating E
newDoc(metricKey, 5d));
userSession.logIn(USER1);
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(metricKey)).getFacets();
assertThat(facets.get(metricKey)).containsExactly(
entry("1", 3L),
entry("2", 2L),
entry("3", 0L),
entry("4", 0L),
entry("5", 0L));
}
@Test
public void facet_quality_gate() {
index(
// 2 docs with QG OK
newDoc().setQualityGateStatus(OK.name()),
newDoc().setQualityGateStatus(OK.name()),
// 4 docs with QG ERROR
newDoc().setQualityGateStatus(ERROR.name()),
newDoc().setQualityGateStatus(ERROR.name()),
newDoc().setQualityGateStatus(ERROR.name()),
newDoc().setQualityGateStatus(ERROR.name()));
LinkedHashMap<String, Long> result = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(ALERT_STATUS_KEY)).getFacets().get(ALERT_STATUS_KEY);
assertThat(result).containsOnly(
entry(ERROR.name(), 4L),
entry(OK.name(), 2L),
entry(WARN.name(), 0L));
}
@Test
public void facet_quality_gate_is_sticky() {
index(
// 2 docs with QG OK
newDoc(NCLOC, 10d, COVERAGE, 0d).setQualityGateStatus(OK.name()),
newDoc(NCLOC, 10d, COVERAGE, 0d).setQualityGateStatus(OK.name()),
// 4 docs with QG ERROR
newDoc(NCLOC, 100d, COVERAGE, 0d).setQualityGateStatus(ERROR.name()),
newDoc(NCLOC, 5000d, COVERAGE, 40d).setQualityGateStatus(ERROR.name()),
newDoc(NCLOC, 12000d, COVERAGE, 50d).setQualityGateStatus(ERROR.name()),
newDoc(NCLOC, 13000d, COVERAGE, 60d).setQualityGateStatus(ERROR.name()));
Facets facets = underTest.search(new ProjectMeasuresQuery()
.setQualityGateStatus(ERROR)
.addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 55d)),
new SearchOptions().addFacets(ALERT_STATUS_KEY, NCLOC)).getFacets();
// Sticky facet on quality gate does not take into account quality gate filter
assertThat(facets.get(ALERT_STATUS_KEY)).containsOnly(
entry(OK.name(), 2L),
entry(ERROR.name(), 3L),
entry(WARN.name(), 0L));
// But facet on ncloc does well take into into filters
assertThat(facets.get(NCLOC)).containsExactly(
entry("*-1000.0", 1L),
entry("1000.0-10000.0", 1L),
entry("10000.0-100000.0", 1L),
entry("100000.0-500000.0", 0L),
entry("500000.0-*", 0L));
}
@Test
public void facet_quality_gate_contains_only_projects_authorized_for_user() {
// User can see these projects
indexForUser(USER1,
// 2 docs with QG OK
newDoc().setQualityGateStatus(OK.name()),
newDoc().setQualityGateStatus(OK.name()));
// User cannot see these projects
indexForUser(USER2,
// 4 docs with QG ERROR
newDoc().setQualityGateStatus(ERROR.name()),
newDoc().setQualityGateStatus(ERROR.name()),
newDoc().setQualityGateStatus(ERROR.name()),
newDoc().setQualityGateStatus(ERROR.name()));
userSession.logIn(USER1);
LinkedHashMap<String, Long> result = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(ALERT_STATUS_KEY)).getFacets().get(ALERT_STATUS_KEY);
assertThat(result).containsOnly(
entry(ERROR.name(), 0L),
entry(OK.name(), 2L),
entry(WARN.name(), 0L));
}
@Test
public void facet_quality_gate_using_deprecated_warning() {
index(
// 2 docs with QG OK
newDoc().setQualityGateStatus(OK.name()),
newDoc().setQualityGateStatus(OK.name()),
// 3 docs with QG WARN
newDoc().setQualityGateStatus(WARN.name()),
newDoc().setQualityGateStatus(WARN.name()),
newDoc().setQualityGateStatus(WARN.name()),
// 4 docs with QG ERROR
newDoc().setQualityGateStatus(ERROR.name()),
newDoc().setQualityGateStatus(ERROR.name()),
newDoc().setQualityGateStatus(ERROR.name()),
newDoc().setQualityGateStatus(ERROR.name()));
LinkedHashMap<String, Long> result = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(ALERT_STATUS_KEY)).getFacets().get(ALERT_STATUS_KEY);
assertThat(result).containsOnly(
entry(ERROR.name(), 4L),
entry(WARN.name(), 3L),
entry(OK.name(), 2L));
}
@Test
public void facet_quality_gate_does_not_return_deprecated_warning_when_set_ignore_warning_is_true() {
index(
// 2 docs with QG OK
newDoc().setQualityGateStatus(OK.name()),
newDoc().setQualityGateStatus(OK.name()),
// 4 docs with QG ERROR
newDoc().setQualityGateStatus(ERROR.name()),
newDoc().setQualityGateStatus(ERROR.name()),
newDoc().setQualityGateStatus(ERROR.name()),
newDoc().setQualityGateStatus(ERROR.name()));
assertThat(underTest.search(new ProjectMeasuresQuery().setIgnoreWarning(true), new SearchOptions().addFacets(ALERT_STATUS_KEY)).getFacets().get(ALERT_STATUS_KEY)).containsOnly(
entry(ERROR.name(), 4L),
entry(OK.name(), 2L));
assertThat(underTest.search(new ProjectMeasuresQuery().setIgnoreWarning(false), new SearchOptions().addFacets(ALERT_STATUS_KEY)).getFacets().get(ALERT_STATUS_KEY))
.containsOnly(
entry(ERROR.name(), 4L),
entry(WARN.name(), 0L),
entry(OK.name(), 2L));
}
@Test
public void facet_languages() {
index(
newDoc().setLanguages(singletonList("java")),
newDoc().setLanguages(singletonList("java")),
newDoc().setLanguages(singletonList("xoo")),
newDoc().setLanguages(singletonList("xml")),
newDoc().setLanguages(asList("<null>", "java")),
newDoc().setLanguages(asList("<null>", "java", "xoo")));
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(LANGUAGES)).getFacets();
assertThat(facets.get(LANGUAGES)).containsOnly(
entry("<null>", 2L),
entry("java", 4L),
entry("xoo", 2L),
entry("xml", 1L));
}
@Test
public void facet_languages_is_limited_to_10_languages() {
index(
newDoc().setLanguages(asList("<null>", "java", "xoo", "css", "cpp")),
newDoc().setLanguages(asList("xml", "php", "python", "perl", "ruby")),
newDoc().setLanguages(asList("js", "scala")));
Facets facets = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(LANGUAGES)).getFacets();
assertThat(facets.get(LANGUAGES)).hasSize(10);
}
@Test
public void facet_languages_is_sticky() {
index(
newDoc(NCLOC, 10d).setLanguages(singletonList("java")),
newDoc(NCLOC, 10d).setLanguages(singletonList("java")),
newDoc(NCLOC, 10d).setLanguages(singletonList("xoo")),
newDoc(NCLOC, 100d).setLanguages(singletonList("xml")),
newDoc(NCLOC, 100d).setLanguages(asList("<null>", "java")),
newDoc(NCLOC, 5000d).setLanguages(asList("<null>", "java", "xoo")));
Facets facets = underTest.search(
new ProjectMeasuresQuery().setLanguages(ImmutableSet.of("java")),
new SearchOptions().addFacets(LANGUAGES, NCLOC)).getFacets();
// Sticky facet on language does not take into account language filter
assertThat(facets.get(LANGUAGES)).containsOnly(
entry("<null>", 2L),
entry("java", 4L),
entry("xoo", 2L),
entry("xml", 1L));
// But facet on ncloc does well take account into filters
assertThat(facets.get(NCLOC)).containsExactly(
entry("*-1000.0", 3L),
entry("1000.0-10000.0", 1L),
entry("10000.0-100000.0", 0L),
entry("100000.0-500000.0", 0L),
entry("500000.0-*", 0L));
}
@Test
public void facet_languages_returns_more_than_10_languages_when_languages_filter_contains_value_not_in_top_10() {
index(
newDoc().setLanguages(asList("<null>", "java", "xoo", "css", "cpp")),
newDoc().setLanguages(asList("xml", "php", "python", "perl", "ruby")),
newDoc().setLanguages(asList("js", "scala")));
Facets facets = underTest.search(new ProjectMeasuresQuery().setLanguages(ImmutableSet.of("xoo", "xml")), new SearchOptions().addFacets(LANGUAGES)).getFacets();
assertThat(facets.get(LANGUAGES)).containsOnly(
entry("<null>", 1L),
entry("cpp", 1L),
entry("css", 1L),
entry("java", 1L),
entry("js", 1L),
entry("perl", 1L),
entry("php", 1L),
entry("python", 1L),
entry("ruby", 1L),
entry("scala", 1L),
entry("xoo", 1L),
entry("xml", 1L));
}
@Test
public void facet_languages_contains_only_projects_authorized_for_user() {
// User can see these projects
indexForUser(USER1,
newDoc().setLanguages(singletonList("java")),
newDoc().setLanguages(asList("java", "xoo")));
// User cannot see these projects
indexForUser(USER2,
newDoc().setLanguages(singletonList("java")),
newDoc().setLanguages(asList("java", "xoo")));
userSession.logIn(USER1);
LinkedHashMap<String, Long> result = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(LANGUAGES)).getFacets().get(LANGUAGES);
assertThat(result).containsOnly(
entry("java", 2L),
entry("xoo", 1L));
}
@Test
public void facet_qualifier() {
index(
// 2 docs with qualifier APP
newDoc().setQualifier(APP),
newDoc().setQualifier(APP),
// 4 docs with qualifier TRK
newDoc().setQualifier(PROJECT),
newDoc().setQualifier(PROJECT),
newDoc().setQualifier(PROJECT),
newDoc().setQualifier(PROJECT));
LinkedHashMap<String, Long> result = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(FILTER_QUALIFIER)).getFacets().get(FILTER_QUALIFIER);
assertThat(result).containsOnly(
entry(APP, 2L),
entry(PROJECT, 4L));
}
@Test
public void facet_qualifier_is_sticky() {
index(
// 2 docs with qualifier APP
newDoc(NCLOC, 10d, COVERAGE, 0d).setQualifier(APP),
newDoc(NCLOC, 10d, COVERAGE, 0d).setQualifier(APP),
// 4 docs with qualifier TRK
newDoc(NCLOC, 100d, COVERAGE, 0d).setQualifier(PROJECT),
newDoc(NCLOC, 5000d, COVERAGE, 40d).setQualifier(PROJECT),
newDoc(NCLOC, 12000d, COVERAGE, 50d).setQualifier(PROJECT),
newDoc(NCLOC, 13000d, COVERAGE, 60d).setQualifier(PROJECT));
Facets facets = underTest.search(new ProjectMeasuresQuery()
.setQualifiers(Sets.newHashSet(PROJECT))
.addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 55d)),
new SearchOptions().addFacets(FILTER_QUALIFIER, NCLOC)).getFacets();
// Sticky facet on qualifier does not take into account qualifier filter
assertThat(facets.get(FILTER_QUALIFIER)).containsOnly(
entry(APP, 2L),
entry(PROJECT, 3L));
// But facet on ncloc does well take into into filters
assertThat(facets.get(NCLOC)).containsExactly(
entry("*-1000.0", 1L),
entry("1000.0-10000.0", 1L),
entry("10000.0-100000.0", 1L),
entry("100000.0-500000.0", 0L),
entry("500000.0-*", 0L));
}
@Test
public void facet_qualifier_contains_only_app_and_projects_authorized_for_user() {
// User can see these projects
indexForUser(USER1,
// 3 docs with qualifier APP, PROJECT
newDoc().setQualifier(APP),
newDoc().setQualifier(APP),
newDoc().setQualifier(PROJECT));
// User cannot see these projects
indexForUser(USER2,
// 4 docs with qualifier PROJECT
newDoc().setQualifier(PROJECT),
newDoc().setQualifier(PROJECT),
newDoc().setQualifier(PROJECT),
newDoc().setQualifier(PROJECT));
userSession.logIn(USER1);
LinkedHashMap<String, Long> result = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(FILTER_QUALIFIER)).getFacets().get(FILTER_QUALIFIER);
assertThat(result).containsOnly(
entry(APP, 2L),
entry(PROJECT, 1L));
}
@Test
public void facet_tags() {
index(
newDoc().setTags(newArrayList("finance", "offshore", "java")),
newDoc().setTags(newArrayList("finance", "javascript")),
newDoc().setTags(newArrayList("marketing", "finance")),
newDoc().setTags(newArrayList("marketing", "offshore")),
newDoc().setTags(newArrayList("finance", "marketing")),
newDoc().setTags(newArrayList("finance")));
Map<String, Long> result = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(FIELD_TAGS)).getFacets().get(FIELD_TAGS);
assertThat(result).containsOnly(
entry("finance", 5L),
entry("marketing", 3L),
entry("offshore", 2L),
entry("java", 1L),
entry("javascript", 1L));
}
@Test
public void facet_tags_is_sticky() {
index(
newDoc().setTags(newArrayList("finance")).setQualityGateStatus(OK.name()),
newDoc().setTags(newArrayList("finance")).setQualityGateStatus(ERROR.name()),
newDoc().setTags(newArrayList("cpp")).setQualityGateStatus(ERROR.name()));
Facets facets = underTest.search(
new ProjectMeasuresQuery().setTags(newHashSet("cpp")),
new SearchOptions().addFacets(FIELD_TAGS).addFacets(ALERT_STATUS_KEY))
.getFacets();
assertThat(facets.get(FIELD_TAGS)).containsOnly(
entry("finance", 2L),
entry("cpp", 1L));
assertThat(facets.get(ALERT_STATUS_KEY)).containsOnly(
entry(OK.name(), 0L),
entry(ERROR.name(), 1L),
entry(WARN.name(), 0L));
}
@Test
public void facet_tags_returns_10_elements_by_default() {
index(
newDoc().setTags(newArrayList("finance1", "finance2", "finance3", "finance4", "finance5", "finance6", "finance7", "finance8", "finance9", "finance10")),
newDoc().setTags(newArrayList("finance1", "finance2", "finance3", "finance4", "finance5", "finance6", "finance7", "finance8", "finance9", "finance10")),
newDoc().setTags(newArrayList("solo")));
Map<String, Long> result = underTest.search(new ProjectMeasuresQuery(), new SearchOptions().addFacets(FIELD_TAGS)).getFacets().get(FIELD_TAGS);
assertThat(result).hasSize(10).containsOnlyKeys("finance1", "finance2", "finance3", "finance4", "finance5", "finance6", "finance7", "finance8", "finance9", "finance10");
}
@Test
public void facet_tags_returns_more_than_10_tags_when_tags_filter_contains_value_not_in_top_10() {
index(
newDoc().setTags(newArrayList("finance1", "finance2", "finance3", "finance4", "finance5", "finance6", "finance7", "finance8", "finance9", "finance10")),
newDoc().setTags(newArrayList("finance1", "finance2", "finance3", "finance4", "finance5", "finance6", "finance7", "finance8", "finance9", "finance10")),
newDoc().setTags(newArrayList("solo", "solo2")));
Map<String, Long> result = underTest.search(new ProjectMeasuresQuery().setTags(ImmutableSet.of("solo", "solo2")), new SearchOptions().addFacets(FIELD_TAGS)).getFacets()
.get(FIELD_TAGS);
assertThat(result).hasSize(12).containsOnlyKeys("finance1", "finance2", "finance3", "finance4", "finance5", "finance6", "finance7", "finance8", "finance9", "finance10", "solo",
"solo2");
}
@Test
public void search_tags() {
index(
newDoc().setTags(newArrayList("finance", "offshore", "java")),
newDoc().setTags(newArrayList("official", "javascript")),
newDoc().setTags(newArrayList("marketing", "official")),
newDoc().setTags(newArrayList("marketing", "Madhoff")),
newDoc().setTags(newArrayList("finance", "offshore")),
newDoc().setTags(newArrayList("offshore")));
List<String> result = underTest.searchTags("off", 1,10);
assertThat(result).containsOnly("offshore", "official", "Madhoff");
}
@Test
public void search_tags_return_all_tags() {
index(
newDoc().setTags(newArrayList("finance", "offshore", "java")),
newDoc().setTags(newArrayList("official", "javascript")),
newDoc().setTags(newArrayList("marketing", "official")),
newDoc().setTags(newArrayList("marketing", "Madhoff")),
newDoc().setTags(newArrayList("finance", "offshore")),
newDoc().setTags(newArrayList("offshore")));
List<String> result = underTest.searchTags(null, 1, 10);
assertThat(result).containsOnly("offshore", "official", "Madhoff", "finance", "marketing", "java", "javascript");
}
@Test
public void search_tags_in_lexical_order() {
index(
newDoc().setTags(newArrayList("finance", "offshore", "java")),
newDoc().setTags(newArrayList("official", "javascript")),
newDoc().setTags(newArrayList("marketing", "official")),
newDoc().setTags(newArrayList("marketing", "Madhoff")),
newDoc().setTags(newArrayList("finance", "offshore")),
newDoc().setTags(newArrayList("offshore")));
List<String> result = underTest.searchTags(null, 1,10);
assertThat(result).containsExactly("Madhoff", "finance", "java", "javascript", "marketing", "official", "offshore");
}
@Test
public void search_tags_follows_paging() {
index(
newDoc().setTags(newArrayList("finance", "offshore", "java")),
newDoc().setTags(newArrayList("official", "javascript")),
newDoc().setTags(newArrayList("marketing", "official")),
newDoc().setTags(newArrayList("marketing", "Madhoff")),
newDoc().setTags(newArrayList("finance", "offshore")),
newDoc().setTags(newArrayList("offshore")));
List<String> result = underTest.searchTags(null, 1,3);
assertThat(result).containsExactly("Madhoff", "finance", "java");
result = underTest.searchTags(null, 2,3);
assertThat(result).containsExactly("javascript", "marketing", "official");
result = underTest.searchTags(null, 3,3);
assertThat(result).containsExactly("offshore");
result = underTest.searchTags(null, 3,4);
assertThat(result).isEmpty();
}
@Test
public void search_tags_returns_nothing_if_page_too_large() {
index(
newDoc().setTags(newArrayList("finance", "offshore", "java")),
newDoc().setTags(newArrayList("official", "javascript")),
newDoc().setTags(newArrayList("marketing", "official")),
newDoc().setTags(newArrayList("marketing", "Madhoff")),
newDoc().setTags(newArrayList("finance", "offshore")),
newDoc().setTags(newArrayList("offshore")));
List<String> result = underTest.searchTags(null, 10,2);
assertThat(result).isEmpty();
}
@Test
public void search_tags_only_of_authorized_projects() {
indexForUser(USER1,
newDoc(PROJECT1).setTags(singletonList("finance")),
newDoc(PROJECT2).setTags(singletonList("marketing")));
indexForUser(USER2,
newDoc(PROJECT3).setTags(singletonList("offshore")));
userSession.logIn(USER1);
List<String> result = underTest.searchTags(null, 1,10);
assertThat(result).containsOnly("finance", "marketing");
}
@Test
public void search_tags_with_no_tags() {
List<String> result = underTest.searchTags("whatever", 1,10);
assertThat(result).isEmpty();
}
@Test
public void search_tags_with_page_size_at_0() {
index(newDoc().setTags(newArrayList("offshore")));
List<String> result = underTest.searchTags(null, 1,0);
assertThat(result).isEmpty();
}
@Test
public void search_statistics() {
es.putDocuments(TYPE_PROJECT_MEASURES,
newDoc("lines", 10, "coverage", 80)
.setLanguages(Arrays.asList("java", "cs", "js"))
.setNclocLanguageDistributionFromMap(ImmutableMap.of("java", 200, "cs", 250, "js", 50)),
newDoc("lines", 20, "coverage", 80)
.setLanguages(Arrays.asList("java", "python", "kotlin"))
.setNclocLanguageDistributionFromMap(ImmutableMap.of("java", 300, "python", 100, "kotlin", 404)));
ProjectMeasuresStatistics result = underTest.searchSupportStatistics();
assertThat(result.getProjectCount()).isEqualTo(2);
assertThat(result.getProjectCountByLanguage()).containsOnly(
entry("java", 2L), entry("cs", 1L), entry("js", 1L), entry("python", 1L), entry("kotlin", 1L));
assertThat(result.getNclocByLanguage()).containsOnly(
entry("java", 500L), entry("cs", 250L), entry("js", 50L), entry("python", 100L), entry("kotlin", 404L));
}
@Test
public void search_statistics_for_large_instances() {
int nbProjects = 25000;
int javaLocByProjects = 100;
int jsLocByProjects = 900;
int csLocByProjects = 2;
ProjectMeasuresDoc[] documents = IntStream.range(0, nbProjects).mapToObj(i ->
newDoc("lines", 10, "coverage", 80)
.setLanguages(asList("java", "cs", "js"))
.setNclocLanguageDistributionFromMap(ImmutableMap.of("java", javaLocByProjects, "cs", csLocByProjects, "js", jsLocByProjects))).toArray(ProjectMeasuresDoc[]::new);
es.putDocuments(TYPE_PROJECT_MEASURES, documents);
ProjectMeasuresStatistics result = underTest.searchSupportStatistics();
assertThat(result.getProjectCount()).isEqualTo(nbProjects);
assertThat(result.getProjectCountByLanguage())
.hasSize(3)
.containsEntry("java", (long) nbProjects)
.containsEntry("cs", (long) nbProjects)
.containsEntry("js", (long) nbProjects);
assertThat(result.getNclocByLanguage())
.hasSize(3)
.containsEntry("java",(long) nbProjects * javaLocByProjects)
.containsEntry("cs",(long) nbProjects * csLocByProjects)
.containsEntry("js",(long) nbProjects * jsLocByProjects);
}
@Test
public void search_statistics_should_ignore_applications() {
es.putDocuments(TYPE_PROJECT_MEASURES,
// insert projects
newDoc(ComponentTesting.newPrivateProjectDto(), "lines", 10, "coverage", 80)
.setLanguages(Arrays.asList("java", "cs", "js"))
.setNclocLanguageDistributionFromMap(ImmutableMap.of("java", 200, "cs", 250, "js", 50)),
newDoc(ComponentTesting.newPrivateProjectDto(), "lines", 20, "coverage", 80)
.setLanguages(Arrays.asList("java", "python", "kotlin"))
.setNclocLanguageDistributionFromMap(ImmutableMap.of("java", 300, "python", 100, "kotlin", 404)),
// insert applications
newDoc(ComponentTesting.newApplication(), "lines", 1000, "coverage", 70)
.setLanguages(Arrays.asList("java", "python", "kotlin"))
.setNclocLanguageDistributionFromMap(ImmutableMap.of("java", 300, "python", 100, "kotlin", 404)),
newDoc(ComponentTesting.newApplication(), "lines", 20, "coverage", 80)
.setLanguages(Arrays.asList("java", "python", "kotlin"))
.setNclocLanguageDistributionFromMap(ImmutableMap.of("java", 300, "python", 100, "kotlin", 404)));
ProjectMeasuresStatistics result = underTest.searchSupportStatistics();
assertThat(result.getProjectCount()).isEqualTo(2);
assertThat(result.getProjectCountByLanguage()).containsOnly(
entry("java", 2L), entry("cs", 1L), entry("js", 1L), entry("python", 1L), entry("kotlin", 1L));
assertThat(result.getNclocByLanguage()).containsOnly(
entry("java", 500L), entry("cs", 250L), entry("js", 50L), entry("python", 100L), entry("kotlin", 404L));
}
@Test
public void search_statistics_should_count_0_if_no_projects() {
es.putDocuments(TYPE_PROJECT_MEASURES,
// insert applications
newDoc(ComponentTesting.newApplication(), "lines", 1000, "coverage", 70)
.setLanguages(Arrays.asList("java", "python", "kotlin"))
.setNclocLanguageDistributionFromMap(ImmutableMap.of("java", 300, "python", 100, "kotlin", 404)),
newDoc(ComponentTesting.newApplication(), "lines", 20, "coverage", 80)
.setLanguages(Arrays.asList("java", "python", "kotlin"))
.setNclocLanguageDistributionFromMap(ImmutableMap.of("java", 300, "python", 100, "kotlin", 404)));
ProjectMeasuresStatistics result = underTest.searchSupportStatistics();
assertThat(result.getProjectCount()).isZero();
assertThat(result.getProjectCountByLanguage()).isEmpty();
}
@Test
public void fail_if_page_size_greater_than_100() {
assertThatThrownBy(() -> underTest.searchTags("whatever", 1, 101))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Page size must be lower than or equals to 100");
}
@Test
public void fail_if_page_greater_than_20() {
assertThatThrownBy(() -> underTest.searchTags("whatever", 21, 100))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Page must be between 0 and 20");
}
private void index(ProjectMeasuresDoc... docs) {
es.putDocuments(TYPE_PROJECT_MEASURES, docs);
authorizationIndexer.allow(stream(docs).map(doc -> new IndexPermissions(doc.getId(), PROJECT).allowAnyone()).collect(toList()));
}
private void indexForUser(UserDto user, ProjectMeasuresDoc... docs) {
es.putDocuments(TYPE_PROJECT_MEASURES, docs);
authorizationIndexer.allow(stream(docs).map(doc -> new IndexPermissions(doc.getId(), PROJECT).addUserUuid(user.getUuid())).collect(toList()));
}
private void indexForGroup(GroupDto group, ProjectMeasuresDoc... docs) {
es.putDocuments(TYPE_PROJECT_MEASURES, docs);
authorizationIndexer.allow(stream(docs).map(doc -> new IndexPermissions(doc.getId(), PROJECT).addGroupUuid(group.getUuid())).collect(toList()));
}
private static ProjectMeasuresDoc newDoc(ComponentDto project) {
return new ProjectMeasuresDoc()
.setId(project.uuid())
.setKey(project.getKey())
.setName(project.name())
.setQualifier(project.qualifier());
}
private static ProjectMeasuresDoc newDoc() {
return newDoc(ComponentTesting.newPrivateProjectDto());
}
private static ProjectMeasuresDoc newDoc(ComponentDto project, String metric1, Object value1) {
return newDoc(project).setMeasures(newArrayList(newMeasure(metric1, value1)));
}
private static ProjectMeasuresDoc newDoc(ComponentDto project, String metric1, Object value1, String metric2, Object value2) {
return newDoc(project).setMeasures(newArrayList(newMeasure(metric1, value1), newMeasure(metric2, value2)));
}
private static ProjectMeasuresDoc newDoc(ComponentDto project, String metric1, Object value1, String metric2, Object value2, String metric3, Object value3) {
return newDoc(project).setMeasures(newArrayList(newMeasure(metric1, value1), newMeasure(metric2, value2), newMeasure(metric3, value3)));
}
private static Map<String, Object> newMeasure(String key, Object value) {
return ImmutableMap.of("key", key, "value", value);
}
private static ProjectMeasuresDoc newDocWithNoMeasure() {
return newDoc(ComponentTesting.newPrivateProjectDto());
}
private static ProjectMeasuresDoc newDoc(String metric1, Object value1) {
return newDoc(ComponentTesting.newPrivateProjectDto(), metric1, value1);
}
private static ProjectMeasuresDoc newDoc(String metric1, Object value1, String metric2, Object value2) {
return newDoc(ComponentTesting.newPrivateProjectDto(), metric1, value1, metric2, value2);
}
private static ProjectMeasuresDoc newDoc(String metric1, Object value1, String metric2, Object value2, String metric3, Object value3) {
return newDoc(ComponentTesting.newPrivateProjectDto(), metric1, value1, metric2, value2, metric3, value3);
}
private void assertResults(ProjectMeasuresQuery query, ComponentDto... expectedProjects) {
List<String> result = underTest.search(query, new SearchOptions()).getUuids();
assertThat(result).containsExactly(Arrays.stream(expectedProjects).map(ComponentDto::uuid).toArray(String[]::new));
}
private void assertNoResults(ProjectMeasuresQuery query) {
assertResults(query);
}
}
| 72,068 | 39.284516 | 180 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTextSearchTest.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.measure.index;
import com.google.common.collect.ImmutableMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.Facets;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion;
import org.sonar.server.permission.index.IndexPermissions;
import org.sonar.server.permission.index.PermissionIndexerTester;
import org.sonar.server.permission.index.WebAuthorizationTypeSupport;
import org.sonar.server.tester.UserSessionRule;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Lists.newArrayList;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.TYPE_PROJECT_MEASURES;
import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.GT;
import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.LT;
public class ProjectMeasuresIndexTextSearchTest {
private static final String NCLOC = "ncloc";
@Rule
public EsTester es = EsTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private ProjectMeasuresIndexer projectMeasureIndexer = new ProjectMeasuresIndexer(null, es.client());
private PermissionIndexerTester authorizationIndexer = new PermissionIndexerTester(es, projectMeasureIndexer);
private ProjectMeasuresIndex underTest = new ProjectMeasuresIndex(es.client(), new WebAuthorizationTypeSupport(userSession), System2.INSTANCE);
@Test
public void search_partial_text_from_project_key() {
index(
newDoc(newPrivateProjectDto().setUuid("struts").setName("Apache Struts").setKey("org.apache.commons.structs")),
newDoc(newPrivateProjectDto().setUuid("sonarqube").setName("SonarQube").setKey("org.sonar.sonarqube")));
assertTextQueryResults("apache", "struts");
assertTextQueryResults("apache.comm", "struts");
assertTextQueryResults("org.apache.commons.structs", "struts");
assertTextQueryResults("org.", "struts", "sonarqube");
}
@Test
public void match_exact_case_insensitive_name() {
index(
newDoc(newPrivateProjectDto().setUuid("struts").setName("Apache Struts")),
newDoc(newPrivateProjectDto().setUuid("sonarqube").setName("SonarQube")));
assertTextQueryResults("Apache Struts", "struts");
assertTextQueryResults("APACHE STRUTS", "struts");
assertTextQueryResults("APACHE struTS", "struts");
}
@Test
public void match_from_sub_name() {
index(newDoc(newPrivateProjectDto().setUuid("struts").setName("Apache Struts")));
assertTextQueryResults("truts", "struts");
assertTextQueryResults("pache", "struts");
assertTextQueryResults("apach", "struts");
assertTextQueryResults("che stru", "struts");
}
@Test
public void match_name_with_dot() {
index(newDoc(newPrivateProjectDto().setUuid("struts").setName("Apache.Struts")));
assertTextQueryResults("apache struts", "struts");
}
@Test
public void match_partial_name() {
index(newDoc(newPrivateProjectDto().setUuid("struts").setName("XstrutsxXjavax")));
assertTextQueryResults("struts java", "struts");
}
@Test
public void match_partial_name_prefix_word1() {
index(newDoc(newPrivateProjectDto().setUuid("struts").setName("MyStruts.java")));
assertTextQueryResults("struts java", "struts");
}
@Test
public void match_partial_name_suffix_word1() {
index(newDoc(newPrivateProjectDto().setUuid("struts").setName("StrutsObject.java")));
assertTextQueryResults("struts java", "struts");
}
@Test
public void match_partial_name_prefix_word2() {
index(newDoc(newPrivateProjectDto().setUuid("struts").setName("MyStruts.xjava")));
assertTextQueryResults("struts java", "struts");
}
@Test
public void match_partial_name_suffix_word2() {
index(newDoc(newPrivateProjectDto().setUuid("struts").setName("MyStrutsObject.xjavax")));
assertTextQueryResults("struts java", "struts");
}
@Test
public void match_subset_of_document_terms() {
index(newDoc(newPrivateProjectDto().setUuid("struts").setName("Some.Struts.Project.java.old")));
assertTextQueryResults("struts java", "struts");
}
@Test
public void match_partial_match_prefix_and_suffix_everywhere() {
index(newDoc(newPrivateProjectDto().setUuid("struts").setName("MyStruts.javax")));
assertTextQueryResults("struts java", "struts");
}
@Test
public void ignore_empty_words() {
index(newDoc(newPrivateProjectDto().setUuid("struts").setName("Struts")));
assertTextQueryResults(" struts \n \n\n", "struts");
}
@Test
public void match_name_from_prefix() {
index(newDoc(newPrivateProjectDto().setUuid("struts").setName("Apache Struts")));
assertTextQueryResults("apach", "struts");
assertTextQueryResults("ApA", "struts");
assertTextQueryResults("AP", "struts");
}
@Test
public void match_name_from_two_words() {
index(newDoc(newPrivateProjectDto().setUuid("project").setName("ApacheStrutsFoundation")));
assertTextQueryResults("apache struts", "project");
assertTextQueryResults("struts apache", "project");
// Only one word is matching
assertNoResults("apache plugin");
assertNoResults("project struts");
}
@Test
public void match_long_name() {
index(
newDoc(newPrivateProjectDto().setUuid("project1").setName("LongNameLongNameLongNameLongNameSonarQube")),
newDoc(newPrivateProjectDto().setUuid("project2").setName("LongNameLongNameLongNameLongNameSonarQubeX")));
assertTextQueryResults("LongNameLongNameLongNameLongNameSonarQube", "project1", "project2");
}
@Test
public void match_name_with_two_characters() {
index(newDoc(newPrivateProjectDto().setUuid("struts").setName("Apache Struts")));
assertTextQueryResults("st", "struts");
assertTextQueryResults("tr", "struts");
}
@Test
public void match_exact_case_insensitive_key() {
index(
newDoc(newPrivateProjectDto().setUuid("project1").setName("Windows").setKey("project1")),
newDoc(newPrivateProjectDto().setUuid("project2").setName("apachee").setKey("project2")));
assertTextQueryResults("project1", "project1");
assertTextQueryResults("PROJECT1", "project1");
assertTextQueryResults("pRoJecT1", "project1");
}
@Test
public void match_key_with_dot() {
index(
newDoc(newPrivateProjectDto().setUuid("sonarqube").setName("SonarQube").setKey("org.sonarqube")),
newDoc(newPrivateProjectDto().setUuid("sq").setName("SQ").setKey("sonarqube")));
assertTextQueryResults("org.sonarqube", "sonarqube");
assertNoResults("orgsonarqube");
assertNoResults("org-sonarqube");
assertNoResults("org:sonarqube");
assertNoResults("org sonarqube");
}
@Test
public void match_key_with_dash() {
index(
newDoc(newPrivateProjectDto().setUuid("sonarqube").setName("SonarQube").setKey("org-sonarqube")),
newDoc(newPrivateProjectDto().setUuid("sq").setName("SQ").setKey("sonarqube")));
assertTextQueryResults("org-sonarqube", "sonarqube");
assertNoResults("orgsonarqube");
assertNoResults("org.sonarqube");
assertNoResults("org:sonarqube");
assertNoResults("org sonarqube");
}
@Test
public void match_key_with_colon() {
index(
newDoc(newPrivateProjectDto().setUuid("sonarqube").setName("SonarQube").setKey("org:sonarqube")),
newDoc(newPrivateProjectDto().setUuid("sq").setName("SQ").setKey("sonarqube")));
assertTextQueryResults("org:sonarqube", "sonarqube");
assertNoResults("orgsonarqube");
assertNoResults("org-sonarqube");
assertNoResults("org_sonarqube");
assertNoResults("org sonarqube");
}
@Test
public void match_key_having_all_special_characters() {
index(newDoc(newPrivateProjectDto().setUuid("sonarqube").setName("SonarQube").setKey("org.sonarqube:sonar-sérvèr_ç")));
assertTextQueryResults("org.sonarqube:sonar-sérvèr_ç", "sonarqube");
}
@Test
public void facets_take_into_account_text_search() {
index(
// docs with ncloc<1K
newDoc(newPrivateProjectDto().setName("Windows").setKey("project1"), NCLOC, 0d),
newDoc(newPrivateProjectDto().setName("apachee").setKey("project2"), NCLOC, 999d),
// docs with ncloc>=1K and ncloc<10K
newDoc(newPrivateProjectDto().setName("Apache").setKey("project3"), NCLOC, 1_000d),
// docs with ncloc>=100K and ncloc<500K
newDoc(newPrivateProjectDto().setName("Apache Foundation").setKey("project4"), NCLOC, 100_000d));
assertNclocFacet(new ProjectMeasuresQuery().setQueryText("apache"), 1L, 1L, 0L, 1L, 0L);
assertNclocFacet(new ProjectMeasuresQuery().setQueryText("PAch"), 1L, 1L, 0L, 1L, 0L);
assertNclocFacet(new ProjectMeasuresQuery().setQueryText("apache foundation"), 0L, 0L, 0L, 1L, 0L);
assertNclocFacet(new ProjectMeasuresQuery().setQueryText("project3"), 0L, 1L, 0L, 0L, 0L);
assertNclocFacet(new ProjectMeasuresQuery().setQueryText("project"), 2L, 1L, 0L, 1L, 0L);
}
@Test
public void filter_by_metric_take_into_account_text_search() {
index(
newDoc(newPrivateProjectDto().setUuid("project1").setName("Windows").setKey("project1"), NCLOC, 30_000d),
newDoc(newPrivateProjectDto().setUuid("project2").setName("apachee").setKey("project2"), NCLOC, 40_000d),
newDoc(newPrivateProjectDto().setUuid("project3").setName("Apache").setKey("project3"), NCLOC, 50_000d),
newDoc(newPrivateProjectDto().setUuid("project4").setName("Apache").setKey("project4"), NCLOC, 60_000d));
assertResults(new ProjectMeasuresQuery().setQueryText("apache").addMetricCriterion(MetricCriterion.create(NCLOC, GT, 20_000d)), "project3", "project4", "project2");
assertResults(new ProjectMeasuresQuery().setQueryText("apache").addMetricCriterion(MetricCriterion.create(NCLOC, LT, 55_000d)), "project3", "project2");
assertResults(new ProjectMeasuresQuery().setQueryText("PAC").addMetricCriterion(MetricCriterion.create(NCLOC, LT, 55_000d)), "project3", "project2");
assertResults(new ProjectMeasuresQuery().setQueryText("apachee").addMetricCriterion(MetricCriterion.create(NCLOC, GT, 30_000d)), "project2");
assertResults(new ProjectMeasuresQuery().setQueryText("unknown").addMetricCriterion(MetricCriterion.create(NCLOC, GT, 20_000d)));
}
private void index(ProjectMeasuresDoc... docs) {
es.putDocuments(TYPE_PROJECT_MEASURES, docs);
authorizationIndexer.allow(stream(docs).map(doc -> new IndexPermissions(doc.getId(), PROJECT).allowAnyone()).collect(toList()));
}
private static ProjectMeasuresDoc newDoc(ComponentDto project) {
return new ProjectMeasuresDoc()
.setId(project.uuid())
.setKey(project.getKey())
.setName(project.name())
.setQualifier(project.qualifier());
}
private static ProjectMeasuresDoc newDoc(ComponentDto project, String metric1, Object value1) {
return newDoc(project).setMeasures(newArrayList(newMeasure(metric1, value1)));
}
private static Map<String, Object> newMeasure(String key, Object value) {
return ImmutableMap.of("key", key, "value", value);
}
private void assertResults(ProjectMeasuresQuery query, String... expectedProjectUuids) {
List<String> result = underTest.search(query, new SearchOptions()).getUuids();
assertThat(result).containsExactly(expectedProjectUuids);
}
private void assertTextQueryResults(String queryText, String... expectedProjectUuids) {
assertResults(new ProjectMeasuresQuery().setQueryText(queryText), expectedProjectUuids);
}
private void assertNoResults(String queryText) {
assertTextQueryResults(queryText);
}
private void assertNclocFacet(ProjectMeasuresQuery query, Long... facetExpectedValues) {
checkArgument(facetExpectedValues.length == 5, "5 facet values is required");
Facets facets = underTest.search(query, new SearchOptions().addFacets(NCLOC)).getFacets();
assertThat(facets.get(NCLOC)).containsExactly(
entry("*-1000.0", facetExpectedValues[0]),
entry("1000.0-10000.0", facetExpectedValues[1]),
entry("10000.0-100000.0", facetExpectedValues[2]),
entry("100000.0-500000.0", facetExpectedValues[3]),
entry("500000.0-*", facetExpectedValues[4]));
}
}
| 13,584 | 40.042296 | 168 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresQueryTest.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.measure.index;
import org.junit.Test;
import org.sonar.api.measures.Metric.Level;
import org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion;
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.sonar.api.measures.Metric.Level.OK;
import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.EQ;
public class ProjectMeasuresQueryTest {
private ProjectMeasuresQuery underTest = new ProjectMeasuresQuery();
@Test
public void empty_query() {
assertThat(underTest.getMetricCriteria()).isEmpty();
assertThat(underTest.getQualityGateStatus()).isEmpty();
}
@Test
public void add_metric_criterion() {
underTest.addMetricCriterion(MetricCriterion.create("coverage", EQ, 10d));
assertThat(underTest.getMetricCriteria())
.extracting(MetricCriterion::getMetricKey, MetricCriterion::getOperator, MetricCriterion::getValue)
.containsOnly(tuple("coverage", EQ, 10d));
}
@Test
public void isNoData_returns_true_when_no_data() {
underTest.addMetricCriterion(MetricCriterion.createNoData("coverage"));
assertThat(underTest.getMetricCriteria())
.extracting(MetricCriterion::getMetricKey, MetricCriterion::isNoData)
.containsOnly(tuple("coverage", true));
}
@Test
public void isNoData_returns_false_when_data_exists() {
underTest.addMetricCriterion(MetricCriterion.create("coverage", EQ, 10d));
assertThat(underTest.getMetricCriteria())
.extracting(MetricCriterion::getMetricKey, MetricCriterion::getOperator, MetricCriterion::isNoData)
.containsOnly(tuple("coverage", EQ, false));
}
@Test
public void set_quality_gate_status() {
underTest.setQualityGateStatus(OK);
assertThat(underTest.getQualityGateStatus()).contains(Level.OK);
}
@Test
public void default_sort_is_by_name() {
assertThat(underTest.getSort()).isEqualTo("name");
}
@Test
public void fail_to_set_null_sort() {
assertThatThrownBy(() -> underTest.setSort(null))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("Sort cannot be null");
}
@Test
public void fail_to_get_value_when_no_data() {
assertThatThrownBy(() -> MetricCriterion.createNoData("coverage").getValue())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("The criterion for metric coverage has no data");
}
@Test
public void fail_to_get_operator_when_no_data() {
assertThatThrownBy(() -> MetricCriterion.createNoData("coverage").getOperator())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("The criterion for metric coverage has no data");
}
}
| 3,639 | 34.686275 | 105 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectsEsModuleTest.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.measure.index;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class ProjectsEsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new ProjectsEsModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(3);
}
}
| 1,270 | 35.314286 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/permission/index/FooIndex.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.permission.index;
import java.util.Arrays;
import java.util.List;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.sonar.server.es.EsClient;
import static org.sonar.server.permission.index.FooIndexDefinition.DESCRIPTOR;
public class FooIndex {
private final EsClient esClient;
private final WebAuthorizationTypeSupport authorizationTypeSupport;
public FooIndex(EsClient esClient, WebAuthorizationTypeSupport authorizationTypeSupport) {
this.esClient = esClient;
this.authorizationTypeSupport = authorizationTypeSupport;
}
public boolean hasAccessToProject(String projectUuid) {
SearchHits hits = esClient.search(EsClient.prepareSearch(DESCRIPTOR.getName())
.source(new SearchSourceBuilder().query(QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery(FooIndexDefinition.FIELD_PROJECT_UUID, projectUuid))
.filter(authorizationTypeSupport.createQueryFilter()))))
.getHits();
List<String> names = Arrays.stream(hits.getHits())
.map(h -> h.getSourceAsMap().get(FooIndexDefinition.FIELD_NAME).toString())
.toList();
return names.size() == 2 && names.contains("bar") && names.contains("baz");
}
}
| 2,164 | 39.849057 | 92 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/permission/index/FooIndexer.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.permission.index;
import java.util.Optional;
import java.util.Set;
import org.elasticsearch.action.index.IndexRequest;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.server.es.AnalysisIndexer;
import org.sonar.server.es.BaseDoc;
import org.sonar.server.es.EsClient;
import static org.sonar.server.permission.index.FooIndexDefinition.TYPE_FOO;
public class FooIndexer implements AnalysisIndexer, NeedAuthorizationIndexer {
private static final AuthorizationScope AUTHORIZATION_SCOPE = new AuthorizationScope(TYPE_FOO, p -> true);
private final EsClient esClient;
private final DbClient dbClient;
public FooIndexer(EsClient esClient, DbClient dbClient) {
this.esClient = esClient;
this.dbClient = dbClient;
}
@Override
public AuthorizationScope getAuthorizationScope() {
return AUTHORIZATION_SCOPE;
}
@Override
public void indexOnAnalysis(String branchUuid) {
indexOnAnalysis(branchUuid, Set.of());
}
@Override
public void indexOnAnalysis(String branchUuid, Set<String> unchangedComponentUuids) {
try(DbSession dbSession = dbClient.openSession(true)){
Optional<BranchDto> branchDto = dbClient.branchDao().selectByUuid(dbSession, branchUuid);
if (branchDto.isEmpty()) {
//For portfolio, adding branchUuid directly
addToIndex(branchUuid, "bar");
addToIndex(branchUuid, "baz");
}else{
addToIndex(branchDto.get().getProjectUuid(), "bar");
addToIndex(branchDto.get().getProjectUuid(), "baz");
}
}
}
private void addToIndex(String projectUuid, String name) {
FooDoc fooDoc = new FooDoc(projectUuid, name);
esClient.index(new IndexRequest(TYPE_FOO.getMainType().getIndex().getName())
.type(TYPE_FOO.getMainType().getType())
.id(fooDoc.getId())
.routing(fooDoc.getRouting().orElse(null))
.source(fooDoc.getFields()));
}
private static final class FooDoc extends BaseDoc {
private final String projectUuid;
private final String name;
private FooDoc(String projectUuid, String name) {
super(TYPE_FOO);
this.projectUuid = projectUuid;
this.name = name;
setField(FooIndexDefinition.FIELD_PROJECT_UUID, projectUuid);
setField(FooIndexDefinition.FIELD_NAME, name);
setParent(AuthorizationDoc.idOf(projectUuid));
}
@Override
public String getId() {
return projectUuid + "_" + name;
}
}
}
| 3,353 | 31.882353 | 108 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/permission/index/PermissionIndexerTest.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.permission.index;
import java.util.Collection;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.ProjectData;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.es.EsQueueDto;
import org.sonar.db.portfolio.PortfolioDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.IndexType;
import org.sonar.server.es.IndexType.IndexMainType;
import org.sonar.server.es.Indexers.EntityEvent;
import org.sonar.server.es.IndexingResult;
import org.sonar.server.tester.UserSessionRule;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.api.web.UserRole.ADMIN;
import static org.sonar.api.web.UserRole.USER;
import static org.sonar.server.es.Indexers.EntityEvent.PERMISSION_CHANGE;
import static org.sonar.server.permission.index.IndexAuthorizationConstants.TYPE_AUTHORIZATION;
public class PermissionIndexerTest {
private static final IndexMainType INDEX_TYPE_FOO_AUTH = IndexType.main(FooIndexDefinition.DESCRIPTOR, TYPE_AUTHORIZATION);
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public EsTester es = EsTester.createCustom(new FooIndexDefinition());
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private FooIndex fooIndex = new FooIndex(es.client(), new WebAuthorizationTypeSupport(userSession));
private FooIndexer fooIndexer = new FooIndexer(es.client(), db.getDbClient());
private PermissionIndexer underTest = new PermissionIndexer(db.getDbClient(), es.client(), fooIndexer);
@Test
public void indexOnStartup_grants_access_to_any_user_and_to_group_Anyone_on_public_projects() {
ProjectDto project = createAndIndexPublicProject();
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
indexOnStartup();
verifyAnyoneAuthorized(project);
verifyAuthorized(project, user1);
verifyAuthorized(project, user2);
}
@Test
public void indexAll_grants_access_to_any_user_and_to_group_Anyone_on_public_projects() {
ProjectDto project = createAndIndexPublicProject();
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
underTest.indexAll(underTest.getIndexTypes());
verifyAnyoneAuthorized(project);
verifyAuthorized(project, user1);
verifyAuthorized(project, user2);
}
@Test
public void deletion_resilience_will_deindex_projects() {
ProjectDto project1 = createUnindexedPublicProject();
ProjectDto project2 = createUnindexedPublicProject();
// UserDto user1 = db.users().insertUser();
indexOnStartup();
assertThat(es.countDocuments(INDEX_TYPE_FOO_AUTH)).isEqualTo(2);
// Simulate a indexation issue
db.getDbClient().purgeDao().deleteProject(db.getSession(), project1.getUuid(), PROJECT, project1.getName(), project1.getKey());
underTest.prepareForRecoveryOnEntityEvent(db.getSession(), asList(project1.getUuid()), EntityEvent.DELETION);
assertThat(db.countRowsOfTable(db.getSession(), "es_queue")).isOne();
Collection<EsQueueDto> esQueueDtos = db.getDbClient().esQueueDao().selectForRecovery(db.getSession(), Long.MAX_VALUE, 2);
underTest.index(db.getSession(), esQueueDtos);
assertThat(db.countRowsOfTable(db.getSession(), "es_queue")).isZero();
assertThat(es.countDocuments(INDEX_TYPE_FOO_AUTH)).isOne();
}
@Test
public void indexOnStartup_grants_access_to_user() {
ProjectDto project = createAndIndexPrivateProject();
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
db.users().insertProjectPermissionOnUser(user1, USER, project);
db.users().insertProjectPermissionOnUser(user2, ADMIN, project);
indexOnStartup();
// anonymous
verifyAnyoneNotAuthorized(project);
// user1 has access
verifyAuthorized(project, user1);
// user2 has not access (only USER permission is accepted)
verifyNotAuthorized(project, user2);
}
@Test
public void indexOnStartup_grants_access_to_group_on_private_project() {
ProjectDto project = createAndIndexPrivateProject();
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
UserDto user3 = db.users().insertUser();
GroupDto group1 = db.users().insertGroup();
GroupDto group2 = db.users().insertGroup();
db.users().insertEntityPermissionOnGroup(group1, USER, project);
db.users().insertEntityPermissionOnGroup(group2, ADMIN, project);
indexOnStartup();
// anonymous
verifyAnyoneNotAuthorized(project);
// group1 has access
verifyAuthorized(project, user1, group1);
// group2 has not access (only USER permission is accepted)
verifyNotAuthorized(project, user2, group2);
// user3 is not in any group
verifyNotAuthorized(project, user3);
}
@Test
public void indexOnStartup_grants_access_to_user_and_group() {
ProjectDto project = createAndIndexPrivateProject();
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
GroupDto group = db.users().insertGroup();
db.users().insertMember(group, user2);
db.users().insertProjectPermissionOnUser(user1, USER, project);
db.users().insertEntityPermissionOnGroup(group, USER, project);
indexOnStartup();
// anonymous
verifyAnyoneNotAuthorized(project);
// has direct access
verifyAuthorized(project, user1);
// has access through group
verifyAuthorized(project, user1, group);
// no access
verifyNotAuthorized(project, user2);
}
@Test
public void indexOnStartup_does_not_grant_access_to_anybody_on_private_project() {
ProjectDto project = createAndIndexPrivateProject();
UserDto user = db.users().insertUser();
GroupDto group = db.users().insertGroup();
indexOnStartup();
verifyAnyoneNotAuthorized(project);
verifyNotAuthorized(project, user);
verifyNotAuthorized(project, user, group);
}
@Test
public void indexOnStartup_grants_access_to_anybody_on_public_project() {
ProjectDto project = createAndIndexPublicProject();
UserDto user = db.users().insertUser();
GroupDto group = db.users().insertGroup();
indexOnStartup();
verifyAnyoneAuthorized(project);
verifyAuthorized(project, user);
verifyAuthorized(project, user, group);
}
@Test
public void indexOnStartup_grants_access_to_anybody_on_view() {
PortfolioDto view = createAndIndexPortfolio();
UserDto user = db.users().insertUser();
GroupDto group = db.users().insertGroup();
indexOnStartup();
verifyAnyoneAuthorized(view);
verifyAuthorized(view, user);
verifyAuthorized(view, user, group);
}
@Test
public void indexOnStartup_grants_access_on_many_projects() {
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
ProjectDto project = null;
for (int i = 0; i < 10; i++) {
project = createAndIndexPrivateProject();
db.users().insertProjectPermissionOnUser(user1, USER, project);
}
indexOnStartup();
verifyAnyoneNotAuthorized(project);
verifyAuthorized(project, user1);
verifyNotAuthorized(project, user2);
}
@Test
public void public_projects_are_visible_to_anybody() {
ProjectDto projectOnOrg1 = createAndIndexPublicProject();
UserDto user = db.users().insertUser();
indexOnStartup();
verifyAnyoneAuthorized(projectOnOrg1);
verifyAuthorized(projectOnOrg1, user);
}
@Test
public void permissions_are_not_updated_on_project_tags_update() {
ProjectDto project = createAndIndexPublicProject();
indexPermissions(project, EntityEvent.PROJECT_TAGS_UPDATE);
assertThatAuthIndexHasSize(0);
verifyAnyoneNotAuthorized(project);
}
@Test
public void permissions_are_not_updated_on_project_key_update() {
ProjectDto project = createAndIndexPublicProject();
indexPermissions(project, EntityEvent.PROJECT_TAGS_UPDATE);
assertThatAuthIndexHasSize(0);
verifyAnyoneNotAuthorized(project);
}
@Test
public void index_permissions_on_project_creation() {
ProjectDto project = createAndIndexPrivateProject();
UserDto user = db.users().insertUser();
db.users().insertProjectPermissionOnUser(user, USER, project);
indexPermissions(project, EntityEvent.CREATION);
assertThatAuthIndexHasSize(1);
verifyAuthorized(project, user);
}
@Test
public void index_permissions_on_permission_change() {
ProjectDto project = createAndIndexPrivateProject();
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
db.users().insertProjectPermissionOnUser(user1, USER, project);
indexPermissions(project, EntityEvent.CREATION);
verifyAuthorized(project, user1);
verifyNotAuthorized(project, user2);
db.users().insertProjectPermissionOnUser(user2, USER, project);
indexPermissions(project, PERMISSION_CHANGE);
verifyAuthorized(project, user1);
verifyAuthorized(project, user1);
}
@Test
public void delete_permissions_on_project_deletion() {
ProjectDto project = createAndIndexPrivateProject();
UserDto user = db.users().insertUser();
db.users().insertProjectPermissionOnUser(user, USER, project);
indexPermissions(project, EntityEvent.CREATION);
verifyAuthorized(project, user);
db.getDbClient().purgeDao().deleteProject(db.getSession(), project.getUuid(), PROJECT, project.getUuid(), project.getKey());
indexPermissions(project, EntityEvent.DELETION);
verifyNotAuthorized(project, user);
assertThatAuthIndexHasSize(0);
}
@Test
public void errors_during_indexing_are_recovered() {
ProjectDto project = createAndIndexPublicProject();
es.lockWrites(INDEX_TYPE_FOO_AUTH);
IndexingResult result = indexPermissions(project, PERMISSION_CHANGE);
assertThat(result.getTotal()).isOne();
assertThat(result.getFailures()).isOne();
// index is still read-only, fail to recover
result = recover();
assertThat(result.getTotal()).isOne();
assertThat(result.getFailures()).isOne();
assertThatAuthIndexHasSize(0);
assertThatEsQueueTableHasSize(1);
es.unlockWrites(INDEX_TYPE_FOO_AUTH);
result = recover();
assertThat(result.getTotal()).isOne();
assertThat(result.getFailures()).isZero();
verifyAnyoneAuthorized(project);
assertThatEsQueueTableHasSize(0);
}
private void assertThatAuthIndexHasSize(int expectedSize) {
assertThat(es.countDocuments(FooIndexDefinition.TYPE_AUTHORIZATION)).isEqualTo(expectedSize);
}
private void indexOnStartup() {
underTest.indexOnStartup(underTest.getIndexTypes());
}
private void verifyAuthorized(EntityDto entity, UserDto user) {
logIn(user);
verifyAuthorized(entity, true);
}
private void verifyAuthorized(EntityDto entity, UserDto user, GroupDto group) {
logIn(user).setGroups(group);
verifyAuthorized(entity, true);
}
private void verifyNotAuthorized(EntityDto entity, UserDto user) {
logIn(user);
verifyAuthorized(entity, false);
}
private void verifyNotAuthorized(EntityDto entity, UserDto user, GroupDto group) {
logIn(user).setGroups(group);
verifyAuthorized(entity, false);
}
private void verifyAnyoneAuthorized(EntityDto entity) {
userSession.anonymous();
verifyAuthorized(entity, true);
}
private void verifyAnyoneNotAuthorized(EntityDto entity) {
userSession.anonymous();
verifyAuthorized(entity, false);
}
private void verifyAuthorized(EntityDto entity, boolean expectedAccess) {
assertThat(fooIndex.hasAccessToProject(entity.getUuid())).isEqualTo(expectedAccess);
}
private UserSessionRule logIn(UserDto u) {
userSession.logIn(u);
return userSession;
}
private IndexingResult indexPermissions(EntityDto entity, EntityEvent cause) {
DbSession dbSession = db.getSession();
Collection<EsQueueDto> items = underTest.prepareForRecoveryOnEntityEvent(dbSession, singletonList(entity.getUuid()), cause);
dbSession.commit();
return underTest.index(dbSession, items);
}
private ProjectDto createUnindexedPublicProject() {
return db.components().insertPublicProject().getProjectDto();
}
private ProjectDto createAndIndexPrivateProject() {
ProjectData project = db.components().insertPrivateProject();
fooIndexer.indexOnAnalysis(project.getMainBranchDto().getUuid());
return project.getProjectDto();
}
private ProjectDto createAndIndexPublicProject() {
ProjectData project = db.components().insertPublicProject();
fooIndexer.indexOnAnalysis(project.getMainBranchDto().getUuid());
return project.getProjectDto();
}
private PortfolioDto createAndIndexPortfolio() {
PortfolioDto view = db.components().insertPublicPortfolioDto();
fooIndexer.indexOnAnalysis(view.getUuid());
return view;
}
private IndexingResult recover() {
Collection<EsQueueDto> items = db.getDbClient().esQueueDao().selectForRecovery(db.getSession(), System.currentTimeMillis() + 1_000L, 10);
return underTest.index(db.getSession(), items);
}
private void assertThatEsQueueTableHasSize(int expectedSize) {
assertThat(db.countRowsOfTable("es_queue")).isEqualTo(expectedSize);
}
}
| 14,429 | 32.952941 | 141 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/test/java/org/sonar/server/permission/index/WebAuthorizationTypeSupportTest.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.permission.index;
import org.elasticsearch.join.query.HasParentQueryBuilder;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.GroupTesting;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTesting;
import org.sonar.server.tester.UserSessionRule;
import static org.sonar.test.JsonAssert.assertJson;
public class WebAuthorizationTypeSupportTest {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private WebAuthorizationTypeSupport underTest = new WebAuthorizationTypeSupport(userSession);
@Test
public void createQueryFilter_sets_filter_on_anyone_group_if_user_is_anonymous() {
userSession.anonymous();
HasParentQueryBuilder filter = (HasParentQueryBuilder) underTest.createQueryFilter();
assertJson(filter.toString()).isSimilarTo("{" +
" \"has_parent\" : {" +
" \"query\" : {" +
" \"bool\" : {" +
" \"filter\" : [{" +
" \"bool\" : {" +
" \"should\" : [{" +
" \"term\" : {" +
" \"auth_allowAnyone\" : {\"value\": true}" +
" }" +
" }]" +
" }" +
" }]" +
" }" +
" }," +
" \"parent_type\" : \"auth\"" +
" }" +
"}");
}
@Test
public void createQueryFilter_sets_filter_on_anyone_and_user_id_if_user_is_logged_in_but_has_no_groups() {
UserDto userDto = UserTesting.newUserDto();
userSession.logIn(userDto);
HasParentQueryBuilder filter = (HasParentQueryBuilder) underTest.createQueryFilter();
assertJson(filter.toString()).isSimilarTo("{" +
" \"has_parent\": {" +
" \"query\": {" +
" \"bool\": {" +
" \"filter\": [{" +
" \"bool\": {" +
" \"should\": [" +
" {" +
" \"term\": {" +
" \"auth_allowAnyone\": {\"value\": true}" +
" }" +
" }," +
" {" +
" \"term\": {" +
" \"auth_userIds\": {\"value\": \"" + userDto.getUuid() + "\"}" +
" }" +
" }" +
" ]" +
" }" +
" }]" +
" }" +
" }," +
" \"parent_type\": \"auth\"" +
" }" +
"}");
}
@Test
public void createQueryFilter_sets_filter_on_anyone_and_user_id_and_group_ids_if_user_is_logged_in_and_has_groups() {
GroupDto group1 = GroupTesting.newGroupDto().setUuid("10");
GroupDto group2 = GroupTesting.newGroupDto().setUuid("11");
UserDto userDto = UserTesting.newUserDto();
userSession.logIn(userDto).setGroups(group1, group2);
HasParentQueryBuilder filter = (HasParentQueryBuilder) underTest.createQueryFilter();
assertJson(filter.toString()).isSimilarTo("{" +
" \"has_parent\": {" +
" \"query\": {" +
" \"bool\": {" +
" \"filter\": [{" +
" \"bool\": {" +
" \"should\": [" +
" {" +
" \"term\": {" +
" \"auth_allowAnyone\": {\"value\": true}" +
" }" +
" }," +
" {" +
" \"term\": {" +
" \"auth_userIds\": {\"value\": \"" + userDto.getUuid() + "\"}" +
" }" +
" }," +
" {" +
" \"term\": {" +
" \"auth_groupIds\": {\"value\": \"10\"}" +
" }" +
" }," +
" {" +
" \"term\": {" +
" \"auth_groupIds\": {\"value\": \"11\"}" +
" }" +
" }" +
" ]" +
" }" +
" }]" +
" }" +
" }," +
" \"parent_type\": \"auth\"" +
" }" +
"}");
}
}
| 4,953 | 32.931507 | 119 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/testFixtures/java/org/sonar/server/permission/index/FooIndexDefinition.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.permission.index;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.es.Index;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.IndexType;
import org.sonar.server.es.newindex.NewAuthorizedIndex;
import static org.sonar.server.es.newindex.SettingsConfiguration.MANUAL_REFRESH_INTERVAL;
import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder;
public class FooIndexDefinition implements IndexDefinition {
public static final Index DESCRIPTOR = Index.withRelations("foos");
public static final String FOO_TYPE = "foo";
public static final IndexType.IndexMainType TYPE_AUTHORIZATION = IndexType.main(DESCRIPTOR, IndexAuthorizationConstants.TYPE_AUTHORIZATION);
public static final IndexType.IndexRelationType TYPE_FOO = IndexType.relation(TYPE_AUTHORIZATION, FOO_TYPE);
public static final String FIELD_NAME = "name";
public static final String FIELD_PROJECT_UUID = "projectUuid";
@Override
public void define(IndexDefinitionContext context) {
NewAuthorizedIndex newIndex = context.createWithAuthorization(
DESCRIPTOR,
newBuilder(new MapSettings().asConfig())
.setRefreshInterval(MANUAL_REFRESH_INTERVAL)
.build());
newIndex.createTypeMapping(TYPE_FOO)
.keywordFieldBuilder(FIELD_NAME).build()
.keywordFieldBuilder(FIELD_PROJECT_UUID).build();
}
}
| 2,249 | 41.45283 | 142 | java |
sonarqube | sonarqube-master/server/sonar-webserver-es/src/testFixtures/java/org/sonar/server/permission/index/PermissionIndexerTester.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.permission.index;
import java.util.List;
import java.util.stream.Stream;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import static java.util.Arrays.stream;
public class PermissionIndexerTester {
private final PermissionIndexer permissionIndexer;
public PermissionIndexerTester(EsTester esTester, NeedAuthorizationIndexer indexer, NeedAuthorizationIndexer... others) {
NeedAuthorizationIndexer[] indexers = Stream.concat(Stream.of(indexer), stream(others)).toArray(NeedAuthorizationIndexer[]::new);
this.permissionIndexer = new PermissionIndexer(null, esTester.client(), indexers);
}
public PermissionIndexerTester allowOnlyAnyone(ComponentDto... projects) {
return allow(stream(projects).map(project -> new IndexPermissions(project.uuid(), project.qualifier()).allowAnyone()).toList());
}
public PermissionIndexerTester allowOnlyAnyone(EntityDto... entities) {
return allow(stream(entities).map(entity -> new IndexPermissions(entity.getUuid(), entity.getQualifier()).allowAnyone()).toList());
}
public PermissionIndexerTester allowOnlyUser(ComponentDto project, UserDto user) {
IndexPermissions dto = new IndexPermissions(project.uuid(), project.qualifier())
.addUserUuid(user.getUuid());
return allow(dto);
}
public PermissionIndexerTester allowOnlyUser(EntityDto entityDto, UserDto user) {
IndexPermissions dto = new IndexPermissions(entityDto.getUuid(), entityDto.getQualifier())
.addUserUuid(user.getUuid());
return allow(dto);
}
public PermissionIndexerTester allowOnlyGroup(ComponentDto project, GroupDto group) {
IndexPermissions dto = new IndexPermissions(project.uuid(), project.qualifier())
.addGroupUuid(group.getUuid());
return allow(dto);
}
public PermissionIndexerTester allowOnlyGroup(EntityDto entityDto, GroupDto group) {
IndexPermissions dto = new IndexPermissions(entityDto.getUuid(), entityDto.getQualifier())
.addGroupUuid(group.getUuid());
return allow(dto);
}
public PermissionIndexerTester allow(IndexPermissions... indexPermissions) {
return allow(stream(indexPermissions).toList());
}
public PermissionIndexerTester allow(List<IndexPermissions> indexPermissions) {
permissionIndexer.index(indexPermissions);
return this;
}
}
| 3,298 | 39.231707 | 135 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/ComputeEngineMetricStatusTask.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.sonar.api.config.Configuration;
import org.sonar.server.app.ProcessCommandWrapper;
public class ComputeEngineMetricStatusTask implements MonitoringTask {
private static final String DELAY_IN_MILISECONDS_PROPERTY = "sonar.server.monitoring.other.initial.delay";
private static final String PERIOD_IN_MILISECONDS_PROPERTY = "sonar.server.monitoring.other.period";
private final ServerMonitoringMetrics serverMonitoringMetrics;
private final ProcessCommandWrapper processCommandWrapper;
private final Configuration config;
public ComputeEngineMetricStatusTask(ServerMonitoringMetrics serverMonitoringMetrics,
ProcessCommandWrapper processCommandWrapper, Configuration configuration) {
this.serverMonitoringMetrics = serverMonitoringMetrics;
this.processCommandWrapper = processCommandWrapper;
this.config = configuration;
}
@Override
public void run() {
if (processCommandWrapper.isCeOperational()) {
serverMonitoringMetrics.setComputeEngineStatusToGreen();
} else {
serverMonitoringMetrics.setComputeEngineStatusToRed();
}
}
@Override
public long getDelay() {
return config.getLong(DELAY_IN_MILISECONDS_PROPERTY).orElse(10_000L);
}
@Override
public long getPeriod() {
return config.getLong(PERIOD_IN_MILISECONDS_PROPERTY).orElse(10_000L);
}
}
| 2,221 | 35.42623 | 108 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/ElasticSearchMetricTask.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.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.sonar.api.config.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.response.NodeStats;
import org.sonar.server.es.response.NodeStatsResponse;
public class ElasticSearchMetricTask implements MonitoringTask {
private static final Logger LOG = LoggerFactory.getLogger(ElasticSearchMetricTask.class);
private static final String DELAY_IN_MILISECONDS_PROPERTY = "sonar.server.monitoring.es.initial.delay";
private static final String PERIOD_IN_MILISECONDS_PROPERTY = "sonar.server.monitoring.es.period";
private final ServerMonitoringMetrics serverMonitoringMetrics;
private final EsClient esClient;
private final Configuration config;
public ElasticSearchMetricTask(ServerMonitoringMetrics serverMonitoringMetrics, EsClient esClient, Configuration configuration) {
this.serverMonitoringMetrics = serverMonitoringMetrics;
this.esClient = esClient;
config = configuration;
}
@Override
public void run() {
updateElasticSearchHealthStatus();
updateFileSystemMetrics();
}
private void updateElasticSearchHealthStatus() {
try {
ClusterHealthStatus esStatus = esClient.clusterHealth(new ClusterHealthRequest()).getStatus();
if (esStatus == null) {
serverMonitoringMetrics.setElasticSearchStatusToRed();
} else {
switch (esStatus) {
case GREEN, YELLOW:
serverMonitoringMetrics.setElasticSearchStatusToGreen();
break;
case RED:
serverMonitoringMetrics.setElasticSearchStatusToRed();
break;
}
}
} catch (Exception e) {
LOG.error("Failed to query ES status", e);
serverMonitoringMetrics.setElasticSearchStatusToRed();
}
}
private void updateFileSystemMetrics() {
try {
NodeStatsResponse nodeStatsResponse = esClient.nodesStats();
if (nodeStatsResponse.getNodeStats().isEmpty()) {
LOG.error("Failed to query ES status, no nodes stats returned by elasticsearch API");
} else {
for (NodeStats nodeStat : nodeStatsResponse.getNodeStats()) {
serverMonitoringMetrics.setElasticSearchDiskSpaceFreeBytes(nodeStat.getName(), nodeStat.getDiskAvailableBytes());
serverMonitoringMetrics.setElasticSearchDiskSpaceTotalBytes(nodeStat.getName(), nodeStat.getDiskTotalBytes());
}
}
} catch (Exception e) {
LOG.error("Failed to query ES status", e);
}
}
@Override
public long getDelay() {
return config.getLong(DELAY_IN_MILISECONDS_PROPERTY).orElse(10_000L);
}
@Override
public long getPeriod() {
return config.getLong(PERIOD_IN_MILISECONDS_PROPERTY).orElse(10_000L);
}
}
| 3,760 | 36.237624 | 131 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/MainCollector.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 com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.sonar.api.Startable;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class MainCollector implements Startable {
private final MonitoringTask[] monitoringTasks;
private ScheduledExecutorService scheduledExecutorService;
public MainCollector(MonitoringTask[] monitoringTasks) {
this.monitoringTasks = monitoringTasks;
}
@Override
public void start() {
this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(getClass().getCanonicalName() + "-thread-%d")
.build());
for (MonitoringTask task : monitoringTasks) {
scheduledExecutorService.scheduleWithFixedDelay(task, task.getDelay(), task.getPeriod(), MILLISECONDS);
}
}
@Override
public void stop() {
scheduledExecutorService.shutdown();
}
@VisibleForTesting
ScheduledExecutorService getScheduledExecutorService() {
return scheduledExecutorService;
}
}
| 2,093 | 33.327869 | 109 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/MonitoringTask.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;
public interface MonitoringTask extends Runnable {
long getDelay();
long getPeriod();
}
| 975 | 33.857143 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/ServerMonitoringMetrics.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.Gauge;
import io.prometheus.client.Summary;
import org.sonar.api.server.ServerSide;
@ServerSide
public class ServerMonitoringMetrics {
public static final int UP_STATUS = 1;
public static final int DOWN_STATUS = 0;
private final Gauge githubHealthIntegrationStatus;
private final Gauge gitlabHealthIntegrationStatus;
private final Gauge bitbucketHealthIntegrationStatus;
private final Gauge azureHealthIntegrationStatus;
private final Gauge computeEngineGauge;
private final Gauge elasticsearchGauge;
private final Gauge cePendingTasksTotal;
private final Summary ceTasksRunningDuration;
private final Gauge elasticsearchDiskSpaceFreeBytesGauge;
private final Gauge elasticSearchDiskSpaceTotalBytes;
private final Gauge licenseDaysBeforeExpiration;
private final Gauge linesOfCodeRemaining;
private final Gauge linesOfCodeAnalyzed;
private final Gauge webUptimeMinutes;
private final Gauge numberOfConnectedSonarLintClients;
public ServerMonitoringMetrics() {
githubHealthIntegrationStatus = Gauge.build()
.name("sonarqube_health_integration_github_status")
.help("Tells whether SonarQube instance has configured GitHub integration and its status is green. 1 for green, 0 otherwise .")
.register();
gitlabHealthIntegrationStatus = Gauge.build()
.name("sonarqube_health_integration_gitlab_status")
.help("Tells whether SonarQube instance has configured GitLab integration and its status is green. 1 for green, 0 otherwise .")
.register();
bitbucketHealthIntegrationStatus = Gauge.build()
.name("sonarqube_health_integration_bitbucket_status")
.help("Tells whether SonarQube instance has configured BitBucket integration and its status is green. 1 for green, 0 otherwise .")
.register();
azureHealthIntegrationStatus = Gauge.build()
.name("sonarqube_health_integration_azuredevops_status")
.help("Tells whether SonarQube instance has configured Azure integration and its status is green. 1 for green, 0 otherwise .")
.register();
cePendingTasksTotal = Gauge.build()
.name("sonarqube_compute_engine_pending_tasks_total")
.help("Number of tasks at given point of time that were pending in the Compute Engine queue [SHARED, same value for every SonarQube instance]")
.register();
ceTasksRunningDuration = Summary.build()
.name("sonarqube_compute_engine_tasks_running_duration_seconds")
.help("Compute engine task running time in seconds")
.labelNames("task_type", "project_key")
.register();
computeEngineGauge = Gauge.build()
.name("sonarqube_health_compute_engine_status")
.help("Tells whether Compute Engine is up (healthy, ready to take tasks) or down. 1 for up, 0 for down")
.register();
elasticsearchGauge = Gauge.build()
.name("sonarqube_health_elasticsearch_status")
.help("Tells whether Elasticsearch is up or down. 1 for Up, 0 for down")
.register();
licenseDaysBeforeExpiration = Gauge.build()
.name("sonarqube_license_days_before_expiration_total")
.help("Days until the SonarQube license will expire.")
.register();
linesOfCodeRemaining = Gauge.build()
.name("sonarqube_license_number_of_lines_remaining_total")
.help("Number of lines remaining until the limit for the current license is hit.")
.register();
linesOfCodeAnalyzed = Gauge.build()
.name("sonarqube_license_number_of_lines_analyzed_total")
.help("Number of lines analyzed.")
.register();
elasticsearchDiskSpaceFreeBytesGauge = Gauge.build()
.name("sonarqube_elasticsearch_disk_space_free_bytes")
.help("Space left on device")
.labelNames("node_name")
.register();
elasticSearchDiskSpaceTotalBytes = Gauge.build()
.name("sonarqube_elasticsearch_disk_space_total_bytes")
.help("Total disk space on the device")
.labelNames("node_name")
.register();
webUptimeMinutes = Gauge.build()
.name("sonarqube_web_uptime_minutes")
.help("Number of minutes for how long the SonarQube instance is running")
.register();
numberOfConnectedSonarLintClients = Gauge.build()
.name("sonarqube_number_of_connected_sonarlint_clients")
.help("Number of connected SonarLint clients")
.register();
}
public void setGithubStatusToGreen() {
githubHealthIntegrationStatus.set(UP_STATUS);
}
public void setGithubStatusToRed() {
githubHealthIntegrationStatus.set(DOWN_STATUS);
}
public void setGitlabStatusToGreen() {
gitlabHealthIntegrationStatus.set(UP_STATUS);
}
public void setGitlabStatusToRed() {
gitlabHealthIntegrationStatus.set(DOWN_STATUS);
}
public void setAzureStatusToGreen() {
azureHealthIntegrationStatus.set(UP_STATUS);
}
public void setAzureStatusToRed() {
azureHealthIntegrationStatus.set(DOWN_STATUS);
}
public void setBitbucketStatusToGreen() {
bitbucketHealthIntegrationStatus.set(UP_STATUS);
}
public void setBitbucketStatusToRed() {
bitbucketHealthIntegrationStatus.set(DOWN_STATUS);
}
public void setNumberOfPendingTasks(int numberOfPendingTasks) {
cePendingTasksTotal.set(numberOfPendingTasks);
}
public void observeComputeEngineTaskDuration(long durationInSeconds, String taskType, String projectKey) {
ceTasksRunningDuration.labels(taskType, projectKey).observe(durationInSeconds);
}
public void setComputeEngineStatusToGreen() {
computeEngineGauge.set(UP_STATUS);
}
public void setComputeEngineStatusToRed() {
computeEngineGauge.set(DOWN_STATUS);
}
public void setElasticSearchStatusToGreen() {
elasticsearchGauge.set(UP_STATUS);
}
public void setElasticSearchStatusToRed() {
elasticsearchGauge.set(DOWN_STATUS);
}
public void setLicenseDayUntilExpire(long days) {
licenseDaysBeforeExpiration.set(days);
}
public void setLinesOfCodeRemaining(long loc) {
linesOfCodeRemaining.set(loc);
}
public void setLinesOfCodeAnalyzed(long loc) {
linesOfCodeAnalyzed.set(loc);
}
public void setElasticSearchDiskSpaceFreeBytes(String name, long diskAvailableBytes) {
elasticsearchDiskSpaceFreeBytesGauge.labels(name).set(diskAvailableBytes);
}
public void setElasticSearchDiskSpaceTotalBytes(String name, long diskTotalBytes) {
elasticSearchDiskSpaceTotalBytes.labels(name).set(diskTotalBytes);
}
public void setWebUptimeMinutes(long minutes) {
webUptimeMinutes.set(minutes);
}
public void setNumberOfConnectedSonarLintClients(long noOfClients) {
numberOfConnectedSonarLintClients.set(noOfClients);
}
}
| 7,562 | 34.013889 | 149 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/SonarLintConnectedClientsTask.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.sonar.api.config.Configuration;
import org.sonar.server.pushapi.sonarlint.SonarLintClientsRegistry;
public class SonarLintConnectedClientsTask implements MonitoringTask {
private static final String DELAY_IN_MILISECONDS_PROPERTY = "sonar.server.monitoring.other.initial.delay";
private static final String PERIOD_IN_MILISECONDS_PROPERTY = "sonar.server.monitoring.other.period";
private final ServerMonitoringMetrics serverMonitoringMetrics;
private final SonarLintClientsRegistry sonarLintClientsRegistry;
private final Configuration config;
public SonarLintConnectedClientsTask(ServerMonitoringMetrics serverMonitoringMetrics, SonarLintClientsRegistry sonarLintClientsRegistry,
Configuration configuration) {
this.serverMonitoringMetrics = serverMonitoringMetrics;
this.sonarLintClientsRegistry = sonarLintClientsRegistry;
this.config = configuration;
}
@Override
public void run() {
serverMonitoringMetrics.setNumberOfConnectedSonarLintClients(sonarLintClientsRegistry.countConnectedClients());
}
@Override
public long getDelay() {
return config.getLong(DELAY_IN_MILISECONDS_PROPERTY).orElse(10_000L);
}
@Override
public long getPeriod() {
return config.getLong(PERIOD_IN_MILISECONDS_PROPERTY).orElse(10_000L);
}
}
| 2,177 | 37.892857 | 138 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/WebUptimeTask.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.lang.management.ManagementFactory;
import org.sonar.api.config.Configuration;
public class WebUptimeTask implements MonitoringTask {
private static final String DELAY_IN_MILISECONDS_PROPERTY = "sonar.server.monitoring.webuptime.initial.delay";
private static final String PERIOD_IN_MILISECONDS_PROPERTY = "sonar.server.monitoring.webuptime.period";
private final ServerMonitoringMetrics metrics;
private final Configuration config;
public WebUptimeTask(ServerMonitoringMetrics metrics, Configuration configuration) {
this.metrics = metrics;
this.config = configuration;
}
@Override
public long getDelay() {
return config.getLong(DELAY_IN_MILISECONDS_PROPERTY).orElse(10_000L);
}
@Override
public long getPeriod() {
return config.getLong(PERIOD_IN_MILISECONDS_PROPERTY).orElse(5_000L);
}
@Override
public void run() {
long javaUptimeInMilliseconds = ManagementFactory.getRuntimeMXBean().getUptime();
metrics.setWebUptimeMinutes(javaUptimeInMilliseconds / (1000 * 60));
}
}
| 1,926 | 34.685185 | 112 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/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.monitoring;
import javax.annotation.ParametersAreNonnullByDefault;
| 968 | 37.76 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/ce/ComputeEngineMetricsTask.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.sonar.api.config.Configuration;
import org.sonar.db.DbClient;
import org.sonar.server.monitoring.MonitoringTask;
import org.sonar.server.monitoring.ServerMonitoringMetrics;
public abstract class ComputeEngineMetricsTask implements MonitoringTask {
private static final String DELAY_IN_MILISECONDS_PROPERTY = "sonar.server.monitoring.ce.initial.delay";
private static final String PERIOD_IN_MILISECONDS_PROPERTY = "sonar.server.monitoring.ce.period";
protected final DbClient dbClient;
protected final ServerMonitoringMetrics metrics;
private final Configuration config;
protected ComputeEngineMetricsTask(DbClient dbClient, ServerMonitoringMetrics metrics, Configuration config) {
this.dbClient = dbClient;
this.metrics = metrics;
this.config = config;
}
@Override
public long getDelay() {
return config.getLong(DELAY_IN_MILISECONDS_PROPERTY).orElse(10_000L);
}
@Override
public long getPeriod() {
return config.getLong(PERIOD_IN_MILISECONDS_PROPERTY).orElse(30_000L);
}
}
| 1,921 | 35.264151 | 112 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/ce/NumberOfTasksInQueueTask.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.sonar.api.config.Configuration;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.ce.CeQueueDto;
import org.sonar.server.monitoring.ServerMonitoringMetrics;
public class NumberOfTasksInQueueTask extends ComputeEngineMetricsTask {
public NumberOfTasksInQueueTask(DbClient dbClient, ServerMonitoringMetrics metrics, Configuration config) {
super(dbClient, metrics, config);
}
@Override
public void run() {
try (DbSession dbSession = dbClient.openSession(false)) {
int size = dbClient.ceQueueDao().countByStatus(dbSession, CeQueueDto.Status.PENDING);
metrics.setNumberOfPendingTasks(size);
}
}
}
| 1,557 | 35.232558 | 109 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/ce/RecentTasksDurationTask.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.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.sonar.api.config.Configuration;
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.ce.CeActivityDto;
import org.sonar.db.entity.EntityDto;
import org.sonar.server.monitoring.ServerMonitoringMetrics;
import static java.util.Objects.requireNonNull;
public class RecentTasksDurationTask extends ComputeEngineMetricsTask {
private static final Logger LOGGER = LoggerFactory.getLogger(RecentTasksDurationTask.class);
private final System2 system;
private long lastUpdatedTimestamp;
public RecentTasksDurationTask(DbClient dbClient, ServerMonitoringMetrics metrics, Configuration config,
System2 system) {
super(dbClient, metrics, config);
this.system = system;
this.lastUpdatedTimestamp = system.now();
}
@Override
public void run() {
try (DbSession dbSession = dbClient.openSession(false)) {
List<CeActivityDto> recentSuccessfulTasks = getRecentSuccessfulTasks(dbSession);
Collection<String> entityUuids = recentSuccessfulTasks.stream()
.map(CeActivityDto::getEntityUuid)
.toList();
List<EntityDto> entities = dbClient.entityDao().selectByUuids(dbSession, entityUuids);
Map<String, String> entityUuidAndKeys = entities.stream()
.collect(Collectors.toMap(EntityDto::getUuid, EntityDto::getKey));
reportObservedDurationForTasks(recentSuccessfulTasks, entityUuidAndKeys);
}
lastUpdatedTimestamp = system.now();
}
private List<CeActivityDto> getRecentSuccessfulTasks(DbSession dbSession) {
List<CeActivityDto> recentTasks = dbClient.ceActivityDao().selectNewerThan(dbSession, lastUpdatedTimestamp);
return recentTasks.stream()
.filter(c -> c.getStatus() == CeActivityDto.Status.SUCCESS)
.toList();
}
private void reportObservedDurationForTasks(List<CeActivityDto> tasks, Map<String, String> entityUuidAndKeys) {
for (CeActivityDto task : tasks) {
String mainComponentUuid = task.getEntityUuid();
Long executionTimeMs = task.getExecutionTimeMs();
try {
requireNonNull(mainComponentUuid);
requireNonNull(executionTimeMs);
String mainComponentKey = entityUuidAndKeys.get(mainComponentUuid);
requireNonNull(mainComponentKey);
metrics.observeComputeEngineTaskDuration(executionTimeMs, task.getTaskType(), mainComponentKey);
} catch (RuntimeException e) {
LOGGER.warn("Can't report metric data for a CE task with component uuid " + mainComponentUuid, e);
}
}
}
}
| 3,602 | 36.926316 | 113 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/ce/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.monitoring.ce;
import javax.annotation.ParametersAreNonnullByDefault;
| 971 | 37.88 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/devops/AzureMetricsTask.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.List;
import org.sonar.alm.client.azure.AzureDevOpsValidator;
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.AlmSettingDto;
import org.sonar.server.monitoring.ServerMonitoringMetrics;
public class AzureMetricsTask extends DevOpsMetricsTask {
private final AzureDevOpsValidator azureDevOpsValidator;
public AzureMetricsTask(ServerMonitoringMetrics metrics, AzureDevOpsValidator azureDevOpsValidator,
DbClient dbClient, Configuration config) {
super(dbClient, metrics, config);
this.azureDevOpsValidator = azureDevOpsValidator;
}
@Override
public void run() {
try (DbSession dbSession = dbClient.openSession(false)) {
List<AlmSettingDto> azureSettingsDtos = dbClient.almSettingDao().selectByAlm(dbSession, ALM.AZURE_DEVOPS);
if (azureSettingsDtos.isEmpty()) {
metrics.setAzureStatusToRed();
return;
}
validate(azureSettingsDtos);
}
}
private void validate(List<AlmSettingDto> almSettingDtos) {
try {
for (AlmSettingDto dto : almSettingDtos) {
azureDevOpsValidator.validate(dto);
}
metrics.setAzureStatusToGreen();
} catch (Exception e) {
metrics.setAzureStatusToRed();
}
}
}
| 2,231 | 32.818182 | 112 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/devops/BitbucketMetricsTask.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.List;
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.AlmSettingDto;
import org.sonar.server.monitoring.ServerMonitoringMetrics;
public class BitbucketMetricsTask extends DevOpsMetricsTask {
private final BitbucketCloudValidator bitbucketCloudValidator;
private final BitbucketServerSettingsValidator bitbucketServerValidator;
public BitbucketMetricsTask(ServerMonitoringMetrics metrics, BitbucketCloudValidator bitbucketCloudValidator,
BitbucketServerSettingsValidator bitbucketServerSettingsValidator, DbClient dbClient, Configuration config) {
super(dbClient, metrics, config);
this.bitbucketCloudValidator = bitbucketCloudValidator;
this.bitbucketServerValidator = bitbucketServerSettingsValidator;
}
@Override
public void run() {
try (DbSession dbSession = dbClient.openSession(false)) {
List<AlmSettingDto> bitbucketServerDtos = dbClient.almSettingDao().selectByAlm(dbSession, ALM.BITBUCKET);
List<AlmSettingDto> bitbucketCloudDtos = dbClient.almSettingDao().selectByAlm(dbSession, ALM.BITBUCKET_CLOUD);
if (bitbucketServerDtos.isEmpty() && bitbucketCloudDtos.isEmpty()) {
metrics.setBitbucketStatusToRed();
return;
}
try {
validate(bitbucketServerDtos, bitbucketCloudDtos);
metrics.setBitbucketStatusToGreen();
} catch (RuntimeException e) {
metrics.setBitbucketStatusToRed();
}
}
}
private void validate(List<AlmSettingDto> bitbucketServerDtos, List<AlmSettingDto> bitbucketCloudDtos) {
for (AlmSettingDto dto : bitbucketServerDtos) {
bitbucketServerValidator.validate(dto);
}
for (AlmSettingDto dto : bitbucketCloudDtos) {
bitbucketCloudValidator.validate(dto);
}
}
}
| 2,923 | 38.513514 | 116 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/devops/DevOpsMetricsTask.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 org.sonar.api.config.Configuration;
import org.sonar.db.DbClient;
import org.sonar.server.monitoring.MonitoringTask;
import org.sonar.server.monitoring.ServerMonitoringMetrics;
public abstract class DevOpsMetricsTask implements MonitoringTask {
private static final String DELAY_IN_MILISECONDS_PROPERTY = "sonar.server.monitoring.devops.initial.delay";
private static final String PERIOD_IN_MILISECONDS_PROPERTY = "sonar.server.monitoring.devops.period";
protected final DbClient dbClient;
protected final ServerMonitoringMetrics metrics;
private final Configuration config;
protected DevOpsMetricsTask(DbClient dbClient, ServerMonitoringMetrics metrics, Configuration config) {
this.dbClient = dbClient;
this.metrics = metrics;
this.config = config;
}
@Override
public long getDelay() {
return config.getLong(DELAY_IN_MILISECONDS_PROPERTY).orElse(10_000L);
}
@Override
public long getPeriod() {
return config.getLong(PERIOD_IN_MILISECONDS_PROPERTY).orElse(300_000L);
}
}
| 1,920 | 35.245283 | 109 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/devops/GithubMetricsTask.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.List;
import org.sonar.alm.client.github.GithubGlobalSettingsValidator;
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.AlmSettingDto;
import org.sonar.server.monitoring.ServerMonitoringMetrics;
public class GithubMetricsTask extends DevOpsMetricsTask {
private final GithubGlobalSettingsValidator githubValidator;
public GithubMetricsTask(ServerMonitoringMetrics metrics, GithubGlobalSettingsValidator githubValidator,
DbClient dbClient, Configuration config) {
super(dbClient, metrics, config);
this.githubValidator = githubValidator;
}
@Override
public void run() {
try (DbSession dbSession = dbClient.openSession(false)) {
List<AlmSettingDto> githubSettingsDtos = dbClient.almSettingDao().selectByAlm(dbSession, ALM.GITHUB);
if (githubSettingsDtos.isEmpty()) {
metrics.setGithubStatusToRed();
return;
}
validateGithub(githubSettingsDtos);
}
}
private void validateGithub(List<AlmSettingDto> almSettingDtos) {
try {
for (AlmSettingDto dto : almSettingDtos) {
githubValidator.validate(dto);
}
metrics.setGithubStatusToGreen();
} catch (RuntimeException e) {
metrics.setGithubStatusToRed();
}
}
}
| 2,255 | 33.181818 | 107 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/devops/GitlabMetricsTask.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.List;
import org.sonar.alm.client.gitlab.GitlabGlobalSettingsValidator;
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.AlmSettingDto;
import org.sonar.server.monitoring.ServerMonitoringMetrics;
public class GitlabMetricsTask extends DevOpsMetricsTask {
private final GitlabGlobalSettingsValidator gitlabValidator;
public GitlabMetricsTask(ServerMonitoringMetrics metrics, GitlabGlobalSettingsValidator gitlabValidator,
DbClient dbClient, Configuration config) {
super(dbClient, metrics, config);
this.gitlabValidator = gitlabValidator;
}
@Override
public void run() {
try (DbSession dbSession = dbClient.openSession(false)) {
List<AlmSettingDto> gitlabSettingsDtos = dbClient.almSettingDao().selectByAlm(dbSession, ALM.GITLAB);
if (gitlabSettingsDtos.isEmpty()) {
metrics.setGitlabStatusToRed();
return;
}
validateGitlab(gitlabSettingsDtos);
}
}
private void validateGitlab(List<AlmSettingDto> almSettingDtos) {
try {
for (AlmSettingDto dto : almSettingDtos) {
gitlabValidator.validate(dto);
}
metrics.setGitlabStatusToGreen();
} catch (RuntimeException e) {
metrics.setGitlabStatusToRed();
}
}
}
| 2,255 | 33.181818 | 107 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/main/java/org/sonar/server/monitoring/devops/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.monitoring.devops;
import javax.annotation.ParametersAreNonnullByDefault;
| 975 | 38.04 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/ComputeEngineMetricStatusTaskTest.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.CollectorRegistry;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.app.ProcessCommandWrapper;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class ComputeEngineMetricStatusTaskTest {
private final ServerMonitoringMetrics serverMonitoringMetrics = mock(ServerMonitoringMetrics.class);
private final ProcessCommandWrapper processCommandWrapper = mock(ProcessCommandWrapper.class);
private final Configuration configuration = new MapSettings().asConfig();
private final ComputeEngineMetricStatusTask underTest = new ComputeEngineMetricStatusTask(serverMonitoringMetrics, processCommandWrapper, configuration);
@Before
public void before() {
CollectorRegistry.defaultRegistry.clear();
}
@Test
public void when_compute_engine_up_status_is_updated_to_green() {
when(processCommandWrapper.isCeOperational()).thenReturn(true);
underTest.run();
verify(serverMonitoringMetrics, times(1)).setComputeEngineStatusToGreen();
verifyNoMoreInteractions(serverMonitoringMetrics);
}
@Test
public void when_compute_engine_down_status_is_updated_to_red() {
when(processCommandWrapper.isCeOperational()).thenReturn(false);
underTest.run();
verify(serverMonitoringMetrics, times(1)).setComputeEngineStatusToRed();
verifyNoMoreInteractions(serverMonitoringMetrics);
}
@Test
public void task_has_default_delay(){
Assertions.assertThat(underTest.getDelay()).isPositive();
Assertions.assertThat(underTest.getPeriod()).isPositive();
}
}
| 2,747 | 35.157895 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-monitoring/src/test/java/org/sonar/server/monitoring/ElasticSearchMetricTaskTest.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 com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.prometheus.client.CollectorRegistry;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import org.assertj.core.api.Assertions;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import org.slf4j.event.Level;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.internal.apachecommons.io.IOUtils;
import org.sonar.api.internal.apachecommons.lang.StringUtils;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.response.NodeStatsResponse;
import static org.assertj.core.api.Assertions.assertThat;
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.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class ElasticSearchMetricTaskTest {
@Rule
public LogTester logTester = new LogTester();
private final ServerMonitoringMetrics serverMonitoringMetrics = mock(ServerMonitoringMetrics.class);
private final EsClient esClient = mock(EsClient.class);
private final Configuration configuration = new MapSettings().asConfig();
private final ElasticSearchMetricTask underTest = new ElasticSearchMetricTask(serverMonitoringMetrics, esClient, configuration);
@Before
public void before() {
CollectorRegistry.defaultRegistry.clear();
}
@Test
public void when_elasticsearch_up_status_is_updated_to_green() {
ClusterHealthResponse clusterHealthResponse = new ClusterHealthResponse();
clusterHealthResponse.setStatus(ClusterHealthStatus.GREEN);
when(esClient.clusterHealth(any())).thenReturn(clusterHealthResponse);
underTest.run();
verify(serverMonitoringMetrics, times(1)).setElasticSearchStatusToGreen();
verifyNoMoreInteractions(serverMonitoringMetrics);
}
@Test
public void elasticsearch_free_disk_space_is_updated() throws IOException {
URL esNodeResponseUrl = getClass().getResource("es-node-response.json");
String jsonPayload = StringUtils.trim(IOUtils.toString(esNodeResponseUrl, StandardCharsets.UTF_8));
JsonObject jsonObject = new Gson().fromJson(jsonPayload, JsonObject.class);
NodeStatsResponse nodeStats = NodeStatsResponse.toNodeStatsResponse(jsonObject);
when(esClient.nodesStats()).thenReturn(nodeStats);
underTest.run();
String nodeName = nodeStats.getNodeStats().get(0).getName();
verify(serverMonitoringMetrics, times(1)).setElasticSearchDiskSpaceFreeBytes(nodeName, 136144027648L);
verify(serverMonitoringMetrics, times(1)).setElasticSearchDiskSpaceTotalBytes(nodeName, 250685575168L);
// elasticsearch health status is not mocked in this test, so this part raise an exception
assertThat(logTester.logs()).hasSize(1);
assertThat(logTester.logs(Level.ERROR)).containsOnly("Failed to query ES status");
}
@Test
public void when_elasticsearch_yellow_status_is_updated_to_green() {
ClusterHealthResponse clusterHealthResponse = new ClusterHealthResponse();
clusterHealthResponse.setStatus(ClusterHealthStatus.YELLOW);
when(esClient.clusterHealth(any())).thenReturn(clusterHealthResponse);
underTest.run();
verify(serverMonitoringMetrics, times(1)).setElasticSearchStatusToGreen();
verifyNoMoreInteractions(serverMonitoringMetrics);
}
@Test
public void when_elasticsearch_down_status_is_updated_to_red() {
ClusterHealthResponse clusterHealthResponse = new ClusterHealthResponse();
clusterHealthResponse.setStatus(ClusterHealthStatus.RED);
when(esClient.clusterHealth(any())).thenReturn(clusterHealthResponse);
underTest.run();
verify(serverMonitoringMetrics, times(1)).setElasticSearchStatusToRed();
verifyNoMoreInteractions(serverMonitoringMetrics);
}
@Test
public void when_no_es_status_null_status_is_updated_to_red() {
ClusterHealthResponse clusterHealthResponse = Mockito.mock(ClusterHealthResponse.class);
when(clusterHealthResponse.getStatus()).thenReturn(null);
when(esClient.clusterHealth(any())).thenReturn(clusterHealthResponse);
underTest.run();
verify(serverMonitoringMetrics, times(1)).setElasticSearchStatusToRed();
verifyNoMoreInteractions(serverMonitoringMetrics);
}
@Test
public void when_es_status_throw_exception_status_is_updated_to_red() {
when(esClient.clusterHealth(any())).thenThrow(new IllegalStateException("exception in cluster health"));
underTest.run();
verify(serverMonitoringMetrics, times(1)).setElasticSearchStatusToRed();
verifyNoMoreInteractions(serverMonitoringMetrics);
assertThat(logTester.logs()).hasSize(2);
assertThat(logTester.logs(Level.ERROR)).containsOnly("Failed to query ES status");
}
@Test
public void task_has_default_delay(){
Assertions.assertThat(underTest.getDelay()).isPositive();
Assertions.assertThat(underTest.getPeriod()).isPositive();
}
}
| 6,151 | 37.691824 | 130 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.